-
Notifications
You must be signed in to change notification settings - Fork 0
/
Node.ts
81 lines (70 loc) · 2.1 KB
/
Node.ts
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
/**
* Can be a string or number only
*/
export type NodeId = string | number;
/**
* Can be a string, number or enum
*/
export type NodeType = string | number;
/**
* A simple Node type that supports any additional props required by your app.
*/
export interface Node {
id: NodeId;
/**
* Typically you'll want to define an enum with types and use that here. You
* could then create a `Schema` to setup constraints. If your nodes are all the same
* then you could just assign any string or number here.
*/
type: NodeType;
/**
* Only required for container types like folders
*/
expanded?: boolean;
/**
* Can this node be dragged? Defaults to false.
*/
dragDisabled?: boolean;
/**
* Nodes can include any additional properties as necessary.
*/
[key: string]: any;
}
/**
* Flat nodes are nodes stored in a flat array. They keep a reference
* to their parent as `parentId` so they can be converted into `TreeNodes` which
* are used by the `Tree` when rendering. A node with no `parentId`
* becomes a root node on the `Tree`.
*/
export interface FlatNode extends Node {
parentId?: NodeId;
}
/**
* A `FlatNode` converted to a tree node with it's `children` array
* property set.
*/
export interface TreeNode extends FlatNode {
children: TreeNode[];
}
export type TreeNodeSort = (a: TreeNode, b: TreeNode) => number;
/**
* Creates a simple sorting function that performs an alpha-numeric sort
* using `String.localeCompare`.
*
* @param property the property on the node you wish to use for sorting.
* This property is typically called `name` or `title` etc.
*/
export const createAlphaNumericSort = (
property: keyof TreeNode
): TreeNodeSort => (a: TreeNode, b: TreeNode) =>
String(a[property]).localeCompare(String(b[property]));
/**
* Sort the tree according to the `sortFunction` provided.
*
* @param tree the tree as an array of `TreeNodes`.
* @param sortFunction the sorting function to use.
*/
export const sortTree = (tree: TreeNode[], sortFunction: TreeNodeSort) => {
tree.sort(sortFunction);
tree.forEach((node) => sortTree(node.children, sortFunction));
};