Merge branch '21128-toolbar-context-menu'
[arvados-workbench2.git] / src / models / tree.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { pipe, map, reduce } from 'lodash/fp';
6 export type Tree<T> = Record<string, TreeNode<T>>;
7
8 export const TREE_ROOT_ID = '';
9
10 export interface TreeNode<T = any> {
11     children: string[];
12     value: T;
13     id: string;
14     parent: string;
15     active: boolean;
16     selected: boolean;
17     initialState?: boolean;
18     expanded: boolean;
19     status: TreeNodeStatus;
20 }
21
22 export enum TreeNodeStatus {
23     INITIAL = 'INITIAL',
24     PENDING = 'PENDING',
25     LOADED = 'LOADED',
26 }
27
28 export enum TreePickerId {
29     PROJECTS = 'Projects',
30     SHARED_WITH_ME = 'Shared with me',
31     FAVORITES = 'Favorites',
32     PUBLIC_FAVORITES = 'Public Favorites'
33 }
34
35 export const createTree = <T>(): Tree<T> => ({});
36
37 export const getNode = (id: string) => <T>(tree: Tree<T>): TreeNode<T> | undefined => tree[id];
38
39 export const appendSubtree = <T>(id: string, subtree: Tree<T>) => (tree: Tree<T>) =>
40     pipe(
41         getNodeDescendants(''),
42         map(node => node.parent === '' ? { ...node, parent: id } : node),
43         reduce((newTree, node) => setNode(node)(newTree), tree)
44     )(subtree) as Tree<T>;
45
46 export const setNode = <T>(node: TreeNode<T>) => (tree: Tree<T>): Tree<T> => {
47     if (tree[node.id] && tree[node.id] === node) { return tree; }
48
49     tree[node.id] = node;
50     if (tree[node.parent]) {
51         tree[node.parent].children = Array.from(new Set([...tree[node.parent].children, node.id]));
52     }
53     return tree;
54 };
55
56 export const getNodeValue = (id: string) => <T>(tree: Tree<T>) => {
57     const node = getNode(id)(tree);
58     return node ? node.value : undefined;
59 };
60
61 export const setNodeValue = (id: string) => <T>(value: T) => (tree: Tree<T>) => {
62     const node = getNode(id)(tree);
63     return node
64         ? setNode(mapNodeValue(() => value)(node))(tree)
65         : tree;
66 };
67
68 export const setNodeValueWith = <T>(mapFn: (value: T) => T) => (id: string) => (tree: Tree<T>) => {
69     const node = getNode(id)(tree);
70     return node
71         ? setNode(mapNodeValue(mapFn)(node))(tree)
72         : tree;
73 };
74
75 export const mapTreeValues = <T, R>(mapFn: (value: T) => R) => (tree: Tree<T>): Tree<R> =>
76     getNodeDescendantsIds('')(tree)
77         .map(id => getNode(id)(tree))
78         .filter(node => !!node)
79         .map(mapNodeValue(mapFn))
80         .reduce((newTree, node) => setNode(node)(newTree), createTree<R>());
81
82 export const mapTree = <T, R = T>(mapFn: (node: TreeNode<T>) => TreeNode<R>) => (tree: Tree<T>): Tree<R> =>
83     getNodeDescendantsIds('')(tree)
84         .map(id => getNode(id)(tree))
85         .map(mapFn)
86         .reduce((newTree, node) => setNode(node)(newTree), createTree<R>());
87
88 export const getNodeAncestors = (id: string) => <T>(tree: Tree<T>) =>
89     mapIdsToNodes(getNodeAncestorsIds(id)(tree))(tree);
90
91
92 export const getNodeAncestorsIds = (id: string) => <T>(tree: Tree<T>): string[] => {
93     const node = getNode(id)(tree);
94     return node && node.parent
95         ? [...getNodeAncestorsIds(node.parent)(tree), node.parent]
96         : [];
97 };
98
99 export const getNodeDescendants = (id: string, limit = Infinity) => <T>(tree: Tree<T>) =>
100     mapIdsToNodes(getNodeDescendantsIds(id, limit)(tree))(tree);
101
102 export const countNodes = <T>(tree: Tree<T>) =>
103     getNodeDescendantsIds('')(tree).length;
104
105 export const countChildren = (id: string) => <T>(tree: Tree<T>) =>
106     getNodeChildren('')(tree).length;
107
108 export const getNodeDescendantsIds = (id: string, limit = Infinity) => <T>(tree: Tree<T>): string[] => {
109     const node = getNode(id)(tree);
110     const children = node ? node.children :
111         id === TREE_ROOT_ID
112             ? getRootNodeChildrenIds(tree)
113             : [];
114
115     return children
116         .concat(limit < 1
117             ? []
118             : children
119                 .map(id => getNodeDescendantsIds(id, limit - 1)(tree))
120                 .reduce((nodes, nodeChildren) => [...nodes, ...nodeChildren], []));
121 };
122
123 export const getNodeChildren = (id: string) => <T>(tree: Tree<T>) =>
124     mapIdsToNodes(getNodeChildrenIds(id)(tree))(tree);
125
126 export const getNodeChildrenIds = (id: string) => <T>(tree: Tree<T>): string[] =>
127     getNodeDescendantsIds(id, 0)(tree);
128
129 export const mapIdsToNodes = (ids: string[]) => <T>(tree: Tree<T>) =>
130     ids.map(id => getNode(id)(tree)).filter((node): node is TreeNode<T> => node !== undefined);
131
132 export const activateNode = (id: string) => <T>(tree: Tree<T>) =>
133     mapTree((node: TreeNode<T>) => node.id === id ? { ...node, active: true } : { ...node, active: false })(tree);
134
135 export const deactivateNode = <T>(tree: Tree<T>) =>
136     mapTree((node: TreeNode<T>) => node.active ? { ...node, active: false } : node)(tree);
137
138 export const expandNode = (...ids: string[]) => <T>(tree: Tree<T>) =>
139     mapTree((node: TreeNode<T>) => ids.some(id => id === node.id) ? { ...node, expanded: true } : node)(tree);
140
141 export const expandNodeAncestors = (...ids: string[]) => <T>(tree: Tree<T>) => {
142     const ancestors = ids.reduce((acc, id): string[] => ([...acc, ...getNodeAncestorsIds(id)(tree)]), [] as string[]);
143     return mapTree((node: TreeNode<T>) => ancestors.some(id => id === node.id) ? { ...node, expanded: true } : node)(tree);
144 }
145
146 export const collapseNode = (...ids: string[]) => <T>(tree: Tree<T>) =>
147     mapTree((node: TreeNode<T>) => ids.some(id => id === node.id) ? { ...node, expanded: false } : node)(tree);
148
149 export const toggleNodeCollapse = (...ids: string[]) => <T>(tree: Tree<T>) =>
150     mapTree((node: TreeNode<T>) => ids.some(id => id === node.id) ? { ...node, expanded: !node.expanded } : node)(tree);
151
152 export const setNodeStatus = (id: string) => (status: TreeNodeStatus) => <T>(tree: Tree<T>) => {
153     const node = getNode(id)(tree);
154     return node
155         ? setNode({ ...node, status })(tree)
156         : tree;
157 };
158
159 export const toggleNodeSelection = (id: string, cascade: boolean) => <T>(tree: Tree<T>) => {
160     const node = getNode(id)(tree);
161
162     return node
163         ? cascade
164             ? pipe(
165                 setNode({ ...node, selected: !node.selected }),
166                 toggleAncestorsSelection(id),
167                 toggleDescendantsSelection(id))(tree)
168             : setNode({ ...node, selected: !node.selected })(tree)
169         : tree;
170 };
171
172 export const selectNode = (id: string, cascade: boolean) => <T>(tree: Tree<T>) => {
173     const node = getNode(id)(tree);
174     return node && node.selected
175         ? tree
176         : toggleNodeSelection(id, cascade)(tree);
177 };
178
179 export const selectNodes = (id: string | string[], cascade: boolean) => <T>(tree: Tree<T>) => {
180     const ids = typeof id === 'string' ? [id] : id;
181     return ids.reduce((tree, id) => selectNode(id, cascade)(tree), tree);
182 };
183 export const deselectNode = (id: string, cascade: boolean) => <T>(tree: Tree<T>) => {
184     const node = getNode(id)(tree);
185     return node && node.selected
186         ? toggleNodeSelection(id, cascade)(tree)
187         : tree;
188 };
189
190 export const deselectNodes = (id: string | string[], cascade: boolean) => <T>(tree: Tree<T>) => {
191     const ids = typeof id === 'string' ? [id] : id;
192     return ids.reduce((tree, id) => deselectNode(id, cascade)(tree), tree);
193 };
194
195 export const getSelectedNodes = <T>(tree: Tree<T>) =>
196     getNodeDescendants('')(tree)
197         .filter(node => node.selected);
198
199 export const initTreeNode = <T>(data: Pick<TreeNode<T>, 'id' | 'value'> & { parent?: string }): TreeNode<T> => ({
200     children: [],
201     active: false,
202     selected: false,
203     expanded: false,
204     status: TreeNodeStatus.INITIAL,
205     parent: '',
206     ...data,
207 });
208
209 export const getTreeDirty = (id: string) => <T>(tree: Tree<T>): boolean => {
210     const node = getNode(id)(tree);
211     const children = getNodeDescendants(id)(tree);
212     return (node
213             && node.initialState !== undefined
214             && node.selected !== node.initialState
215             )
216             || children.some(child =>
217                 child.initialState !== undefined
218                 && child.selected !== child.initialState
219             );
220 }
221
222 const toggleDescendantsSelection = (id: string) => <T>(tree: Tree<T>) => {
223     const node = getNode(id)(tree);
224     if (node) {
225         return getNodeDescendants(id)(tree)
226             .reduce((newTree, subNode) =>
227                 setNode({ ...subNode, selected: node.selected })(newTree),
228                 tree);
229     }
230     return tree;
231 };
232
233 const toggleAncestorsSelection = (id: string) => <T>(tree: Tree<T>) => {
234     const ancestors = getNodeAncestorsIds(id)(tree).reverse();
235     return ancestors.reduce((newTree, parent) => parent ? toggleParentNodeSelection(parent)(newTree) : newTree, tree);
236 };
237
238 const toggleParentNodeSelection = (id: string) => <T>(tree: Tree<T>) => {
239     const node = getNode(id)(tree);
240     if (node) {
241         const parentNode = getNode(node.id)(tree);
242         if (parentNode) {
243             const selected = parentNode.children
244                 .map(id => getNode(id)(tree))
245                 .every(node => node !== undefined && node.selected);
246             return setNode({ ...parentNode, selected })(tree);
247         }
248         return setNode(node)(tree);
249     }
250     return tree;
251 };
252
253 const mapNodeValue = <T, R>(mapFn: (value: T) => R) => (node: TreeNode<T>): TreeNode<R> =>
254     ({ ...node, value: mapFn(node.value) });
255
256 const getRootNodeChildrenIds = <T>(tree: Tree<T>) =>
257     Object
258         .keys(tree)
259         .filter(id => getNode(id)(tree)!.parent === TREE_ROOT_ID);