Merge branch '18128-multi-panel-view' into main. Closes #18128.
[arvados-workbench2.git] / src / store / tree-picker / tree-picker-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { unionize, ofType, UnionOf } from "common/unionize";
6 import { TreeNode, initTreeNode, getNodeDescendants, TreeNodeStatus, getNode, TreePickerId, Tree } from 'models/tree';
7 import { createCollectionFilesTree } from "models/collection-file";
8 import { Dispatch } from 'redux';
9 import { RootState } from 'store/store';
10 import { getUserUuid } from "common/getuser";
11 import { ServiceRepository } from 'services/services';
12 import { FilterBuilder } from 'services/api/filter-builder';
13 import { pipe, values } from 'lodash/fp';
14 import { ResourceKind } from 'models/resource';
15 import { GroupContentsResource } from 'services/groups-service/groups-service';
16 import { getTreePicker, TreePicker } from './tree-picker';
17 import { ProjectsTreePickerItem } from 'views-components/projects-tree-picker/generic-projects-tree-picker';
18 import { OrderBuilder } from 'services/api/order-builder';
19 import { ProjectResource } from 'models/project';
20 import { mapTree } from '../../models/tree';
21 import { LinkResource, LinkClass } from "models/link";
22 import { mapTreeValues } from "models/tree";
23 import { sortFilesTree } from "services/collection-service/collection-service-files-response";
24 import { GroupClass, GroupResource } from "models/group";
25
26 export const treePickerActions = unionize({
27     LOAD_TREE_PICKER_NODE: ofType<{ id: string, pickerId: string }>(),
28     LOAD_TREE_PICKER_NODE_SUCCESS: ofType<{ id: string, nodes: Array<TreeNode<any>>, pickerId: string }>(),
29     APPEND_TREE_PICKER_NODE_SUBTREE: ofType<{ id: string, subtree: Tree<any>, pickerId: string }>(),
30     TOGGLE_TREE_PICKER_NODE_COLLAPSE: ofType<{ id: string, pickerId: string }>(),
31     ACTIVATE_TREE_PICKER_NODE: ofType<{ id: string, pickerId: string, relatedTreePickers?: string[] }>(),
32     DEACTIVATE_TREE_PICKER_NODE: ofType<{ pickerId: string }>(),
33     TOGGLE_TREE_PICKER_NODE_SELECTION: ofType<{ id: string, pickerId: string }>(),
34     SELECT_TREE_PICKER_NODE: ofType<{ id: string | string[], pickerId: string }>(),
35     DESELECT_TREE_PICKER_NODE: ofType<{ id: string | string[], pickerId: string }>(),
36     EXPAND_TREE_PICKER_NODES: ofType<{ ids: string[], pickerId: string }>(),
37     RESET_TREE_PICKER: ofType<{ pickerId: string }>()
38 });
39
40 export type TreePickerAction = UnionOf<typeof treePickerActions>;
41
42 export const getProjectsTreePickerIds = (pickerId: string) => ({
43     home: `${pickerId}_home`,
44     shared: `${pickerId}_shared`,
45     favorites: `${pickerId}_favorites`,
46     publicFavorites: `${pickerId}_publicFavorites`
47 });
48
49 export const getAllNodes = <Value>(pickerId: string, filter = (node: TreeNode<Value>) => true) => (state: TreePicker) =>
50     pipe(
51         () => values(getProjectsTreePickerIds(pickerId)),
52
53         ids => ids
54             .map(id => getTreePicker<Value>(id)(state)),
55
56         trees => trees
57             .map(getNodeDescendants(''))
58             .reduce((allNodes, nodes) => allNodes.concat(nodes), []),
59
60         allNodes => allNodes
61             .reduce((map, node) =>
62                 filter(node)
63                     ? map.set(node.id, node)
64                     : map, new Map<string, TreeNode<Value>>())
65             .values(),
66
67         uniqueNodes => Array.from(uniqueNodes),
68     )();
69 export const getSelectedNodes = <Value>(pickerId: string) => (state: TreePicker) =>
70     getAllNodes<Value>(pickerId, node => node.selected)(state);
71
72 export const initProjectsTreePicker = (pickerId: string) =>
73     async (dispatch: Dispatch, _: () => RootState, services: ServiceRepository) => {
74         const { home, shared, favorites, publicFavorites } = getProjectsTreePickerIds(pickerId);
75         dispatch<any>(initUserProject(home));
76         dispatch<any>(initSharedProject(shared));
77         dispatch<any>(initFavoritesProject(favorites));
78         dispatch<any>(initPublicFavoritesProject(publicFavorites));
79     };
80
81 interface ReceiveTreePickerDataParams<T> {
82     data: T[];
83     extractNodeData: (value: T) => { id: string, value: T, status?: TreeNodeStatus };
84     id: string;
85     pickerId: string;
86 }
87
88 export const receiveTreePickerData = <T>(params: ReceiveTreePickerDataParams<T>) =>
89     (dispatch: Dispatch) => {
90         const { data, extractNodeData, id, pickerId, } = params;
91         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
92             id,
93             nodes: data.map(item => initTreeNode(extractNodeData(item))),
94             pickerId,
95         }));
96         dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
97     };
98
99 interface LoadProjectParams {
100     id: string;
101     pickerId: string;
102     includeCollections?: boolean;
103     includeFiles?: boolean;
104     includeFilterGroups?: boolean;
105     loadShared?: boolean;
106 }
107 export const loadProject = (params: LoadProjectParams) =>
108     async (dispatch: Dispatch, _: () => RootState, services: ServiceRepository) => {
109         const { id, pickerId, includeCollections = false, includeFiles = false, includeFilterGroups = false, loadShared = false } = params;
110
111         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId }));
112
113         const filters = pipe(
114             (fb: FilterBuilder) => includeCollections
115                 ? fb.addIsA('uuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
116                 : fb.addIsA('uuid', [ResourceKind.PROJECT]),
117             fb => fb.getFilters(),
118         )(new FilterBuilder());
119
120         const { items } = await services.groupsService.contents(loadShared ? '' : id, { filters, excludeHomeProject: loadShared || undefined });
121
122         dispatch<any>(receiveTreePickerData<GroupContentsResource>({
123             id,
124             pickerId,
125             data: items.filter((item) => {
126                     if (!includeFilterGroups && (item as GroupResource).groupClass && (item as GroupResource).groupClass === GroupClass.FILTER) {
127                         return false;
128                     }
129                     return true;
130                 }),
131             extractNodeData: item => ({
132                 id: item.uuid,
133                 value: item,
134                 status: item.kind === ResourceKind.PROJECT
135                     ? TreeNodeStatus.INITIAL
136                     : includeFiles
137                         ? TreeNodeStatus.INITIAL
138                         : TreeNodeStatus.LOADED
139             }),
140         }));
141     };
142
143 export const loadCollection = (id: string, pickerId: string) =>
144     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
145         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId }));
146
147         const picker = getTreePicker<ProjectsTreePickerItem>(pickerId)(getState().treePicker);
148         if (picker) {
149
150             const node = getNode(id)(picker);
151             if (node && 'kind' in node.value && node.value.kind === ResourceKind.COLLECTION) {
152                 const files = await services.collectionService.files(node.value.portableDataHash);
153                 const tree = createCollectionFilesTree(files);
154                 const sorted = sortFilesTree(tree);
155                 const filesTree = mapTreeValues(services.collectionService.extendFileURL)(sorted);
156
157                 dispatch(
158                     treePickerActions.APPEND_TREE_PICKER_NODE_SUBTREE({
159                         id,
160                         pickerId,
161                         subtree: mapTree(node => ({ ...node, status: TreeNodeStatus.LOADED }))(filesTree)
162                     }));
163
164                 dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
165             }
166         }
167     };
168
169
170 export const initUserProject = (pickerId: string) =>
171     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
172         const uuid = getUserUuid(getState());
173         if (uuid) {
174             dispatch(receiveTreePickerData({
175                 id: '',
176                 pickerId,
177                 data: [{ uuid, name: 'Projects' }],
178                 extractNodeData: value => ({
179                     id: value.uuid,
180                     status: TreeNodeStatus.INITIAL,
181                     value,
182                 }),
183             }));
184         }
185     };
186 export const loadUserProject = (pickerId: string, includeCollections = false, includeFiles = false) =>
187     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
188         const uuid = getUserUuid(getState());
189         if (uuid) {
190             dispatch(loadProject({ id: uuid, pickerId, includeCollections, includeFiles }));
191         }
192     };
193
194 export const SHARED_PROJECT_ID = 'Shared with me';
195 export const initSharedProject = (pickerId: string) =>
196     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
197         dispatch(receiveTreePickerData({
198             id: '',
199             pickerId,
200             data: [{ uuid: SHARED_PROJECT_ID, name: SHARED_PROJECT_ID }],
201             extractNodeData: value => ({
202                 id: value.uuid,
203                 status: TreeNodeStatus.INITIAL,
204                 value,
205             }),
206         }));
207     };
208
209 export const FAVORITES_PROJECT_ID = 'Favorites';
210 export const initFavoritesProject = (pickerId: string) =>
211     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
212         dispatch(receiveTreePickerData({
213             id: '',
214             pickerId,
215             data: [{ uuid: FAVORITES_PROJECT_ID, name: FAVORITES_PROJECT_ID }],
216             extractNodeData: value => ({
217                 id: value.uuid,
218                 status: TreeNodeStatus.INITIAL,
219                 value,
220             }),
221         }));
222     };
223
224 export const PUBLIC_FAVORITES_PROJECT_ID = 'Public Favorites';
225 export const initPublicFavoritesProject = (pickerId: string) =>
226     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
227         dispatch(receiveTreePickerData({
228             id: '',
229             pickerId,
230             data: [{ uuid: PUBLIC_FAVORITES_PROJECT_ID, name: PUBLIC_FAVORITES_PROJECT_ID }],
231             extractNodeData: value => ({
232                 id: value.uuid,
233                 status: TreeNodeStatus.INITIAL,
234                 value,
235             }),
236         }));
237     };
238
239 interface LoadFavoritesProjectParams {
240     pickerId: string;
241     includeCollections?: boolean;
242     includeFiles?: boolean;
243 }
244
245 export const loadFavoritesProject = (params: LoadFavoritesProjectParams,
246     options: { showOnlyOwned: boolean, showOnlyWritable: boolean } = { showOnlyOwned: true, showOnlyWritable: false }) =>
247     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
248         const { pickerId, includeCollections = false, includeFiles = false } = params;
249         const uuid = getUserUuid(getState());
250         if (uuid) {
251             const filters = pipe(
252                 (fb: FilterBuilder) => includeCollections
253                     ? fb.addIsA('head_uuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
254                     : fb.addIsA('head_uuid', [ResourceKind.PROJECT]),
255                 fb => fb.getFilters(),
256             )(new FilterBuilder());
257
258             const { items } = await services.favoriteService.list(uuid, { filters }, options.showOnlyOwned);
259
260             dispatch<any>(receiveTreePickerData<GroupContentsResource>({
261                 id: 'Favorites',
262                 pickerId,
263                 data: items.filter((item) => {
264                     if (options.showOnlyWritable && (item as GroupResource).writableBy && (item as GroupResource).writableBy.indexOf(uuid) === -1) {
265                         return false;
266                     }
267
268                     return true;
269                 }),
270                 extractNodeData: item => ({
271                     id: item.uuid,
272                     value: item,
273                     status: item.kind === ResourceKind.PROJECT
274                         ? TreeNodeStatus.INITIAL
275                         : includeFiles
276                             ? TreeNodeStatus.INITIAL
277                             : TreeNodeStatus.LOADED
278                 }),
279             }));
280         }
281     };
282
283 export const loadPublicFavoritesProject = (params: LoadFavoritesProjectParams) =>
284     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
285         const { pickerId, includeCollections = false, includeFiles = false } = params;
286         const uuidPrefix = getState().auth.config.uuidPrefix;
287         const publicProjectUuid = `${uuidPrefix}-j7d0g-publicfavorites`;
288
289         const filters = pipe(
290             (fb: FilterBuilder) => includeCollections
291                 ? fb.addIsA('head_uuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
292                 : fb.addIsA('head_uuid', [ResourceKind.PROJECT]),
293             fb => fb
294                 .addEqual('link_class', LinkClass.STAR)
295                 .addEqual('owner_uuid', publicProjectUuid)
296                 .getFilters(),
297         )(new FilterBuilder());
298
299         const { items } = await services.linkService.list({ filters });
300
301         dispatch<any>(receiveTreePickerData<LinkResource>({
302             id: 'Public Favorites',
303             pickerId,
304             data: items,
305             extractNodeData: item => ({
306                 id: item.headUuid,
307                 value: item,
308                 status: item.headKind === ResourceKind.PROJECT
309                     ? TreeNodeStatus.INITIAL
310                     : includeFiles
311                         ? TreeNodeStatus.INITIAL
312                         : TreeNodeStatus.LOADED
313             }),
314         }));
315     };
316
317 export const receiveTreePickerProjectsData = (id: string, projects: ProjectResource[], pickerId: string) =>
318     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
319         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
320             id,
321             nodes: projects.map(project => initTreeNode({ id: project.uuid, value: project })),
322             pickerId,
323         }));
324
325         dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
326     };
327
328 export const loadProjectTreePickerProjects = (id: string) =>
329     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
330         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.PROJECTS }));
331
332
333         const ownerUuid = id.length === 0 ? getUserUuid(getState()) || '' : id;
334         const { items } = await services.projectService.list(buildParams(ownerUuid));
335
336         dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.PROJECTS));
337     };
338
339 export const loadFavoriteTreePickerProjects = (id: string) =>
340     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
341         const parentId = getUserUuid(getState()) || '';
342
343         if (id === '') {
344             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: parentId, pickerId: TreePickerId.FAVORITES }));
345             const { items } = await services.favoriteService.list(parentId);
346             dispatch<any>(receiveTreePickerProjectsData(parentId, items as ProjectResource[], TreePickerId.FAVORITES));
347         } else {
348             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.FAVORITES }));
349             const { items } = await services.projectService.list(buildParams(id));
350             dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.FAVORITES));
351         }
352
353     };
354
355 export const loadPublicFavoriteTreePickerProjects = (id: string) =>
356     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
357         const parentId = getUserUuid(getState()) || '';
358
359         if (id === '') {
360             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: parentId, pickerId: TreePickerId.PUBLIC_FAVORITES }));
361             const { items } = await services.favoriteService.list(parentId);
362             dispatch<any>(receiveTreePickerProjectsData(parentId, items as ProjectResource[], TreePickerId.PUBLIC_FAVORITES));
363         } else {
364             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.PUBLIC_FAVORITES }));
365             const { items } = await services.projectService.list(buildParams(id));
366             dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.PUBLIC_FAVORITES));
367         }
368
369     };
370
371 const buildParams = (ownerUuid: string) => {
372     return {
373         filters: new FilterBuilder()
374             .addEqual('owner_uuid', ownerUuid)
375             .getFilters(),
376         order: new OrderBuilder<ProjectResource>()
377             .addAsc('name')
378             .getOrder()
379     };
380 };