Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { PayloadAction, createSlice } from '@reduxjs/toolkit'
export enum CollapseValues {
TOGGLE,
FALSE,
TRUE
}
const CollapseActions = {
[CollapseValues.TOGGLE]: (collapse: boolean) => { return collapse = !collapse },
[CollapseValues.FALSE]: () => { return false },
[CollapseValues.TRUE]: () => { return true },
}
type Identifier = {
key: string,
nested: number
}
// containg object location and collapsed information
interface CollapsedItem {
identifier: Identifier
collapsed: boolean
}
export interface ReducerState {
breadcrumbs: Array<string>,
/**
* Meta container containg identifier of
* all non collapsed json objects
*/
collapseContainer: Array<CollapsedItem>
}
const initialState: ReducerState = {
breadcrumbs: [],
collapseContainer: [],
}
export const compareIdentifier = (a: Identifier, b: Identifier): boolean => {
return a.key === b.key && a.nested === b.nested;
}
/**
* Every component instance has its own id.
* This id is getting used as key to define the respective object container
*/
const JsonViewerSlice = createSlice({
name: 'json_viewer',
initialState,
reducers: {
toggleCollapse: (state, { payload }: PayloadAction<{ identifier: Identifier, collapse: CollapseValues }>) => {
const { identifier, collapse } = payload
// potentially find already collapsed
const i = state.collapseContainer.findIndex(i => compareIdentifier(identifier, i.identifier))
if (i === -1) {
// create new collapse
const newItem = { identifier, collapsed: true }
state.collapseContainer = [...state.collapseContainer, newItem]
return;
}
// update nested attribute
state.collapseContainer = state.collapseContainer.map((item, index) => {
if (index !== i) {
return item
}
return {
...item,
collapsed: CollapseActions[collapse](item.collapsed)
}
})
},
setBreadcrumbs: (state, { payload }: PayloadAction<Array<string>>) => {
state.breadcrumbs = payload
},
},
})
export const { toggleCollapse, setBreadcrumbs } = JsonViewerSlice.actions
export default JsonViewerSlice.reducer