Merge branch '21128-toolbar-context-menu'
[arvados-workbench2.git] / src / models / collection-file.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Tree, createTree, setNode, TreeNodeStatus } from './tree';
6 import { head, split, pipe, join } from 'lodash/fp';
7
8 export type CollectionFilesTree = Tree<CollectionDirectory | CollectionFile>;
9
10 export enum CollectionFileType {
11     DIRECTORY = 'directory',
12     FILE = 'file'
13 }
14
15 export interface CollectionDirectory {
16     path: string;
17     url: string;
18     id: string;
19     name: string;
20     type: CollectionFileType.DIRECTORY;
21 }
22
23 export interface CollectionFile {
24     path: string;
25     url: string;
26     id: string;
27     name: string;
28     size: number;
29     type: CollectionFileType.FILE;
30 }
31
32 export interface CollectionUploadFile {
33     name: string;
34 }
35
36 export const createCollectionDirectory = (data: Partial<CollectionDirectory>): CollectionDirectory => ({
37     id: '',
38     name: '',
39     path: '',
40     url: '',
41     type: CollectionFileType.DIRECTORY,
42     ...data
43 });
44
45 export const createCollectionFile = (data: Partial<CollectionFile>): CollectionFile => ({
46     id: '',
47     name: '',
48     path: '',
49     url: '',
50     size: 0,
51     type: CollectionFileType.FILE,
52     ...data
53 });
54
55 export const createCollectionFilesTree = (data: Array<CollectionDirectory | CollectionFile>, joinParents: Boolean = true) => {
56     const directories = data.filter(item => item.type === CollectionFileType.DIRECTORY);
57     directories.sort((a, b) => a.path.localeCompare(b.path));
58     const files = data.filter(item => item.type === CollectionFileType.FILE);
59     return [...directories, ...files]
60         .reduce((tree, item) => setNode({
61             children: [],
62             id: item.id,
63             parent: joinParents ? getParentId(item) : '',
64             value: item,
65             active: false,
66             selected: false,
67             expanded: false,
68             status: TreeNodeStatus.INITIAL
69         })(tree), createTree<CollectionDirectory | CollectionFile>());
70 };
71
72 const getParentId = (item: CollectionDirectory | CollectionFile) =>
73     item.path
74         ? join('', [getCollectionResourceCollectionUuid(item.id), item.path])
75         : item.path;
76
77 export const getCollectionResourceCollectionUuid = pipe(
78     split('/'),
79     head,
80 );