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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
const getDefaultState = () => {
return {
children: [],
ordered: [],
};
};
const initialState = getDefaultState();
const state = { ...initialState };
const getters = {
children(state) {
return (id) => state.children[id] ?? [];
},
ordered(state) {
return state.ordered;
},
};
export const mutations = {
reset(state) {
Object.assign(state, getDefaultState());
},
setChildren(state, children) {
state.children = children;
},
setOrdered(state, ordered) {
state.ordered = ordered;
},
};
const actions = {
build({commit, rootGetters }) {
const context = rootGetters['context'];
const structuralElements = rootGetters['courseware-structural-elements/all'];
const children = structuralElements.reduce((memo, element) => {
const parent = element.relationships.parent?.data?.id ?? null;
if (parent) {
if (!memo[parent]) {
memo[parent] = [];
}
memo[parent].push([element.id, element.attributes.position]);
}
return memo;
}, {});
for (const key of Object.keys(children)) {
children[key].sort((childA, childB) => childA[1] - childB[1]);
children[key] = children[key].map(([id]) => id);
}
commit('setChildren', children);
const ordered = [...visitTree(children, context.rootId)];
commit('setOrdered', ordered);
},
async load({ dispatch, rootGetters }) {
const context = rootGetters['context'];
await dispatch('courseware-structural-elements/loadById', {
id: context.rootId,
options: {
include: 'containers,containers.blocks',
},
}, { root: true });
const root = rootGetters['courseware-structural-elements/byId']({id: context.rootId});
await dispatch('loadDescendants', { root });
},
loadDescendants({ dispatch }, { root }) {
const parent = { id: root.id, type: root.type };
const relationship = 'descendants';
const options = {
'page[offset]': 0,
'page[limit]': 10000,
};
return dispatch(
'courseware-structural-elements/loadRelated',
{ parent, relationship, options },
{ root: true }
);
},
};
function* visitTree(tree, current) {
if (current) {
yield current;
const children = tree[current];
if (children) {
for (let index = 0; index < children.length; index++) {
yield* visitTree(tree, children[index]);
}
}
}
}
export default {
namespaced: true,
actions,
getters,
mutations,
state,
};
|