1 | import { Node } from './types/Node'
|
2 |
|
3 | import State, { StateObject } from './utils/state'
|
4 | import { isNodeCheckable, isLeaf } from './utils/index'
|
5 | import { TreeComponent } from './types/TreeComponent'
|
6 |
|
7 | type CheckboxValueConsistency = 'ALL' | 'BRANCH' | 'LEAF' | 'WITH_INDETERMINATE'
|
8 |
|
9 | export class TreeAPI {
|
10 | private state: State<StateObject>
|
11 | private tree: TreeComponent
|
12 |
|
13 | constructor(tree: TreeComponent, state: State<StateObject>) {
|
14 | this.tree = tree
|
15 | this.state = state
|
16 | }
|
17 |
|
18 | selected(): Node[] {
|
19 | const state = this.state
|
20 | const selectedNodes: Array<Node | null> = this.tree.selectedNodes
|
21 | .map((id: string): Node | null => state.getNodeById(id))
|
22 |
|
23 | return selectedNodes.filter((item: Node | null) => null !== item) as Node[]
|
24 | }
|
25 |
|
26 | checked(valueConsistsOf: CheckboxValueConsistency, ignoreDisabled?: boolean): Node[] {
|
27 | const state = this.state
|
28 | let checkedNodes: Node[] = []
|
29 |
|
30 | this.tree.checkedNodes.forEach((id: string) => {
|
31 | const node = state.getNodeById(id)
|
32 |
|
33 | if (node) {
|
34 | checkedNodes.push(node)
|
35 | }
|
36 | })
|
37 |
|
38 | if ('WITH_INDETERMINATE' === valueConsistsOf) {
|
39 | this.tree.indeterminateNodes.forEach((id: string) => {
|
40 | const node = state.getNodeById(id)
|
41 |
|
42 | if (node) {
|
43 | checkedNodes.push(node)
|
44 | }
|
45 | })
|
46 | }
|
47 |
|
48 | if (ignoreDisabled) {
|
49 | checkedNodes = checkedNodes.filter(isNodeCheckable)
|
50 | }
|
51 |
|
52 | switch(valueConsistsOf) {
|
53 | case 'LEAF': return checkedNodes.filter((node: Node) => isLeaf(node))
|
54 | case 'BRANCH':
|
55 | return checkedNodes.filter((node: Node) => {
|
56 | if (node.parent && node.parent.checked) {
|
57 | return false
|
58 | }
|
59 |
|
60 | return true
|
61 | })
|
62 | }
|
63 |
|
64 | return checkedNodes
|
65 | }
|
66 | } |
\ | No newline at end of file |