@apia/tree 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1397 +1,2 @@
1
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
2
- import { useMount, useDebounceFn, useUnmount } from 'ahooks';
3
- import React, { useState, useEffect, memo } from 'react';
4
- import { shallowEqual } from 'react-redux';
5
- import { Box, Spinner } from 'theme-ui';
6
- import { EventEmitter, PropsStore, addBoundary, getSpecificParent, usePropsSelector, formatMessage, useLatest } from '@apia/util';
7
- import { IconButton } from '@apia/components';
8
- import { getVariant } from '@apia/theme';
9
- import { Icon } from '@apia/icons';
10
- import { uniqueId } from 'lodash-es';
11
-
12
- const getLastVisibleChild = (handler, id, avoidFiltered) => {
13
- const nodeProps = handler.propsStore.getFieldProps(id);
14
- if (id !== "root" && (nodeProps.isDisabled || !nodeProps.isExpanded) || nodeProps.children.length === 0)
15
- return null;
16
- for (let i = nodeProps.children.length - 1; i >= 0; i--) {
17
- const currentId = nodeProps.children[i];
18
- const currentProps = handler.propsStore.getFieldProps(currentId);
19
- if (!avoidFiltered || !currentProps.isFiltered) {
20
- const lastChildrenLastChildren = getLastVisibleChild(
21
- handler,
22
- currentId,
23
- avoidFiltered
24
- );
25
- return lastChildrenLastChildren !== null ? lastChildrenLastChildren : currentId;
26
- }
27
- }
28
- return null;
29
- };
30
- const getPreviousChild = (handler, id, avoidFiltered) => {
31
- var _a, _b;
32
- const nodeProps = handler.propsStore.getFieldProps(id);
33
- const fatherProps = handler.propsStore.getFieldProps(nodeProps.parentId);
34
- let childPosition = (_b = (_a = fatherProps.children) == null ? void 0 : _a.findIndex((current) => current === nodeProps.id)) != null ? _b : -1;
35
- while (childPosition > 0) {
36
- const prevSibling = handler.propsStore.getFieldProps(
37
- fatherProps.children[childPosition - 1]
38
- );
39
- const prevSiblingLastChild = getLastVisibleChild(
40
- handler,
41
- prevSibling.id,
42
- avoidFiltered
43
- );
44
- if (prevSiblingLastChild !== null)
45
- return prevSiblingLastChild;
46
- if (!avoidFiltered || !prevSibling.isFiltered)
47
- return prevSibling.id;
48
- childPosition--;
49
- }
50
- if (nodeProps.parentId === "root")
51
- return null;
52
- return nodeProps.parentId;
53
- };
54
- const getFirstNonFilteredChild = (handler, id) => {
55
- const nodeProps = handler.propsStore.getFieldProps(id);
56
- for (const child of nodeProps.children) {
57
- if (!handler.propsStore.getFieldProps(child).isFiltered)
58
- return child;
59
- }
60
- return null;
61
- };
62
- const getNextChild = (handler, id, avoidChildren, avoidFiltered) => {
63
- var _a, _b;
64
- const nodeProps = handler.propsStore.getFieldProps(id);
65
- const fatherProps = handler.propsStore.getFieldProps(nodeProps.parentId);
66
- let childPosition = (_b = (_a = fatherProps.children) == null ? void 0 : _a.findIndex((current) => current === nodeProps.id)) != null ? _b : Infinity;
67
- if (!avoidChildren && nodeProps.isExpanded) {
68
- if (!avoidFiltered && nodeProps.children.length > 0)
69
- return nodeProps.children[0];
70
- const firstNonFilteredChild = getFirstNonFilteredChild(
71
- handler,
72
- nodeProps.id
73
- );
74
- if (firstNonFilteredChild !== null)
75
- return firstNonFilteredChild;
76
- }
77
- while (childPosition < fatherProps.children.length - 1) {
78
- const nextSibling = fatherProps.children[childPosition + 1];
79
- if (!avoidFiltered || !handler.propsStore.getFieldProps(nextSibling).isFiltered)
80
- return nextSibling;
81
- childPosition++;
82
- }
83
- if (nodeProps.parentId === "root")
84
- return null;
85
- return getNextChild(handler, fatherProps.id, true, avoidFiltered);
86
- };
87
- const getNextNodeWithKey = (handler, id, firstKey, avoidFiltered) => {
88
- let nextChildWithKey = id;
89
- do {
90
- nextChildWithKey = getNextChild(
91
- handler,
92
- nextChildWithKey,
93
- false,
94
- avoidFiltered
95
- );
96
- if (nextChildWithKey !== null) {
97
- const nodeProps2 = handler.propsStore.getFieldProps(nextChildWithKey);
98
- if ((!nodeProps2.isFiltered || !avoidFiltered) && nodeProps2.label.toUpperCase().startsWith(firstKey.toUpperCase()))
99
- return nextChildWithKey;
100
- }
101
- } while (nextChildWithKey !== null);
102
- const nodeProps = handler.propsStore.getFieldProps(id);
103
- const positionInParent = handler.propsStore.getFieldProps(nodeProps.parentId).children.findIndex((current) => current === id);
104
- if (nodeProps.parentId !== "root" || positionInParent > 0) {
105
- const [firstChildOfTree] = handler.propsStore.getFieldProps("root").children;
106
- const firstChildProps = handler.propsStore.getFieldProps(firstChildOfTree);
107
- if (firstChildOfTree && (!avoidFiltered || !firstChildProps.isFiltered) && firstChildProps.label.toUpperCase().startsWith(firstKey.toUpperCase()))
108
- return firstChildOfTree;
109
- nextChildWithKey = firstChildOfTree;
110
- do {
111
- nextChildWithKey = getNextChild(
112
- handler,
113
- nextChildWithKey,
114
- false,
115
- avoidFiltered
116
- );
117
- if (nextChildWithKey) {
118
- const currentNodeProps = handler.propsStore.getFieldProps(nextChildWithKey);
119
- if ((!avoidFiltered || !currentNodeProps.isFiltered) && currentNodeProps.label.toUpperCase().startsWith(firstKey.toUpperCase()))
120
- return nextChildWithKey;
121
- }
122
- } while (nextChildWithKey !== id && nextChildWithKey !== null);
123
- }
124
- return null;
125
- };
126
- const getNodePath = (handler, nodeId) => {
127
- const path = [nodeId];
128
- let currentStep = nodeId;
129
- do {
130
- currentStep = handler.propsStore.getFieldProps(currentStep).parentId;
131
- path.unshift(currentStep);
132
- } while (currentStep !== "root");
133
- return path;
134
- };
135
- const getCommonAncestor = (handler, oneNodeId, anotherNodeId) => {
136
- const oneNodePath = getNodePath(handler, oneNodeId);
137
- const anotherNodePath = getNodePath(handler, anotherNodeId);
138
- for (let i = oneNodePath.length - 1; i >= 0; i--) {
139
- const anotherNodeIndex = anotherNodePath.indexOf(oneNodePath[i]);
140
- if (anotherNodeIndex !== -1)
141
- return {
142
- commonAncestor: oneNodePath[i],
143
- oneNodeAncestorChild: oneNodePath[i + 1],
144
- anotherNodeAncestorChild: anotherNodePath[anotherNodeIndex + 1]
145
- };
146
- }
147
- console.warn(
148
- "This point should have never been reached since the root node is common to all nodes",
149
- { oneNodeId, anotherNodeId, oneNodePath, anotherNodePath }
150
- );
151
- return null;
152
- };
153
- const unfilterNodes = (handler) => {
154
- handler.state.filteredNodes.forEach((current) => {
155
- handler.propsStore.updateField(
156
- current,
157
- { isFiltered: false },
158
- { noEmit: true }
159
- );
160
- });
161
- const firstChild = handler.propsStore.getFieldProps("root").children[0];
162
- if (firstChild)
163
- handler.setFocusedNode(firstChild);
164
- handler.setState({ filteredNodes: [] });
165
- };
166
- const matchNodesAgainstString = (handler, searchString, nodeId = "root") => {
167
- let hasMatched = false;
168
- let matchNode = null;
169
- const nodeProps = handler.propsStore.getFieldProps(nodeId);
170
- if (nodeId !== "root" && nodeProps.label.match(new RegExp(searchString, "i"))) {
171
- handler.propsStore.updateField(nodeId, { isFiltered: false });
172
- hasMatched = true;
173
- matchNode = nodeProps.id;
174
- handler.setState({
175
- filteredNodes: handler.state.filteredNodes.filter(
176
- (current) => current !== nodeId
177
- )
178
- });
179
- }
180
- let hasChildrenMatched = false;
181
- nodeProps.children.forEach((current) => {
182
- hasChildrenMatched = matchNodesAgainstString(handler, searchString, current) || hasMatched;
183
- hasMatched = hasChildrenMatched || hasMatched;
184
- if (hasMatched && !matchNode)
185
- matchNode = current;
186
- });
187
- if (hasChildrenMatched) {
188
- handler.propsStore.updateField(nodeId, { isExpanded: true });
189
- if (hasMatched && !matchNode)
190
- matchNode = nodeId;
191
- }
192
- if (!hasMatched) {
193
- handler.propsStore.updateField(
194
- nodeId,
195
- { isFiltered: true },
196
- { noEmit: true }
197
- );
198
- handler.setState({
199
- filteredNodes: [...handler.state.filteredNodes, nodeId]
200
- });
201
- }
202
- if (matchNode !== null)
203
- handler.setFocusedNode(matchNode);
204
- return hasMatched;
205
- };
206
- const selectAllNodesBetweenTwoNodes = (handler, oneNodeId, anotherNodeId, avoidFiltered) => {
207
- const commonAncestorData = getCommonAncestor(
208
- handler,
209
- oneNodeId,
210
- anotherNodeId
211
- );
212
- if (commonAncestorData) {
213
- const { anotherNodeAncestorChild, commonAncestor, oneNodeAncestorChild } = commonAncestorData;
214
- const ancestorProps = handler.propsStore.getFieldProps(commonAncestor);
215
- const oneNodePosition = ancestorProps.children.findIndex(
216
- (current) => current === oneNodeAncestorChild
217
- );
218
- const anotherNodePosition = ancestorProps.children.findIndex(
219
- (current) => current === anotherNodeAncestorChild
220
- );
221
- let currentId = oneNodePosition >= anotherNodePosition ? anotherNodeId : oneNodeId;
222
- const lastNodeId = oneNodePosition < anotherNodePosition ? anotherNodeId : oneNodeId;
223
- handler.toggleNodeSelectedState(currentId, true);
224
- do {
225
- currentId = getNextChild(handler, currentId, avoidFiltered);
226
- if (currentId !== null)
227
- handler.toggleNodeSelectedState(currentId, true);
228
- } while (currentId !== lastNodeId && currentId !== null);
229
- }
230
- };
231
-
232
- var __defProp$6 = Object.defineProperty;
233
- var __defProps$5 = Object.defineProperties;
234
- var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
235
- var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
236
- var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
237
- var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
238
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
239
- var __spreadValues$6 = (a, b) => {
240
- for (var prop in b || (b = {}))
241
- if (__hasOwnProp$6.call(b, prop))
242
- __defNormalProp$6(a, prop, b[prop]);
243
- if (__getOwnPropSymbols$6)
244
- for (var prop of __getOwnPropSymbols$6(b)) {
245
- if (__propIsEnum$6.call(b, prop))
246
- __defNormalProp$6(a, prop, b[prop]);
247
- }
248
- return a;
249
- };
250
- var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
251
- const trees = {};
252
- const treesRecordEmitter = new class TreesRecordEmitter extends EventEmitter {
253
- emit(eventName, params) {
254
- super.emit(eventName, params);
255
- trees[params.name] = params.controller;
256
- }
257
- }();
258
- function useTreeDataController(name) {
259
- const [controller, setDataController] = useState(
260
- trees[name]
261
- );
262
- useEffect(() => {
263
- if (trees[name] !== controller)
264
- setDataController(trees[name]);
265
- return treesRecordEmitter.on("addController", (ev) => {
266
- if (ev.name === name)
267
- setDataController(ev.controller);
268
- });
269
- }, []);
270
- return controller;
271
- }
272
- function getTreeDataController(name) {
273
- return trees[name];
274
- }
275
- class TreeDataController extends EventEmitter {
276
- constructor(name, configuration, propsStore = new PropsStore({
277
- logCommands: {
278
- propsStore: `treeProps_${name}`,
279
- propsLog: `treeLog_${name}`,
280
- propsSuscriptors: `propsSuscriptors_${name}`,
281
- updateProp: `updateProp_${name}`
282
- }
283
- })) {
284
- var _a;
285
- super();
286
- this.name = name;
287
- this.propsStore = propsStore;
288
- this.hasApendedFirstChild = false;
289
- /**
290
- * Este array se usa para conocer los padres faltantes al momento de la
291
- * construcción del árbol, de forma de optimizar el proceso
292
- */
293
- this.missingParents = [];
294
- this.nonEmittedUpdates = [];
295
- this.stateKey = "treeState";
296
- this._configuration = configuration != null ? configuration : {
297
- current: { emitUpdates: true }
298
- };
299
- this._configuration.current.emitUpdates = (_a = this._configuration.current.emitUpdates) != null ? _a : true;
300
- this.setState(this.getInitialState());
301
- treesRecordEmitter.emit("addController", {
302
- name,
303
- controller: this
304
- });
305
- this.initRoot();
306
- }
307
- get configuration() {
308
- return __spreadValues$6({}, this._configuration);
309
- }
310
- get state() {
311
- return this.propsStore.getFieldProps(
312
- this.stateKey
313
- );
314
- }
315
- get stateStore() {
316
- return this.propsStore;
317
- }
318
- destructor() {
319
- this.propsStore.destructor();
320
- }
321
- append(node) {
322
- var _a, _b, _c, _d, _e, _f;
323
- const newNode = __spreadProps$5(__spreadValues$6({}, node), { nodeProps: (_a = node.nodeProps) != null ? _a : {} });
324
- if ((_b = this.propsStore.getFieldProps(newNode.id)) == null ? void 0 : _b.children) {
325
- console.error("DUPLICATED NODE: The conflict origin is ", newNode, this);
326
- return;
327
- }
328
- let father;
329
- if (newNode.parentId !== void 0 && ((_c = this.propsStore.getFieldProps(newNode.parentId)) == null ? void 0 : _c.children)) {
330
- father = newNode.parentId;
331
- } else {
332
- father = "root";
333
- if (newNode.parentId)
334
- this.missingParents.push(newNode.parentId);
335
- newNode.actualParentId = newNode.parentId;
336
- newNode.parentId = "root";
337
- }
338
- this.propsStore.updateField(
339
- newNode.id,
340
- __spreadProps$5(__spreadValues$6({}, newNode), {
341
- children: (_d = newNode.children) != null ? _d : []
342
- }),
343
- { isUrgent: true }
344
- );
345
- this.setState({ length: this.state.length + 1 });
346
- if (this.missingParents.includes(newNode.id)) {
347
- this.propsStore.getFieldProps("root").children.forEach((currentChild) => {
348
- if (this.propsStore.getFieldProps(currentChild).actualParentId === newNode.id) {
349
- this.move(currentChild, newNode.id);
350
- }
351
- });
352
- this.missingParents = this.missingParents.filter(
353
- (current) => current !== newNode.id
354
- );
355
- }
356
- this.propsStore.updateField(
357
- father,
358
- {
359
- children: [
360
- ...this.propsStore.getFieldProps(father).children,
361
- newNode.id
362
- ]
363
- },
364
- { noEmit: !((_e = this._configuration.current) == null ? void 0 : _e.emitUpdates) }
365
- );
366
- if (!((_f = this._configuration.current) == null ? void 0 : _f.emitUpdates))
367
- this.nonEmittedUpdates.push(father);
368
- if (!this.hasApendedFirstChild) {
369
- this.hasApendedFirstChild = true;
370
- this.setFocusedNode(newNode.id, true);
371
- }
372
- if (newNode.isExpanded)
373
- this.toggleNodeExpandedState(newNode.id, true);
374
- }
375
- /**
376
- * Cuando se quieren agregar muchos nodos, es conveniente llamar primero al
377
- * método batchInit y luego de finalizar, al método batchFinish()
378
- */
379
- batchInit() {
380
- this.config({ emitUpdates: false });
381
- this.setState({ isLoading: true }, { isUrgent: true });
382
- }
383
- /**
384
- * Cuando se quieren agregar muchos nodos, es conveniente llamar primero al
385
- * método batchInit y luego de finalizar, al método batchFinish()
386
- */
387
- batchFinish() {
388
- this.config({ emitUpdates: true });
389
- setTimeout(() => this.setState({ isLoading: false }), 0);
390
- }
391
- config(newConf) {
392
- var _a;
393
- if (!((_a = this._configuration.current) == null ? void 0 : _a.emitUpdates) && newConf.emitUpdates) {
394
- this.nonEmittedUpdates.forEach(
395
- (current) => this.propsStore.updateField(current, {
396
- children: [...this.propsStore.getFieldProps(current).children]
397
- })
398
- );
399
- this.nonEmittedUpdates = [];
400
- }
401
- Object.assign(
402
- this._configuration.current,
403
- newConf
404
- );
405
- }
406
- deselectAll() {
407
- this.state.selectedNodes.forEach(
408
- (currentId) => this.propsStore.updateField(currentId, { isSelected: false })
409
- );
410
- this.setState({ selectedNodes: [] });
411
- }
412
- forceEmitUpdate() {
413
- var _a;
414
- this.propsStore.updateField("root", {
415
- forceUpdate: ((_a = this.propsStore.getFieldProps("root").forceUpdate) != null ? _a : 0) + 1
416
- });
417
- }
418
- getInitialState() {
419
- return {
420
- expandedNodes: [],
421
- filteredNodes: [],
422
- focusedNode: null,
423
- isLoading: false,
424
- length: 0,
425
- selectedNodes: []
426
- };
427
- }
428
- getNodesAsArray() {
429
- const allFields = __spreadValues$6({}, this.propsStore.fields);
430
- delete allFields[this.stateKey];
431
- delete allFields.root;
432
- return Object.values(allFields);
433
- }
434
- /**
435
- * Devuelve un array que contiene el id de todos los nodos pertenecientes al
436
- * árbol
437
- */
438
- getNodesIds() {
439
- const allFields = __spreadValues$6({}, this.propsStore.fields);
440
- delete allFields[this.stateKey];
441
- delete allFields.root;
442
- return Object.keys(allFields);
443
- }
444
- getParentId(parentId) {
445
- return this.propsStore.getFieldProps(parentId).parentId;
446
- }
447
- /**
448
- * Este método permite controlar el comportamiento con el teclado desde fuera
449
- * del componente.
450
- */
451
- handleKey(ev) {
452
- var _a;
453
- const focusedId = this.state.focusedNode;
454
- const nodeProps = this.propsStore.getFieldProps(focusedId);
455
- if (ev.key === "*") {
456
- if (this.state.focusedNode === null)
457
- return;
458
- const parent = this.propsStore.getFieldProps(
459
- this.propsStore.getFieldProps(this.state.focusedNode).parentId
460
- );
461
- parent.children.forEach(
462
- (current) => this.toggleNodeExpandedState(current, true)
463
- );
464
- } else if (ev.key.match(/^\w$/)) {
465
- const nextChildWithKey = getNextNodeWithKey(
466
- this,
467
- focusedId,
468
- ev.key,
469
- true
470
- );
471
- if (nextChildWithKey !== null) {
472
- this.setFocusedNode(nextChildWithKey);
473
- this.emit("mustFocus", nextChildWithKey);
474
- }
475
- } else
476
- switch (ev.code) {
477
- case "Home": {
478
- const firstChild = getFirstNonFilteredChild(this, "root");
479
- if (firstChild === null)
480
- return;
481
- if (ev.shiftKey && ev.ctrlKey && this.state.focusedNode !== null) {
482
- selectAllNodesBetweenTwoNodes(
483
- this,
484
- firstChild,
485
- this.state.focusedNode,
486
- true
487
- );
488
- }
489
- this.setFocusedNode(firstChild);
490
- this.emit("mustFocus", firstChild);
491
- break;
492
- }
493
- case "End": {
494
- const lastVisibleChild = getLastVisibleChild(this, "root", true);
495
- if (lastVisibleChild !== null) {
496
- if (ev.shiftKey && ev.ctrlKey && this.state.focusedNode !== null) {
497
- selectAllNodesBetweenTwoNodes(
498
- this,
499
- lastVisibleChild,
500
- this.state.focusedNode,
501
- true
502
- );
503
- }
504
- this.setFocusedNode(lastVisibleChild);
505
- this.emit("mustFocus", lastVisibleChild);
506
- }
507
- break;
508
- }
509
- case "ArrowRight": {
510
- if (nodeProps.isLeaf)
511
- return;
512
- ev.preventDefault();
513
- if (nodeProps.isExpanded) {
514
- const firstChild = getFirstNonFilteredChild(this, nodeProps.id);
515
- if (firstChild !== null) {
516
- this.setFocusedNode(firstChild);
517
- this.emit("mustFocus", firstChild);
518
- }
519
- } else
520
- this.toggleNodeExpandedState(nodeProps.id, true);
521
- break;
522
- }
523
- case "ArrowLeft": {
524
- ev.preventDefault();
525
- if (nodeProps.isLeaf || !nodeProps.isExpanded) {
526
- if (nodeProps.parentId !== "root" && nodeProps.parentId !== void 0) {
527
- this.setFocusedNode(nodeProps.parentId);
528
- this.emit("mustFocus", nodeProps.parentId);
529
- }
530
- } else
531
- this.toggleNodeExpandedState(nodeProps.id, false);
532
- break;
533
- }
534
- case "ArrowUp": {
535
- ev.preventDefault();
536
- const prevChild = getPreviousChild(this, nodeProps.id, true);
537
- if (prevChild !== null) {
538
- if (ev.shiftKey)
539
- this.toggleNodeSelectedState(prevChild, true);
540
- this.setFocusedNode(prevChild);
541
- this.emit("mustFocus", prevChild);
542
- } else
543
- this.emit("onArrowUpOnFirstElement", true);
544
- break;
545
- }
546
- case "ArrowDown": {
547
- ev.preventDefault();
548
- const nextChild = getNextChild(this, nodeProps.id, false, true);
549
- if (nextChild !== null) {
550
- if (ev.shiftKey)
551
- this.toggleNodeSelectedState(nextChild, true);
552
- this.setFocusedNode(nextChild);
553
- this.emit("mustFocus", nextChild);
554
- }
555
- break;
556
- }
557
- case "Space": {
558
- if ((_a = this._configuration.current) == null ? void 0 : _a.disableSelection)
559
- return;
560
- ev.preventDefault();
561
- this.toggleNodeSelectedState(nodeProps.id);
562
- break;
563
- }
564
- }
565
- }
566
- isNode(node) {
567
- return typeof node === "object" && "parentId" in node;
568
- }
569
- isNodeContainer(node) {
570
- return typeof node === "object" && !this.isNode(node);
571
- }
572
- includes(searchNode) {
573
- return !!this.propsStore.getFieldProps(searchNode.id);
574
- }
575
- initRoot() {
576
- this.propsStore.updateField(
577
- "root",
578
- { children: [], id: "root" },
579
- { isUrgent: true }
580
- );
581
- }
582
- move(moveNode, destinationNode, afterOrBefore) {
583
- var _a, _b;
584
- const currentFather = this.propsStore.getFieldProps(
585
- this.propsStore.getFieldProps(moveNode).parentId
586
- );
587
- const newFather = this.propsStore.getFieldProps(destinationNode);
588
- if (!currentFather) {
589
- console.warn("The current node does not belong to the tree.", moveNode);
590
- return;
591
- }
592
- if (!newFather) {
593
- console.warn(
594
- "The destination node does not belong to the tree. No action will be made",
595
- destinationNode
596
- );
597
- return;
598
- }
599
- currentFather.children = (_a = currentFather.children) == null ? void 0 : _a.filter(
600
- (search) => search !== moveNode
601
- );
602
- if (!newFather.children)
603
- newFather.children = [];
604
- if (!afterOrBefore)
605
- newFather.children.push(moveNode);
606
- else if (afterOrBefore.position) {
607
- newFather.children.splice(afterOrBefore.position - 1, 0, moveNode);
608
- } else {
609
- const key = afterOrBefore.after ? afterOrBefore.after : afterOrBefore.before;
610
- const relatedNodeKey = key && this.isNode(key) ? key.id : key;
611
- const relatedNodeIndex = newFather.children.findIndex(
612
- (search) => search === relatedNodeKey
613
- );
614
- const actualIndex = addBoundary(
615
- afterOrBefore.before !== void 0 ? relatedNodeIndex : relatedNodeIndex + 1,
616
- 0
617
- );
618
- if (actualIndex === -1 || actualIndex === newFather.children.length)
619
- newFather.children.push(moveNode);
620
- else
621
- newFather.children.splice(actualIndex, 0, moveNode);
622
- }
623
- this.propsStore.updateField(currentFather.id, {
624
- children: [...(_b = currentFather.children) != null ? _b : []]
625
- });
626
- this.propsStore.updateField(newFather.id, {
627
- children: [...newFather.children]
628
- });
629
- this.propsStore.updateField(moveNode, {
630
- parentId: newFather.id
631
- });
632
- }
633
- /**
634
- * Borra el nodo del árbol, y dependiendo del parámetro removeChildren, borra
635
- * también sus hijos.
636
- *
637
- * @param removeChildren - Si se pasa en false, los nodos hijos son movidos al root
638
- */
639
- remove(removeNode, removeChildren = true) {
640
- var _a, _b;
641
- const removeNodeId = this.isNode(removeNode) ? removeNode.id : removeNode;
642
- const removingNode = this.propsStore.getFieldProps(removeNodeId);
643
- if (!removingNode)
644
- return;
645
- const father = this.propsStore.getFieldProps(removingNode.parentId);
646
- if (father) {
647
- this.propsStore.updateField(father.id, {
648
- children: (_a = father.children) == null ? void 0 : _a.filter((search) => search !== removeNodeId)
649
- });
650
- }
651
- (_b = removingNode.children) == null ? void 0 : _b.forEach((current) => {
652
- if (removeChildren) {
653
- this.remove(current);
654
- } else {
655
- this.move(current, "root");
656
- }
657
- });
658
- this.setState({
659
- selectedNodes: this.state.selectedNodes.filter(
660
- (current) => current !== removeNodeId
661
- ),
662
- focusedNode: this.state.focusedNode === removeNodeId ? null : this.state.focusedNode,
663
- length: this.state.length - 1
664
- });
665
- this.propsStore.removeField(removeNodeId);
666
- }
667
- removeMultiple(nodes, removeChildren = true) {
668
- nodes.forEach((current) => this.remove(current, removeChildren));
669
- }
670
- /**
671
- * Borra todos los nodos del árbol.
672
- */
673
- removeAll() {
674
- this.hasApendedFirstChild = false;
675
- this.setState({ focusedNode: null }, { isUrgent: true });
676
- this.setSelectedNodes([]);
677
- this.initRoot();
678
- Object.keys(this.propsStore.fields).forEach((current) => {
679
- if (!["root", this.stateKey].includes(current))
680
- this.propsStore.removeField(current);
681
- });
682
- }
683
- selectAll() {
684
- this.setState({
685
- selectedNodes: this.getNodesIds()
686
- });
687
- this.state.selectedNodes.forEach(
688
- (currentId) => this.propsStore.updateField(currentId, { isSelected: true })
689
- );
690
- }
691
- setFocusedNode(key, avoidSelection) {
692
- var _a, _b;
693
- if (this.state.focusedNode !== null)
694
- this.propsStore.updateField(this.state.focusedNode, { isFocused: false });
695
- this.setState({
696
- focusedNode: key
697
- });
698
- if (!((_a = this._configuration.current) == null ? void 0 : _a.isMultiple) && !avoidSelection && ((_b = this._configuration.current) == null ? void 0 : _b.selectionMode) !== "explicit")
699
- this.setSelectedNodes([key]);
700
- this.propsStore.updateField(key, { isFocused: true });
701
- }
702
- setSelectedNodes(nodes, force = false) {
703
- var _a;
704
- if (((_a = this._configuration.current) == null ? void 0 : _a.disableSelection) && !force)
705
- return;
706
- this.state.selectedNodes.forEach(
707
- (current) => this.propsStore.updateField(current, { isSelected: false })
708
- );
709
- this.setState({
710
- selectedNodes: nodes.filter((current) => {
711
- const { isSelectable } = this.propsStore.getFieldProps(current);
712
- if (isSelectable !== false)
713
- this.propsStore.updateField(current, { isSelected: true });
714
- return isSelectable !== false;
715
- })
716
- });
717
- }
718
- setSelectedNodesByClickEvent(ev) {
719
- var _a, _b, _c, _d;
720
- if ((_a = this._configuration.current) == null ? void 0 : _a.disableSelection)
721
- return;
722
- const nodeKey = (_b = getSpecificParent(
723
- ev.target,
724
- (current) => current.getAttribute("role") === "treeitem"
725
- )) == null ? void 0 : _b.getAttribute("data-key");
726
- if (nodeKey) {
727
- const nodeProps = this.propsStore.getFieldProps(nodeKey);
728
- if (nodeProps.isDisabled || nodeProps.isSelectable === false)
729
- return;
730
- const previousSelectionKeys = [...this.state.selectedNodes];
731
- const newSelection = ((_c = this._configuration.current) == null ? void 0 : _c.isMultiple) ? nodeProps.isSelected ? previousSelectionKeys.filter((current) => current !== nodeKey) : [...previousSelectionKeys, nodeKey] : [nodeKey];
732
- this.setState({
733
- selectedNodes: newSelection
734
- });
735
- previousSelectionKeys.forEach((current) => {
736
- if (!newSelection.includes(current))
737
- this.propsStore.updateField(current, { isSelected: false });
738
- });
739
- this.propsStore.updateField(nodeKey, {
740
- isSelected: ((_d = this._configuration.current) == null ? void 0 : _d.isMultiple) ? !nodeProps.isSelected : true
741
- });
742
- } else
743
- console.warn("Cannot set selection, no treeitem found", ev);
744
- }
745
- setState(updateProps, conf) {
746
- this.propsStore.updateField(
747
- this.stateKey,
748
- __spreadValues$6(__spreadValues$6({}, this.state), updateProps),
749
- conf
750
- );
751
- }
752
- toggleNodeExpandedState(key, shouldExpand) {
753
- var _a, _b, _c, _d, _e;
754
- const nodeProps = this.propsStore.getFieldProps(key);
755
- if (nodeProps.isDisabled || nodeProps.isLeaf || nodeProps.isLoading)
756
- return;
757
- if (((_a = this._configuration.current) == null ? void 0 : _a.onLoadData) && !nodeProps.hasLoaded) {
758
- this.propsStore.updateField(key, { isLoading: true });
759
- (_b = this._configuration.current) == null ? void 0 : _b.onLoadData(nodeProps).finally(() => {
760
- var _a2, _b2;
761
- this.propsStore.updateField(key, {
762
- isLoading: false,
763
- isExpanded: true,
764
- hasLoaded: true
765
- });
766
- this.setState({
767
- expandedNodes: [...this.state.expandedNodes, key]
768
- });
769
- (_b2 = (_a2 = this._configuration.current) == null ? void 0 : _a2.onExpand) == null ? void 0 : _b2.call(
770
- _a2,
771
- this.propsStore.getFieldProps(key)
772
- );
773
- });
774
- } else {
775
- const { expandedNodes } = this.state;
776
- const shouldExpandInner = shouldExpand !== void 0 ? shouldExpand : !expandedNodes.includes(key);
777
- if ((_c = this.propsStore.getFieldProps(key)) == null ? void 0 : _c.isDisabled)
778
- return;
779
- this.setState({
780
- expandedNodes: shouldExpandInner ? [...expandedNodes, key] : expandedNodes.filter((current) => current !== key)
781
- });
782
- this.propsStore.updateField(key, { isExpanded: shouldExpandInner });
783
- (_e = (_d = this._configuration.current) == null ? void 0 : _d.onExpand) == null ? void 0 : _e.call(
784
- _d,
785
- this.propsStore.getFieldProps(key)
786
- );
787
- }
788
- }
789
- toggleNodeSelectedState(key, isSelected) {
790
- var _a, _b;
791
- if ((_a = this._configuration.current) == null ? void 0 : _a.disableSelection)
792
- return;
793
- const nodeProps = this.propsStore.getFieldProps(key);
794
- if (nodeProps.isDisabled || nodeProps.isSelectable === false)
795
- return;
796
- const shouldSelect = isSelected !== void 0 ? isSelected : !this.state.selectedNodes.includes(key);
797
- if (shouldSelect && !((_b = this._configuration.current) == null ? void 0 : _b.isMultiple) && this.state.selectedNodes[0])
798
- this.toggleNodeSelectedState(this.state.selectedNodes[0], false);
799
- this.propsStore.updateField(key, { isSelected: shouldSelect });
800
- this.setState({
801
- selectedNodes: shouldSelect ? [...this.state.selectedNodes, key] : this.state.selectedNodes.filter((current) => current !== key)
802
- });
803
- }
804
- }
805
- function useTreeSelector(handler, configuration) {
806
- var _a;
807
- return usePropsSelector(
808
- (_a = handler == null ? void 0 : handler.stateKey) != null ? _a : "__NO__TREE__KEY__",
809
- __spreadValues$6({
810
- propsStore: handler == null ? void 0 : handler.propsStore
811
- }, configuration)
812
- );
813
- }
814
- function useTreeSelectorByName(treeName, configuration) {
815
- var _a;
816
- const handler = useTreeDataController(treeName);
817
- const selection = usePropsSelector(
818
- (_a = handler == null ? void 0 : handler.stateKey) != null ? _a : "__NO__TREE__KEY__",
819
- __spreadValues$6({
820
- propsStore: handler == null ? void 0 : handler.propsStore
821
- }, configuration)
822
- );
823
- return { selection, handler };
824
- }
825
-
826
- var __defProp$5 = Object.defineProperty;
827
- var __defProps$4 = Object.defineProperties;
828
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
829
- var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
830
- var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
831
- var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
832
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
833
- var __spreadValues$5 = (a, b) => {
834
- for (var prop in b || (b = {}))
835
- if (__hasOwnProp$5.call(b, prop))
836
- __defNormalProp$5(a, prop, b[prop]);
837
- if (__getOwnPropSymbols$5)
838
- for (var prop of __getOwnPropSymbols$5(b)) {
839
- if (__propIsEnum$5.call(b, prop))
840
- __defNormalProp$5(a, prop, b[prop]);
841
- }
842
- return a;
843
- };
844
- var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
845
- function getActiveDescendantName(treeName, nodeId) {
846
- return `${treeName}__${nodeId}`;
847
- }
848
- function getDomProps(_, treeName, type, par) {
849
- var _a;
850
- switch (type) {
851
- case "node": {
852
- const node = par;
853
- const tree = getTreeDataController(treeName);
854
- return __spreadProps$4(__spreadValues$5({
855
- "aria-disabled": node.isDisabled,
856
- "aria-expanded": node.isLeaf ? void 0 : !!node.isExpanded,
857
- "aria-label": node.label
858
- }, ((_a = tree.configuration.current) == null ? void 0 : _a.disableSelection) ? void 0 : {
859
- "aria-selected": node.isSelectable !== false && !node.isDisabled ? !!node.isSelected : void 0
860
- }), {
861
- className: node.className,
862
- color: node.color,
863
- "data-key": node.id,
864
- id: getActiveDescendantName(treeName, node.id),
865
- role: "treeitem",
866
- title: node.title
867
- });
868
- }
869
- default: {
870
- const tree = par;
871
- return {
872
- role: "tree",
873
- "aria-multiselectable": tree.isMultiple
874
- };
875
- }
876
- }
877
- }
878
-
879
- var __defProp$4 = Object.defineProperty;
880
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
881
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
882
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
883
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
884
- var __spreadValues$4 = (a, b) => {
885
- for (var prop in b || (b = {}))
886
- if (__hasOwnProp$4.call(b, prop))
887
- __defNormalProp$4(a, prop, b[prop]);
888
- if (__getOwnPropSymbols$4)
889
- for (var prop of __getOwnPropSymbols$4(b)) {
890
- if (__propIsEnum$4.call(b, prop))
891
- __defNormalProp$4(a, prop, b[prop]);
892
- }
893
- return a;
894
- };
895
- const SearchLabel = ({
896
- isLoading: isSearching,
897
- onDelete,
898
- searchString
899
- }) => {
900
- if (!searchString && !isSearching)
901
- return null;
902
- return /* @__PURE__ */ jsx(Box, { className: `tree__searchLabelBox ${isSearching ? "isLoading" : ""}`, children: isSearching ? /* @__PURE__ */ jsx(Spinner, { className: "tree__loading" }) : /* @__PURE__ */ jsxs(Box, { as: "label", className: "tree__searchLabel", children: [
903
- formatMessage(window.LBL_FILTERING_BY, { TOK1: searchString }),
904
- /* @__PURE__ */ jsx(
905
- IconButton,
906
- __spreadValues$4({
907
- icon: "Close",
908
- "aria-label": window.LBL_DELETE_FILTER,
909
- onClick: onDelete,
910
- title: window.LBL_DELETE_FILTER,
911
- size: "sm"
912
- }, getVariant("icon-inherit"))
913
- )
914
- ] }) });
915
- };
916
-
917
- const TreeContext = React.createContext({});
918
- function useTreeContext() {
919
- const context = React.useContext(TreeContext);
920
- if (!context)
921
- throw new Error("There is no tree context");
922
- return context;
923
- }
924
- const TreeContextProvider = ({
925
- children,
926
- value
927
- }) => {
928
- const Provider = React.useMemo(() => {
929
- return TreeContext.Provider;
930
- }, []);
931
- return /* @__PURE__ */ jsx(Provider, { value, children });
932
- };
933
-
934
- const DefaultIconRenderer = (props) => {
935
- var _a;
936
- return /* @__PURE__ */ jsx(
937
- Icon,
938
- {
939
- name: props.icon,
940
- title: "",
941
- size: (_a = props.iconSize) != null ? _a : "iconsm"
942
- }
943
- );
944
- };
945
-
946
- const DefaultLabelRenderer = (props) => {
947
- return /* @__PURE__ */ jsx(Box, { as: "span", children: props.label });
948
- };
949
-
950
- const Spacer = ({ level }) => {
951
- return /* @__PURE__ */ jsx(Fragment, { children: Array(level).fill("").map((_, i) => i).map((current) => /* @__PURE__ */ jsx(Box, { className: "spacer" }, current)) });
952
- };
953
-
954
- var __defProp$3 = Object.defineProperty;
955
- var __defProps$3 = Object.defineProperties;
956
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
957
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
958
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
959
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
960
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
961
- var __spreadValues$3 = (a, b) => {
962
- for (var prop in b || (b = {}))
963
- if (__hasOwnProp$3.call(b, prop))
964
- __defNormalProp$3(a, prop, b[prop]);
965
- if (__getOwnPropSymbols$3)
966
- for (var prop of __getOwnPropSymbols$3(b)) {
967
- if (__propIsEnum$3.call(b, prop))
968
- __defNormalProp$3(a, prop, b[prop]);
969
- }
970
- return a;
971
- };
972
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
973
- const TreeItemLabel = ({ level, treeKey }) => {
974
- var _a, _b, _c;
975
- const {
976
- handler,
977
- treeProps: { toggleNodesOnLabelClick }
978
- } = useTreeContext();
979
- const props = usePropsSelector(treeKey, {
980
- selector: (current) => current,
981
- comparator: (prevProps, newProps) => {
982
- return shallowEqual(prevProps, newProps) && shallowEqual(prevProps == null ? void 0 : prevProps.children, newProps == null ? void 0 : newProps.children);
983
- },
984
- propsStore: handler.propsStore
985
- });
986
- const Renderer = React.useMemo(
987
- () => {
988
- var _a2;
989
- return (_a2 = props.labelRenderer) != null ? _a2 : DefaultLabelRenderer;
990
- },
991
- [props.labelRenderer]
992
- );
993
- const handleToggle = React.useCallback(() => {
994
- handler.toggleNodeExpandedState(treeKey);
995
- }, [handler, treeKey]);
996
- const IconRenderer = React.useMemo(() => {
997
- return typeof props.icon === "string" ? DefaultIconRenderer : props.icon;
998
- }, [props.icon]);
999
- const onClick = React.useCallback(() => {
1000
- if (props.allowToggleExpandedFromLabel !== false)
1001
- handler.toggleNodeExpandedState(treeKey);
1002
- }, [handler, props.allowToggleExpandedFromLabel, treeKey]);
1003
- return /* @__PURE__ */ jsxs(
1004
- Box,
1005
- {
1006
- as: "span",
1007
- className: `tree__nodeItemLabel ${props.isFocused ? "focus" : ""}`,
1008
- children: [
1009
- /* @__PURE__ */ jsx(Spacer, { level }),
1010
- (props.isLoading || props.isExpanded && props.isLeaf !== true || props.isLeaf === false || ((_b = (_a = props.children) == null ? void 0 : _a.length) != null ? _b : 0) > 0 || props.isLeaf === void 0 && !props.hasLoaded && ((_c = handler.configuration.current) == null ? void 0 : _c.onLoadData)) && /* @__PURE__ */ jsx(Box, { className: "tree__expanderWrapper", children: props.isLoading ? /* @__PURE__ */ jsx(Spinner, { sx: { width: "iconSm", height: "iconSm" } }) : /* @__PURE__ */ jsx(
1011
- Icon,
1012
- {
1013
- className: "tree__expandIcon",
1014
- onClick: handleToggle,
1015
- name: props.isExpanded ? "MinusFilled" : "PlusFilled",
1016
- title: "",
1017
- size: "iconSm"
1018
- }
1019
- ) }),
1020
- props.icon && IconRenderer && /* @__PURE__ */ jsx(IconRenderer, __spreadValues$3({}, props)),
1021
- /* @__PURE__ */ jsx(
1022
- Box,
1023
- {
1024
- as: "span",
1025
- className: "tree__nodeItemLabelRenderer",
1026
- onClick: toggleNodesOnLabelClick !== false ? onClick : void 0,
1027
- children: /* @__PURE__ */ jsx(Renderer, __spreadProps$3(__spreadValues$3({}, props), { level }))
1028
- }
1029
- )
1030
- ]
1031
- }
1032
- );
1033
- };
1034
- var TreeItemLabel$1 = React.memo(TreeItemLabel);
1035
-
1036
- var __defProp$2 = Object.defineProperty;
1037
- var __defProps$2 = Object.defineProperties;
1038
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
1039
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
1040
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
1041
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
1042
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1043
- var __spreadValues$2 = (a, b) => {
1044
- for (var prop in b || (b = {}))
1045
- if (__hasOwnProp$2.call(b, prop))
1046
- __defNormalProp$2(a, prop, b[prop]);
1047
- if (__getOwnPropSymbols$2)
1048
- for (var prop of __getOwnPropSymbols$2(b)) {
1049
- if (__propIsEnum$2.call(b, prop))
1050
- __defNormalProp$2(a, prop, b[prop]);
1051
- }
1052
- return a;
1053
- };
1054
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
1055
- const TreeItem = ({ level, treeKey }) => {
1056
- const { handler, name, forceUpdate, treeProps } = useTreeContext();
1057
- const props = usePropsSelector(treeKey, {
1058
- selector: (current) => current,
1059
- comparator: (prevProps, newProps) => {
1060
- return shallowEqual(prevProps, newProps) && shallowEqual(prevProps == null ? void 0 : prevProps.children, newProps == null ? void 0 : newProps.children);
1061
- },
1062
- propsStore: handler.propsStore
1063
- });
1064
- const nodes = React.useMemo(
1065
- () => {
1066
- var _a, _b;
1067
- return (_b = (_a = props.children) == null ? void 0 : _a.map(
1068
- (current) => handler.propsStore.getFieldProps(current)
1069
- )) != null ? _b : [];
1070
- },
1071
- [props.children, handler.propsStore]
1072
- );
1073
- return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsxs(Box, __spreadProps$2(__spreadValues$2({ as: "li" }, getDomProps(treeProps, name, "node", props)), { children: [
1074
- /* @__PURE__ */ jsx(TreeItemLabel$1, { level, treeKey }),
1075
- /* @__PURE__ */ jsx(
1076
- TreeItemChildren$1,
1077
- {
1078
- forceUpdate,
1079
- role: "group",
1080
- level,
1081
- nodes
1082
- }
1083
- )
1084
- ] })) });
1085
- };
1086
- var TreeItem$1 = React.memo(TreeItem);
1087
-
1088
- var __defProp$1 = Object.defineProperty;
1089
- var __defProps$1 = Object.defineProperties;
1090
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
1091
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
1092
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
1093
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
1094
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1095
- var __spreadValues$1 = (a, b) => {
1096
- for (var prop in b || (b = {}))
1097
- if (__hasOwnProp$1.call(b, prop))
1098
- __defNormalProp$1(a, prop, b[prop]);
1099
- if (__getOwnPropSymbols$1)
1100
- for (var prop of __getOwnPropSymbols$1(b)) {
1101
- if (__propIsEnum$1.call(b, prop))
1102
- __defNormalProp$1(a, prop, b[prop]);
1103
- }
1104
- return a;
1105
- };
1106
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
1107
- var __objRest = (source, exclude) => {
1108
- var target = {};
1109
- for (var prop in source)
1110
- if (__hasOwnProp$1.call(source, prop) && exclude.indexOf(prop) < 0)
1111
- target[prop] = source[prop];
1112
- if (source != null && __getOwnPropSymbols$1)
1113
- for (var prop of __getOwnPropSymbols$1(source)) {
1114
- if (exclude.indexOf(prop) < 0 && __propIsEnum$1.call(source, prop))
1115
- target[prop] = source[prop];
1116
- }
1117
- return target;
1118
- };
1119
- const TreeItemChildren = React.forwardRef((_a, ref) => {
1120
- var _b = _a, { level, nodes, forceUpdate } = _b, props = __objRest(_b, ["level", "nodes", "forceUpdate"]);
1121
- const { handler } = useTreeContext();
1122
- return /* @__PURE__ */ jsx(Box, __spreadProps$1(__spreadValues$1({ ref, as: "ul" }, props), { children: nodes == null ? void 0 : nodes.map((current) => {
1123
- const currentProps = handler.propsStore.getFieldProps(current.id);
1124
- if (!currentProps)
1125
- return null;
1126
- return currentProps.isFiltered ? null : /* @__PURE__ */ jsx(TreeItem$1, { level: level + 1, treeKey: current.id }, current.id);
1127
- }) }));
1128
- });
1129
- TreeItemChildren.displayName = "TreeItemChildren";
1130
- var TreeItemChildren$1 = React.memo(TreeItemChildren);
1131
-
1132
- function useTreeData({ name, treeProps }) {
1133
- const props = useLatest(treeProps);
1134
- const handler = React.useMemo(
1135
- () => new TreeDataController(name, props),
1136
- // eslint-disable-next-line react-hooks/exhaustive-deps
1137
- []
1138
- );
1139
- useMount(() => {
1140
- var _a;
1141
- (_a = treeProps == null ? void 0 : treeProps.initialNodes) == null ? void 0 : _a.forEach((current) => handler.append(current));
1142
- });
1143
- const data = usePropsSelector("root", {
1144
- comparator: shallowEqual,
1145
- propsStore: handler.propsStore,
1146
- selector: (current) => {
1147
- var _a;
1148
- return {
1149
- children: (_a = current.children) != null ? _a : [],
1150
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
1151
- forceUpdate: current.forceUpdate
1152
- };
1153
- }
1154
- });
1155
- const keyHandlerId = React.useMemo(() => `keyHandler${uniqueId()}`, []);
1156
- const keyHandlerRef = React.useRef(null);
1157
- const focusOnNode = React.useCallback(
1158
- (key, retry = 3) => {
1159
- var _a, _b;
1160
- if (keyHandlerRef.current) {
1161
- const focusElement = keyHandlerRef.current.querySelector(
1162
- `[data-key="${key}"]`
1163
- );
1164
- (_a = keyHandlerRef.current) == null ? void 0 : _a.focus();
1165
- if (focusElement) {
1166
- const actualFocusElement = ((_b = treeProps.focusGetter) != null ? _b : (liElement) => liElement.querySelector(
1167
- ":scope > .tree__nodeItemLabel"
1168
- ))(focusElement);
1169
- const nodeProps = handler.propsStore.getFieldProps(key);
1170
- if (!treeProps.focusGetter || !nodeProps.labelRenderer)
1171
- actualFocusElement.classList.add("focused");
1172
- actualFocusElement.scrollIntoView({
1173
- inline: "nearest",
1174
- block: "nearest"
1175
- });
1176
- } else if (retry > 0)
1177
- setTimeout(() => focusOnNode(key, retry - 1), 30);
1178
- }
1179
- },
1180
- [handler.propsStore, treeProps.focusGetter]
1181
- );
1182
- React.useEffect(() => {
1183
- const unsuscribe1 = handler.on("mustFocus", (node) => focusOnNode(node));
1184
- const unsuscribe2 = handler.on(
1185
- "onArrowUpOnFirstElement",
1186
- () => {
1187
- var _a;
1188
- return (_a = treeProps.onArrowUpOnFirstElement) == null ? void 0 : _a.call(treeProps);
1189
- }
1190
- );
1191
- return () => {
1192
- unsuscribe1();
1193
- unsuscribe2();
1194
- };
1195
- }, [focusOnNode, handler, treeProps]);
1196
- return {
1197
- data,
1198
- handler,
1199
- keyHandler: {
1200
- id: keyHandlerId,
1201
- onKeyDown: React.useCallback(
1202
- (ev) => {
1203
- var _a;
1204
- if (ev.key === "Enter") {
1205
- const key = handler.state.focusedNode;
1206
- if (key) {
1207
- const nodeProps = handler.propsStore.getFieldProps(key);
1208
- (_a = treeProps.onNodeClick) == null ? void 0 : _a.call(treeProps, ev, nodeProps);
1209
- }
1210
- } else {
1211
- handler.handleKey(ev);
1212
- }
1213
- },
1214
- [handler, treeProps]
1215
- ),
1216
- onMouseDown: React.useCallback(
1217
- (ev) => {
1218
- var _a;
1219
- const previousFocused = handler.state.focusedNode;
1220
- if (previousFocused !== null && ev.shiftKey && ((_a = handler.configuration.current) == null ? void 0 : _a.isMultiple))
1221
- ev.preventDefault();
1222
- },
1223
- [handler.configuration, handler.state.focusedNode]
1224
- ),
1225
- onClick: React.useCallback(
1226
- (ev) => {
1227
- var _a, _b;
1228
- if (getSpecificParent(ev.target, (current) => current.classList.contains("tree__expandIcon")))
1229
- return;
1230
- const node = getSpecificParent(
1231
- ev.target,
1232
- (current) => !!current.getAttribute("data-key")
1233
- );
1234
- if (node) {
1235
- const previousFocused = handler.state.focusedNode;
1236
- const key = node.getAttribute("data-key");
1237
- const nodeProps = handler.propsStore.getFieldProps(key);
1238
- (_a = treeProps.onNodeClick) == null ? void 0 : _a.call(treeProps, ev, nodeProps);
1239
- if (previousFocused !== null && ev.shiftKey && ((_b = handler.configuration.current) == null ? void 0 : _b.isMultiple)) {
1240
- selectAllNodesBetweenTwoNodes(
1241
- handler,
1242
- previousFocused,
1243
- key,
1244
- true
1245
- );
1246
- } else {
1247
- handler.setFocusedNode(key);
1248
- handler.setSelectedNodesByClickEvent(ev);
1249
- }
1250
- if (key)
1251
- focusOnNode(key);
1252
- }
1253
- },
1254
- [focusOnNode, handler, treeProps]
1255
- ),
1256
- ref: keyHandlerRef
1257
- }
1258
- };
1259
- }
1260
-
1261
- var __defProp = Object.defineProperty;
1262
- var __defProps = Object.defineProperties;
1263
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1264
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1265
- var __hasOwnProp = Object.prototype.hasOwnProperty;
1266
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
1267
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1268
- var __spreadValues = (a, b) => {
1269
- for (var prop in b || (b = {}))
1270
- if (__hasOwnProp.call(b, prop))
1271
- __defNormalProp(a, prop, b[prop]);
1272
- if (__getOwnPropSymbols)
1273
- for (var prop of __getOwnPropSymbols(b)) {
1274
- if (__propIsEnum.call(b, prop))
1275
- __defNormalProp(a, prop, b[prop]);
1276
- }
1277
- return a;
1278
- };
1279
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1280
- const Tree = (props) => {
1281
- var _a, _b, _c;
1282
- const { data, handler, keyHandler } = useTreeData({
1283
- name: props.name,
1284
- treeProps: __spreadValues({}, props)
1285
- });
1286
- const [isLoading, setIsLoading] = React.useState(false);
1287
- const [currentSearchString, setCurrentSearchString] = React.useState("");
1288
- const isTreeLoading = useTreeSelector(handler, {
1289
- selector: (current) => current.isLoading
1290
- });
1291
- React.useEffect(() => {
1292
- setIsLoading(isTreeLoading);
1293
- }, [isTreeLoading]);
1294
- const search = useDebounceFn(
1295
- () => {
1296
- if (props.filterString === void 0)
1297
- return;
1298
- setIsLoading(true);
1299
- React.startTransition(() => {
1300
- setCurrentSearchString(props.filterString);
1301
- });
1302
- if (props.filterString !== void 0 && props.filterString !== "") {
1303
- unfilterNodes(handler);
1304
- matchNodesAgainstString(handler, props.filterString);
1305
- handler.forceEmitUpdate();
1306
- } else {
1307
- unfilterNodes(handler);
1308
- handler.forceEmitUpdate();
1309
- }
1310
- setTimeout(() => setIsLoading(false), 0);
1311
- },
1312
- { wait: 200 }
1313
- );
1314
- React.useEffect(() => {
1315
- search.run();
1316
- if (!props.filterString)
1317
- search.flush();
1318
- }, [props.filterString]);
1319
- usePropsSelector(
1320
- handler.stateKey,
1321
- {
1322
- propsStore: handler.propsStore,
1323
- selector: (current) => current,
1324
- comparator: (prevProps, newProps) => {
1325
- var _a2;
1326
- if (props.onSelect && !shallowEqual(prevProps == null ? void 0 : prevProps.selectedNodes, newProps == null ? void 0 : newProps.selectedNodes)) {
1327
- props.onSelect(
1328
- ((_a2 = newProps == null ? void 0 : newProps.selectedNodes) != null ? _a2 : []).map(
1329
- (currentId) => handler.propsStore.getFieldProps(currentId)
1330
- )
1331
- );
1332
- }
1333
- return true;
1334
- }
1335
- }
1336
- );
1337
- const { focusedNode } = usePropsSelector(handler.stateKey, {
1338
- propsStore: handler.propsStore,
1339
- selector: (current) => ({
1340
- focusedNode: current.focusedNode
1341
- })
1342
- });
1343
- useMount(() => {
1344
- if (props.getHandler)
1345
- props.getHandler(handler);
1346
- });
1347
- useUnmount(() => handler.destructor());
1348
- const contextValue = React.useMemo(() => {
1349
- const actualValue = {
1350
- handler,
1351
- name: props.name,
1352
- forceUpdate: data.forceUpdate,
1353
- focusGetter: props.focusGetter,
1354
- treeProps: props
1355
- };
1356
- return actualValue;
1357
- }, [handler, props, data.forceUpdate]);
1358
- return /* @__PURE__ */ jsx(TreeContextProvider, { value: contextValue, children: /* @__PURE__ */ jsxs(
1359
- Box,
1360
- __spreadProps(__spreadValues({
1361
- className: `tree ${(_a = props.className) != null ? _a : ""}`
1362
- }, getVariant((_b = props.variant) != null ? _b : "layout.common.trees.primary")), {
1363
- children: [
1364
- /* @__PURE__ */ jsx(
1365
- SearchLabel,
1366
- {
1367
- isLoading: (_c = props.isLoading) != null ? _c : isLoading,
1368
- onDelete: props.onDeleteFilterString,
1369
- searchString: props.hideSearchLabel ? "" : currentSearchString
1370
- }
1371
- ),
1372
- /* @__PURE__ */ jsx(
1373
- TreeItemChildren$1,
1374
- __spreadValues({
1375
- "aria-activedescendant": focusedNode !== null ? getActiveDescendantName(props.name, focusedNode) : void 0,
1376
- "aria-label": props.label,
1377
- as: "ul",
1378
- forceUpdate: data.forceUpdate,
1379
- level: -1,
1380
- nodes: React.useMemo(
1381
- () => data.children.map(
1382
- (current) => handler.propsStore.getFieldProps(current)
1383
- ),
1384
- [data.children, handler.propsStore]
1385
- ),
1386
- role: "tree",
1387
- tabIndex: 0
1388
- }, keyHandler)
1389
- )
1390
- ]
1391
- })
1392
- ) });
1393
- };
1394
- var Tree$1 = memo(Tree);
1395
-
1396
- export { Tree$1 as Tree, TreeDataController, useTreeContext, useTreeData, useTreeDataController, useTreeSelector, useTreeSelectorByName };
1
+ import{jsx as f,jsxs as O,Fragment as U}from"react/jsx-runtime";import{useMount as D,useDebounceFn as Se,useUnmount as me}from"ahooks";import p,{useState as ve,useEffect as be,memo as Ne}from"react";import{shallowEqual as N}from"react-redux";import{Box as m,Spinner as k}from"theme-ui";import{EventEmitter as T,PropsStore as Fe,addBoundary as Pe,getSpecificParent as _,usePropsSelector as b,formatMessage as ye,useLatest as Ee}from"@apia/util";import{IconButton as Oe}from"@apia/components";import{getVariant as A}from"@apia/theme";import{Icon as K}from"@apia/icons";import{uniqueId as we}from"lodash-es";const x=(t,e,r)=>{const o=t.propsStore.getFieldProps(e);if(e!=="root"&&(o.isDisabled||!o.isExpanded)||o.children.length===0)return null;for(let l=o.children.length-1;l>=0;l--){const s=o.children[l],d=t.propsStore.getFieldProps(s);if(!r||!d.isFiltered){const n=x(t,s,r);return n!==null?n:s}}return null},Ie=(t,e,r)=>{var o,l;const s=t.propsStore.getFieldProps(e),d=t.propsStore.getFieldProps(s.parentId);let n=(l=(o=d.children)==null?void 0:o.findIndex(i=>i===s.id))!=null?l:-1;for(;n>0;){const i=t.propsStore.getFieldProps(d.children[n-1]),a=x(t,i.id,r);if(a!==null)return a;if(!r||!i.isFiltered)return i.id;n--}return s.parentId==="root"?null:s.parentId},L=(t,e)=>{const r=t.propsStore.getFieldProps(e);for(const o of r.children)if(!t.propsStore.getFieldProps(o).isFiltered)return o;return null},P=(t,e,r,o)=>{var l,s;const d=t.propsStore.getFieldProps(e),n=t.propsStore.getFieldProps(d.parentId);let i=(s=(l=n.children)==null?void 0:l.findIndex(a=>a===d.id))!=null?s:1/0;if(!r&&d.isExpanded){if(!o&&d.children.length>0)return d.children[0];const a=L(t,d.id);if(a!==null)return a}for(;i<n.children.length-1;){const a=n.children[i+1];if(!o||!t.propsStore.getFieldProps(a).isFiltered)return a;i++}return d.parentId==="root"?null:P(t,n.id,!0,o)},_e=(t,e,r,o)=>{let l=e;do if(l=P(t,l,!1,o),l!==null){const n=t.propsStore.getFieldProps(l);if((!n.isFiltered||!o)&&n.label.toUpperCase().startsWith(r.toUpperCase()))return l}while(l!==null);const s=t.propsStore.getFieldProps(e),d=t.propsStore.getFieldProps(s.parentId).children.findIndex(n=>n===e);if(s.parentId!=="root"||d>0){const[n]=t.propsStore.getFieldProps("root").children,i=t.propsStore.getFieldProps(n);if(n&&(!o||!i.isFiltered)&&i.label.toUpperCase().startsWith(r.toUpperCase()))return n;l=n;do if(l=P(t,l,!1,o),l){const a=t.propsStore.getFieldProps(l);if((!o||!a.isFiltered)&&a.label.toUpperCase().startsWith(r.toUpperCase()))return l}while(l!==e&&l!==null)}return null},M=(t,e)=>{const r=[e];let o=e;do o=t.propsStore.getFieldProps(o).parentId,r.unshift(o);while(o!=="root");return r},xe=(t,e,r)=>{const o=M(t,e),l=M(t,r);for(let s=o.length-1;s>=0;s--){const d=l.indexOf(o[s]);if(d!==-1)return{commonAncestor:o[s],oneNodeAncestorChild:o[s+1],anotherNodeAncestorChild:l[d+1]}}return console.warn("This point should have never been reached since the root node is common to all nodes",{oneNodeId:e,anotherNodeId:r,oneNodePath:o,anotherNodePath:l}),null},R=t=>{t.state.filteredNodes.forEach(r=>{t.propsStore.updateField(r,{isFiltered:!1},{noEmit:!0})});const e=t.propsStore.getFieldProps("root").children[0];e&&t.setFocusedNode(e),t.setState({filteredNodes:[]})},B=(t,e,r="root")=>{let o=!1,l=null;const s=t.propsStore.getFieldProps(r);r!=="root"&&s.label.match(new RegExp(e,"i"))&&(t.propsStore.updateField(r,{isFiltered:!1}),o=!0,l=s.id,t.setState({filteredNodes:t.state.filteredNodes.filter(n=>n!==r)}));let d=!1;return s.children.forEach(n=>{d=B(t,e,n)||o,o=d||o,o&&!l&&(l=n)}),d&&(t.propsStore.updateField(r,{isExpanded:!0}),o&&!l&&(l=r)),o||(t.propsStore.updateField(r,{isFiltered:!0},{noEmit:!0}),t.setState({filteredNodes:[...t.state.filteredNodes,r]})),l!==null&&t.setFocusedNode(l),o},C=(t,e,r,o)=>{const l=xe(t,e,r);if(l){const{anotherNodeAncestorChild:s,commonAncestor:d,oneNodeAncestorChild:n}=l,i=t.propsStore.getFieldProps(d),a=i.children.findIndex(g=>g===n),c=i.children.findIndex(g=>g===s);let u=a>=c?r:e;const h=a<c?r:e;t.toggleNodeSelectedState(u,!0);do u=P(t,u,o),u!==null&&t.toggleNodeSelectedState(u,!0);while(u!==h&&u!==null)}};var Le=Object.defineProperty,Ce=Object.defineProperties,$e=Object.getOwnPropertyDescriptors,z=Object.getOwnPropertySymbols,je=Object.prototype.hasOwnProperty,Ue=Object.prototype.propertyIsEnumerable,G=(t,e,r)=>e in t?Le(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,v=(t,e)=>{for(var r in e||(e={}))je.call(e,r)&&G(t,r,e[r]);if(z)for(var r of z(e))Ue.call(e,r)&&G(t,r,e[r]);return t},H=(t,e)=>Ce(t,$e(e));const y={},W=new class extends T{emit(t,e){super.emit(t,e),y[e.name]=e.controller}};function q(t){const[e,r]=ve(y[t]);return be(()=>(y[t]!==e&&r(y[t]),W.on("addController",o=>{o.name===t&&r(o.controller)})),[]),e}function De(t){return y[t]}class V extends T{constructor(e,r,o=new Fe({logCommands:{propsStore:`treeProps_${e}`,propsLog:`treeLog_${e}`,propsSuscriptors:`propsSuscriptors_${e}`,updateProp:`updateProp_${e}`}})){var l;super(),this.name=e,this.propsStore=o,this.hasApendedFirstChild=!1,this.missingParents=[],this.nonEmittedUpdates=[],this.stateKey="treeState",this._configuration=r??{current:{emitUpdates:!0}},this._configuration.current.emitUpdates=(l=this._configuration.current.emitUpdates)!=null?l:!0,this.setState(this.getInitialState()),W.emit("addController",{name:e,controller:this}),this.initRoot()}get configuration(){return v({},this._configuration)}get state(){return this.propsStore.getFieldProps(this.stateKey)}get stateStore(){return this.propsStore}destructor(){this.propsStore.destructor()}append(e){var r,o,l,s,d,n;const i=H(v({},e),{nodeProps:(r=e.nodeProps)!=null?r:{}});if((o=this.propsStore.getFieldProps(i.id))!=null&&o.children){console.error("DUPLICATED NODE: The conflict origin is ",i,this);return}let a;i.parentId!==void 0&&(l=this.propsStore.getFieldProps(i.parentId))!=null&&l.children?a=i.parentId:(a="root",i.parentId&&this.missingParents.push(i.parentId),i.actualParentId=i.parentId,i.parentId="root"),this.propsStore.updateField(i.id,H(v({},i),{children:(s=i.children)!=null?s:[]}),{isUrgent:!0}),this.setState({length:this.state.length+1}),this.missingParents.includes(i.id)&&(this.propsStore.getFieldProps("root").children.forEach(c=>{this.propsStore.getFieldProps(c).actualParentId===i.id&&this.move(c,i.id)}),this.missingParents=this.missingParents.filter(c=>c!==i.id)),this.propsStore.updateField(a,{children:[...this.propsStore.getFieldProps(a).children,i.id]},{noEmit:!((d=this._configuration.current)!=null&&d.emitUpdates)}),(n=this._configuration.current)!=null&&n.emitUpdates||this.nonEmittedUpdates.push(a),this.hasApendedFirstChild||(this.hasApendedFirstChild=!0,this.setFocusedNode(i.id,!0)),i.isExpanded&&this.toggleNodeExpandedState(i.id,!0)}batchInit(){this.config({emitUpdates:!1}),this.setState({isLoading:!0},{isUrgent:!0})}batchFinish(){this.config({emitUpdates:!0}),setTimeout(()=>this.setState({isLoading:!1}),0)}config(e){var r;!((r=this._configuration.current)!=null&&r.emitUpdates)&&e.emitUpdates&&(this.nonEmittedUpdates.forEach(o=>this.propsStore.updateField(o,{children:[...this.propsStore.getFieldProps(o).children]})),this.nonEmittedUpdates=[]),Object.assign(this._configuration.current,e)}deselectAll(){this.state.selectedNodes.forEach(e=>this.propsStore.updateField(e,{isSelected:!1})),this.setState({selectedNodes:[]})}forceEmitUpdate(){var e;this.propsStore.updateField("root",{forceUpdate:((e=this.propsStore.getFieldProps("root").forceUpdate)!=null?e:0)+1})}getInitialState(){return{expandedNodes:[],filteredNodes:[],focusedNode:null,isLoading:!1,length:0,selectedNodes:[]}}getNodesAsArray(){const e=v({},this.propsStore.fields);return delete e[this.stateKey],delete e.root,Object.values(e)}getNodesIds(){const e=v({},this.propsStore.fields);return delete e[this.stateKey],delete e.root,Object.keys(e)}getParentId(e){return this.propsStore.getFieldProps(e).parentId}handleKey(e){var r;const o=this.state.focusedNode,l=this.propsStore.getFieldProps(o);if(e.key==="*"){if(this.state.focusedNode===null)return;this.propsStore.getFieldProps(this.propsStore.getFieldProps(this.state.focusedNode).parentId).children.forEach(s=>this.toggleNodeExpandedState(s,!0))}else if(e.key.match(/^\w$/)){const s=_e(this,o,e.key,!0);s!==null&&(this.setFocusedNode(s),this.emit("mustFocus",s))}else switch(e.code){case"Home":{const s=L(this,"root");if(s===null)return;e.shiftKey&&e.ctrlKey&&this.state.focusedNode!==null&&C(this,s,this.state.focusedNode,!0),this.setFocusedNode(s),this.emit("mustFocus",s);break}case"End":{const s=x(this,"root",!0);s!==null&&(e.shiftKey&&e.ctrlKey&&this.state.focusedNode!==null&&C(this,s,this.state.focusedNode,!0),this.setFocusedNode(s),this.emit("mustFocus",s));break}case"ArrowRight":{if(l.isLeaf)return;if(e.preventDefault(),l.isExpanded){const s=L(this,l.id);s!==null&&(this.setFocusedNode(s),this.emit("mustFocus",s))}else this.toggleNodeExpandedState(l.id,!0);break}case"ArrowLeft":{e.preventDefault(),l.isLeaf||!l.isExpanded?l.parentId!=="root"&&l.parentId!==void 0&&(this.setFocusedNode(l.parentId),this.emit("mustFocus",l.parentId)):this.toggleNodeExpandedState(l.id,!1);break}case"ArrowUp":{e.preventDefault();const s=Ie(this,l.id,!0);s!==null?(e.shiftKey&&this.toggleNodeSelectedState(s,!0),this.setFocusedNode(s),this.emit("mustFocus",s)):this.emit("onArrowUpOnFirstElement",!0);break}case"ArrowDown":{e.preventDefault();const s=P(this,l.id,!1,!0);s!==null&&(e.shiftKey&&this.toggleNodeSelectedState(s,!0),this.setFocusedNode(s),this.emit("mustFocus",s));break}case"Space":{if((r=this._configuration.current)!=null&&r.disableSelection)return;e.preventDefault(),this.toggleNodeSelectedState(l.id);break}}}isNode(e){return typeof e=="object"&&"parentId"in e}isNodeContainer(e){return typeof e=="object"&&!this.isNode(e)}includes(e){return!!this.propsStore.getFieldProps(e.id)}initRoot(){this.propsStore.updateField("root",{children:[],id:"root"},{isUrgent:!0})}move(e,r,o){var l,s;const d=this.propsStore.getFieldProps(this.propsStore.getFieldProps(e).parentId),n=this.propsStore.getFieldProps(r);if(!d){console.warn("The current node does not belong to the tree.",e);return}if(!n){console.warn("The destination node does not belong to the tree. No action will be made",r);return}if(d.children=(l=d.children)==null?void 0:l.filter(i=>i!==e),n.children||(n.children=[]),!o)n.children.push(e);else if(o.position)n.children.splice(o.position-1,0,e);else{const i=o.after?o.after:o.before,a=i&&this.isNode(i)?i.id:i,c=n.children.findIndex(h=>h===a),u=Pe(o.before!==void 0?c:c+1,0);u===-1||u===n.children.length?n.children.push(e):n.children.splice(u,0,e)}this.propsStore.updateField(d.id,{children:[...(s=d.children)!=null?s:[]]}),this.propsStore.updateField(n.id,{children:[...n.children]}),this.propsStore.updateField(e,{parentId:n.id})}remove(e,r=!0){var o,l;const s=this.isNode(e)?e.id:e,d=this.propsStore.getFieldProps(s);if(!d)return;const n=this.propsStore.getFieldProps(d.parentId);n&&this.propsStore.updateField(n.id,{children:(o=n.children)==null?void 0:o.filter(i=>i!==s)}),(l=d.children)==null||l.forEach(i=>{r?this.remove(i):this.move(i,"root")}),this.setState({selectedNodes:this.state.selectedNodes.filter(i=>i!==s),focusedNode:this.state.focusedNode===s?null:this.state.focusedNode,length:this.state.length-1}),this.propsStore.removeField(s)}removeMultiple(e,r=!0){e.forEach(o=>this.remove(o,r))}removeAll(){this.hasApendedFirstChild=!1,this.setState({focusedNode:null},{isUrgent:!0}),this.setSelectedNodes([]),this.initRoot(),Object.keys(this.propsStore.fields).forEach(e=>{["root",this.stateKey].includes(e)||this.propsStore.removeField(e)})}selectAll(){this.setState({selectedNodes:this.getNodesIds()}),this.state.selectedNodes.forEach(e=>this.propsStore.updateField(e,{isSelected:!0}))}setFocusedNode(e,r){var o,l;this.state.focusedNode!==null&&this.propsStore.updateField(this.state.focusedNode,{isFocused:!1}),this.setState({focusedNode:e}),!((o=this._configuration.current)!=null&&o.isMultiple)&&!r&&((l=this._configuration.current)==null?void 0:l.selectionMode)!=="explicit"&&this.setSelectedNodes([e]),this.propsStore.updateField(e,{isFocused:!0})}setSelectedNodes(e,r=!1){var o;(o=this._configuration.current)!=null&&o.disableSelection&&!r||(this.state.selectedNodes.forEach(l=>this.propsStore.updateField(l,{isSelected:!1})),this.setState({selectedNodes:e.filter(l=>{const{isSelectable:s}=this.propsStore.getFieldProps(l);return s!==!1&&this.propsStore.updateField(l,{isSelected:!0}),s!==!1})}))}setSelectedNodesByClickEvent(e){var r,o,l,s;if((r=this._configuration.current)!=null&&r.disableSelection)return;const d=(o=_(e.target,n=>n.getAttribute("role")==="treeitem"))==null?void 0:o.getAttribute("data-key");if(d){const n=this.propsStore.getFieldProps(d);if(n.isDisabled||n.isSelectable===!1)return;const i=[...this.state.selectedNodes],a=(l=this._configuration.current)!=null&&l.isMultiple?n.isSelected?i.filter(c=>c!==d):[...i,d]:[d];this.setState({selectedNodes:a}),i.forEach(c=>{a.includes(c)||this.propsStore.updateField(c,{isSelected:!1})}),this.propsStore.updateField(d,{isSelected:(s=this._configuration.current)!=null&&s.isMultiple?!n.isSelected:!0})}else console.warn("Cannot set selection, no treeitem found",e)}setState(e,r){this.propsStore.updateField(this.stateKey,v(v({},this.state),e),r)}toggleNodeExpandedState(e,r){var o,l,s,d,n;const i=this.propsStore.getFieldProps(e);if(!(i.isDisabled||i.isLeaf||i.isLoading))if((o=this._configuration.current)!=null&&o.onLoadData&&!i.hasLoaded)this.propsStore.updateField(e,{isLoading:!0}),(l=this._configuration.current)==null||l.onLoadData(i).finally(()=>{var a,c;this.propsStore.updateField(e,{isLoading:!1,isExpanded:!0,hasLoaded:!0}),this.setState({expandedNodes:[...this.state.expandedNodes,e]}),(c=(a=this._configuration.current)==null?void 0:a.onExpand)==null||c.call(a,this.propsStore.getFieldProps(e))});else{const{expandedNodes:a}=this.state,c=r!==void 0?r:!a.includes(e);if((s=this.propsStore.getFieldProps(e))!=null&&s.isDisabled)return;this.setState({expandedNodes:c?[...a,e]:a.filter(u=>u!==e)}),this.propsStore.updateField(e,{isExpanded:c}),(n=(d=this._configuration.current)==null?void 0:d.onExpand)==null||n.call(d,this.propsStore.getFieldProps(e))}}toggleNodeSelectedState(e,r){var o,l;if((o=this._configuration.current)!=null&&o.disableSelection)return;const s=this.propsStore.getFieldProps(e);if(s.isDisabled||s.isSelectable===!1)return;const d=r!==void 0?r:!this.state.selectedNodes.includes(e);d&&!((l=this._configuration.current)!=null&&l.isMultiple)&&this.state.selectedNodes[0]&&this.toggleNodeSelectedState(this.state.selectedNodes[0],!1),this.propsStore.updateField(e,{isSelected:d}),this.setState({selectedNodes:d?[...this.state.selectedNodes,e]:this.state.selectedNodes.filter(n=>n!==e)})}}function Y(t,e){var r;return b((r=t?.stateKey)!=null?r:"__NO__TREE__KEY__",v({propsStore:t?.propsStore},e))}function ke(t,e){var r;const o=q(t);return{selection:b((r=o?.stateKey)!=null?r:"__NO__TREE__KEY__",v({propsStore:o?.propsStore},e)),handler:o}}var Te=Object.defineProperty,Ae=Object.defineProperties,Ke=Object.getOwnPropertyDescriptors,J=Object.getOwnPropertySymbols,Me=Object.prototype.hasOwnProperty,Re=Object.prototype.propertyIsEnumerable,Q=(t,e,r)=>e in t?Te(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e)=>{for(var r in e||(e={}))Me.call(e,r)&&Q(t,r,e[r]);if(J)for(var r of J(e))Re.call(e,r)&&Q(t,r,e[r]);return t},ze=(t,e)=>Ae(t,Ke(e));function X(t,e){return`${t}__${e}`}function Ge(t,e,r,o){var l;switch(r){case"node":{const s=o,d=De(e);return ze(Be({"aria-disabled":s.isDisabled,"aria-expanded":s.isLeaf?void 0:!!s.isExpanded,"aria-label":s.label},(l=d.configuration.current)!=null&&l.disableSelection?void 0:{"aria-selected":s.isSelectable!==!1&&!s.isDisabled?!!s.isSelected:void 0}),{className:s.className,color:s.color,"data-key":s.id,id:X(e,s.id),role:"treeitem",title:s.title})}default:return{role:"tree","aria-multiselectable":o.isMultiple}}}var He=Object.defineProperty,Z=Object.getOwnPropertySymbols,We=Object.prototype.hasOwnProperty,qe=Object.prototype.propertyIsEnumerable,ee=(t,e,r)=>e in t?He(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ve=(t,e)=>{for(var r in e||(e={}))We.call(e,r)&&ee(t,r,e[r]);if(Z)for(var r of Z(e))qe.call(e,r)&&ee(t,r,e[r]);return t};const Ye=({isLoading:t,onDelete:e,searchString:r})=>!r&&!t?null:f(m,{className:`tree__searchLabelBox ${t?"isLoading":""}`,children:t?f(k,{className:"tree__loading"}):O(m,{as:"label",className:"tree__searchLabel",children:[ye(window.LBL_FILTERING_BY,{TOK1:r}),f(Oe,Ve({icon:"Close","aria-label":window.LBL_DELETE_FILTER,onClick:e,title:window.LBL_DELETE_FILTER,size:"sm"},A("icon-inherit")))]})}),te=p.createContext({});function w(){const t=p.useContext(te);if(!t)throw new Error("There is no tree context");return t}const Je=({children:t,value:e})=>{const r=p.useMemo(()=>te.Provider,[]);return f(r,{value:e,children:t})},Qe=t=>{var e;return f(K,{name:t.icon,title:"",size:(e=t.iconSize)!=null?e:"iconsm"})},Xe=t=>f(m,{as:"span",children:t.label}),Ze=({level:t})=>f(U,{children:Array(t).fill("").map((e,r)=>r).map(e=>f(m,{className:"spacer"},e))});var et=Object.defineProperty,tt=Object.defineProperties,rt=Object.getOwnPropertyDescriptors,re=Object.getOwnPropertySymbols,ot=Object.prototype.hasOwnProperty,st=Object.prototype.propertyIsEnumerable,oe=(t,e,r)=>e in t?et(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,se=(t,e)=>{for(var r in e||(e={}))ot.call(e,r)&&oe(t,r,e[r]);if(re)for(var r of re(e))st.call(e,r)&&oe(t,r,e[r]);return t},it=(t,e)=>tt(t,rt(e));const lt=({level:t,treeKey:e})=>{var r,o,l;const{handler:s,treeProps:{toggleNodesOnLabelClick:d}}=w(),n=b(e,{selector:h=>h,comparator:(h,g)=>N(h,g)&&N(h?.children,g?.children),propsStore:s.propsStore}),i=p.useMemo(()=>{var h;return(h=n.labelRenderer)!=null?h:Xe},[n.labelRenderer]),a=p.useCallback(()=>{s.toggleNodeExpandedState(e)},[s,e]),c=p.useMemo(()=>typeof n.icon=="string"?Qe:n.icon,[n.icon]),u=p.useCallback(()=>{n.allowToggleExpandedFromLabel!==!1&&s.toggleNodeExpandedState(e)},[s,n.allowToggleExpandedFromLabel,e]);return O(m,{as:"span",className:`tree__nodeItemLabel ${n.isFocused?"focus":""}`,children:[f(Ze,{level:t}),(n.isLoading||n.isExpanded&&n.isLeaf!==!0||n.isLeaf===!1||((o=(r=n.children)==null?void 0:r.length)!=null?o:0)>0||n.isLeaf===void 0&&!n.hasLoaded&&((l=s.configuration.current)==null?void 0:l.onLoadData))&&f(m,{className:"tree__expanderWrapper",children:n.isLoading?f(k,{sx:{width:"iconSm",height:"iconSm"}}):f(K,{className:"tree__expandIcon",onClick:a,name:n.isExpanded?"MinusFilled":"PlusFilled",title:"",size:"iconSm"})}),n.icon&&c&&f(c,se({},n)),f(m,{as:"span",className:"tree__nodeItemLabelRenderer",onClick:d!==!1?u:void 0,children:f(i,it(se({},n),{level:t}))})]})};var nt=p.memo(lt),dt=Object.defineProperty,at=Object.defineProperties,ct=Object.getOwnPropertyDescriptors,ie=Object.getOwnPropertySymbols,pt=Object.prototype.hasOwnProperty,ut=Object.prototype.propertyIsEnumerable,le=(t,e,r)=>e in t?dt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ht=(t,e)=>{for(var r in e||(e={}))pt.call(e,r)&&le(t,r,e[r]);if(ie)for(var r of ie(e))ut.call(e,r)&&le(t,r,e[r]);return t},ft=(t,e)=>at(t,ct(e));const gt=({level:t,treeKey:e})=>{const{handler:r,name:o,forceUpdate:l,treeProps:s}=w(),d=b(e,{selector:i=>i,comparator:(i,a)=>N(i,a)&&N(i?.children,a?.children),propsStore:r.propsStore}),n=p.useMemo(()=>{var i,a;return(a=(i=d.children)==null?void 0:i.map(c=>r.propsStore.getFieldProps(c)))!=null?a:[]},[d.children,r.propsStore]);return f(U,{children:O(m,ft(ht({as:"li"},Ge(s,o,"node",d)),{children:[f(nt,{level:t,treeKey:e}),f(pe,{forceUpdate:l,role:"group",level:t,nodes:n})]}))})};var St=p.memo(gt),mt=Object.defineProperty,vt=Object.defineProperties,bt=Object.getOwnPropertyDescriptors,I=Object.getOwnPropertySymbols,ne=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable,ae=(t,e,r)=>e in t?mt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nt=(t,e)=>{for(var r in e||(e={}))ne.call(e,r)&&ae(t,r,e[r]);if(I)for(var r of I(e))de.call(e,r)&&ae(t,r,e[r]);return t},Ft=(t,e)=>vt(t,bt(e)),Pt=(t,e)=>{var r={};for(var o in t)ne.call(t,o)&&e.indexOf(o)<0&&(r[o]=t[o]);if(t!=null&&I)for(var o of I(t))e.indexOf(o)<0&&de.call(t,o)&&(r[o]=t[o]);return r};const ce=p.forwardRef((t,e)=>{var r=t,{level:o,nodes:l,forceUpdate:s}=r,d=Pt(r,["level","nodes","forceUpdate"]);const{handler:n}=w();return f(m,Ft(Nt({ref:e,as:"ul"},d),{children:l?.map(i=>{const a=n.propsStore.getFieldProps(i.id);return a?a.isFiltered?null:f(St,{level:o+1,treeKey:i.id},i.id):null})}))});ce.displayName="TreeItemChildren";var pe=p.memo(ce);function ue({name:t,treeProps:e}){const r=Ee(e),o=p.useMemo(()=>new V(t,r),[]);D(()=>{var i;(i=e?.initialNodes)==null||i.forEach(a=>o.append(a))});const l=b("root",{comparator:N,propsStore:o.propsStore,selector:i=>{var a;return{children:(a=i.children)!=null?a:[],forceUpdate:i.forceUpdate}}}),s=p.useMemo(()=>`keyHandler${we()}`,[]),d=p.useRef(null),n=p.useCallback((i,a=3)=>{var c,u;if(d.current){const h=d.current.querySelector(`[data-key="${i}"]`);if((c=d.current)==null||c.focus(),h){const g=((u=e.focusGetter)!=null?u:S=>S.querySelector(":scope > .tree__nodeItemLabel"))(h),F=o.propsStore.getFieldProps(i);(!e.focusGetter||!F.labelRenderer)&&g.classList.add("focused"),g.scrollIntoView({inline:"nearest",block:"nearest"})}else a>0&&setTimeout(()=>n(i,a-1),30)}},[o.propsStore,e.focusGetter]);return p.useEffect(()=>{const i=o.on("mustFocus",c=>n(c)),a=o.on("onArrowUpOnFirstElement",()=>{var c;return(c=e.onArrowUpOnFirstElement)==null?void 0:c.call(e)});return()=>{i(),a()}},[n,o,e]),{data:l,handler:o,keyHandler:{id:s,onKeyDown:p.useCallback(i=>{var a;if(i.key==="Enter"){const c=o.state.focusedNode;if(c){const u=o.propsStore.getFieldProps(c);(a=e.onNodeClick)==null||a.call(e,i,u)}}else o.handleKey(i)},[o,e]),onMouseDown:p.useCallback(i=>{var a;o.state.focusedNode!==null&&i.shiftKey&&(a=o.configuration.current)!=null&&a.isMultiple&&i.preventDefault()},[o.configuration,o.state.focusedNode]),onClick:p.useCallback(i=>{var a,c;if(_(i.target,h=>h.classList.contains("tree__expandIcon")))return;const u=_(i.target,h=>!!h.getAttribute("data-key"));if(u){const h=o.state.focusedNode,g=u.getAttribute("data-key"),F=o.propsStore.getFieldProps(g);(a=e.onNodeClick)==null||a.call(e,i,F),h!==null&&i.shiftKey&&(c=o.configuration.current)!=null&&c.isMultiple?C(o,h,g,!0):(o.setFocusedNode(g),o.setSelectedNodesByClickEvent(i)),g&&n(g)}},[n,o,e]),ref:d}}}var yt=Object.defineProperty,Et=Object.defineProperties,Ot=Object.getOwnPropertyDescriptors,he=Object.getOwnPropertySymbols,wt=Object.prototype.hasOwnProperty,It=Object.prototype.propertyIsEnumerable,fe=(t,e,r)=>e in t?yt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$=(t,e)=>{for(var r in e||(e={}))wt.call(e,r)&&fe(t,r,e[r]);if(he)for(var r of he(e))It.call(e,r)&&fe(t,r,e[r]);return t},_t=(t,e)=>Et(t,Ot(e));const xt=t=>{var e,r,o;const{data:l,handler:s,keyHandler:d}=ue({name:t.name,treeProps:$({},t)}),[n,i]=p.useState(!1),[a,c]=p.useState(""),u=Y(s,{selector:S=>S.isLoading});p.useEffect(()=>{i(u)},[u]);const h=Se(()=>{t.filterString!==void 0&&(i(!0),p.startTransition(()=>{c(t.filterString)}),t.filterString!==void 0&&t.filterString!==""?(R(s),B(s,t.filterString),s.forceEmitUpdate()):(R(s),s.forceEmitUpdate()),setTimeout(()=>i(!1),0))},{wait:200});p.useEffect(()=>{h.run(),t.filterString||h.flush()},[t.filterString]),b(s.stateKey,{propsStore:s.propsStore,selector:S=>S,comparator:(S,E)=>{var j;return t.onSelect&&!N(S?.selectedNodes,E?.selectedNodes)&&t.onSelect(((j=E?.selectedNodes)!=null?j:[]).map(ge=>s.propsStore.getFieldProps(ge))),!0}});const{focusedNode:g}=b(s.stateKey,{propsStore:s.propsStore,selector:S=>({focusedNode:S.focusedNode})});D(()=>{t.getHandler&&t.getHandler(s)}),me(()=>s.destructor());const F=p.useMemo(()=>({handler:s,name:t.name,forceUpdate:l.forceUpdate,focusGetter:t.focusGetter,treeProps:t}),[s,t,l.forceUpdate]);return f(Je,{value:F,children:O(m,_t($({className:`tree ${(e=t.className)!=null?e:""}`},A((r=t.variant)!=null?r:"layout.common.trees.primary")),{children:[f(Ye,{isLoading:(o=t.isLoading)!=null?o:n,onDelete:t.onDeleteFilterString,searchString:t.hideSearchLabel?"":a}),f(pe,$({"aria-activedescendant":g!==null?X(t.name,g):void 0,"aria-label":t.label,as:"ul",forceUpdate:l.forceUpdate,level:-1,nodes:p.useMemo(()=>l.children.map(S=>s.propsStore.getFieldProps(S)),[l.children,s.propsStore]),role:"tree",tabIndex:0},d))]}))})};var Lt=Ne(xt);export{Lt as Tree,V as TreeDataController,w as useTreeContext,ue as useTreeData,q as useTreeDataController,Y as useTreeSelector,ke as useTreeSelectorByName};
1397
2
  //# sourceMappingURL=index.js.map