/
svg-tree.ts
1534 lines (1377 loc) · 50.9 KB
/
svg-tree.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
import { html, LitElement, TemplateResult } from 'lit';
import { customElement, property, state } from 'lit/decorators';
import { TreeNode } from './tree/tree-node';
import * as d3selection from 'd3-selection';
import AjaxRequest from '@typo3/core/ajax/ajax-request';
import Notification from './notification';
import { KeyTypesEnum as KeyTypes } from './enum/key-types';
import Icons from './icons';
import { AjaxResponse } from '@typo3/core/ajax/ajax-response';
import { MarkupIdentifiers } from './enum/icon-types';
import { lll } from '@typo3/core/lit-helper';
import DebounceEvent from '@typo3/core/event/debounce-event';
import '@typo3/backend/element/icon-element';
export type TreeWrapperSelection<TBase extends d3selection.BaseType> = d3selection.Selection<TBase, any, any, any>;
export type TreeNodeSelection = d3selection.Selection<d3selection.BaseType, TreeNode, any, any>;
interface SvgTreeData {
nodes: TreeNode[];
links: SvgTreeDataLink[];
}
interface SvgTreeDataLink {
source: TreeNode;
target: TreeNode;
}
interface SvgTreeDataIcon {
identifier: string;
icon: string|null|SVGElement;
}
export interface SvgTreeSettings {
[keys: string]: any;
defaultProperties: {[keys: string]: any};
}
export interface SvgTreeWrapper extends HTMLElement {
svgtree?: SvgTree
}
export class SvgTree extends LitElement {
@property({ type: Object }) setup?: {[keys: string]: any} = null;
@state() settings: SvgTreeSettings = {
showIcons: false,
marginTop: 15,
nodeHeight: 26,
icon: {
size: 16,
containerSize: 20,
},
indentWidth: 20,
width: 300,
duration: 400,
dataUrl: '',
filterUrl: '',
defaultProperties: {},
expandUpToLevel: null as any,
actions: []
};
/**
* Check if cursor is over the SVG element
*/
public isOverSvg: boolean = false;
/**
* Root <svg> element
*/
public svg: TreeWrapperSelection<SVGSVGElement> = null;
/**
* SVG <g> container wrapping all .nodes, .links, .nodes-bg elements
*/
public container: TreeWrapperSelection<SVGGElement> = null;
/**
* SVG <g> container wrapping all .node elements
*/
public nodesContainer: TreeWrapperSelection<SVGGElement> = null;
/**
* SVG <g> container wrapping all .nodes-bg elements
*/
public nodesBgContainer: TreeWrapperSelection<SVGGElement> = null;
/**
* Is set when the input device is hovered over a node
*/
public hoveredNode: TreeNode|null = null;
public nodes: TreeNode[] = [];
public textPosition: number = 10;
protected icons: {[keys: string]: SvgTreeDataIcon} = {};
protected nodesActionsContainer: TreeWrapperSelection<SVGGElement> = null;
/**
* SVG <defs> container wrapping all icon definitions
*/
protected iconsContainer: TreeWrapperSelection<SVGDefsElement> = null;
/**
* SVG <g> container wrapping all links (lines between parent and child)
*
* @type {Selection}
*/
protected linksContainer: TreeWrapperSelection<SVGGElement> = null;
protected data: SvgTreeData = new class implements SvgTreeData {
links: SvgTreeDataLink[] = [];
nodes: TreeNode[] = [];
};
protected viewportHeight: number = 0;
protected scrollBottom: number = 0;
protected searchTerm: string|null = null;
protected unfilteredNodes: string = '';
protected muteErrorNotifications: boolean = false;
protected networkErrorTitle: string = top.TYPO3.lang.tree_networkError;
protected networkErrorMessage: string = top.TYPO3.lang.tree_networkErrorDescription;
/**
* Initializes the tree component - created basic markup, loads and renders data
* @todo declare private
*/
public doSetup(settings: any): void {
Object.assign(this.settings, settings);
if (this.settings.showIcons) {
this.textPosition += this.settings.icon.containerSize;
}
this.svg = d3selection.select(this).select('svg');
this.container = this.svg.select('.nodes-wrapper') as TreeWrapperSelection<SVGGElement>;
this.nodesBgContainer = this.container.select('.nodes-bg') as TreeWrapperSelection<SVGGElement>;
this.nodesActionsContainer = this.container.select('.nodes-actions') as TreeWrapperSelection<SVGGElement>;
this.linksContainer = this.container.select('.links') as TreeWrapperSelection<SVGGElement>;
this.nodesContainer = this.container.select('.nodes') as TreeWrapperSelection<SVGGElement>;
this.iconsContainer = this.svg.select('defs') as TreeWrapperSelection<SVGGElement>;
this.registerUnloadHandler();
this.updateScrollPosition();
this.loadCommonIcons();
this.loadData();
this.dispatchEvent(new Event('svg-tree:initialized'));
}
/**
* Preloads common icons to have them available as early
* as possible and avoid unnessesary early node updates.
*/
public loadCommonIcons(): void
{
this.fetchIcon('actions-chevron-right', false); // used as toggle icon
this.fetchIcon('overlay-backenduser', false); // used as locked indicator (a different user is editing)
this.fetchIcon('actions-caret-right', false); // used as enter icon for stopped trees
this.fetchIcon('actions-link', false); // used as link indicator
}
/**
* Make the DOM element given as parameter focusable and focus it
*
* @param {SVGElement} element
*/
public focusElement(element: SVGElement|HTMLElement): void {
if (element === null) {
return;
}
const visibleElements = element.parentNode.querySelectorAll('[tabindex]');
visibleElements.forEach((visibleElement) => {
visibleElement.setAttribute('tabindex','-1');
});
element.setAttribute('tabindex', '0');
element.focus();
}
/**
* Make the DOM element of the node given as parameter focusable and focus it
*/
public focusNode(node: TreeNode): void {
this.disableFocusedNodes();
node.focused = true;
this.focusElement(this.getElementFromNode(node));
}
public getNodeFromElement(element: SVGElement|HTMLElement): TreeNode | null
{
if (element === null || !('stateId' in element.dataset)) {
return null;
}
return this.getNodeByIdentifier(element.dataset.stateId);
}
/**
* Return the DOM element of a tree node
*/
public getElementFromNode(node: TreeNode): HTMLElement|null {
return this.querySelector('#identifier-' + this.getNodeStateIdentifier(node));
}
/**
* Loads tree data (json) from configured url
*/
public loadData() {
this.nodesAddPlaceholder();
(new AjaxRequest(this.settings.dataUrl))
.get({ cache: 'no-cache' })
.then((response: AjaxResponse) => response.resolve())
.then((json) => {
const nodes = Array.isArray(json) ? json : [];
this.replaceData(nodes);
this.nodesRemovePlaceholder();
// @todo: needed?
this.updateScrollPosition();
this.updateVisibleNodes();
})
.catch((error) => {
this.errorNotification(error, false);
this.nodesRemovePlaceholder();
throw error;
});
}
/**
* Delete old tree and create new one
*/
public replaceData(nodes: TreeNode[]) {
this.setParametersNode(nodes);
this.prepareDataForVisibleNodes();
this.nodesContainer.selectAll('.node').remove();
this.nodesBgContainer.selectAll('.node-bg').remove();
this.nodesActionsContainer.selectAll('.node-action').remove();
this.linksContainer.selectAll('.link').remove();
this.updateVisibleNodes();
}
/**
* Set parameters like node parents, parentsStateIdentifier, checked.
* Usually called when data is loaded initially or replaced completely.
*
* @param {Node[]} nodes
*/
public setParametersNode(nodes: TreeNode[] = null): void {
nodes = nodes || this.nodes;
nodes = nodes.map((node, index) => {
if (typeof node.command === 'undefined') {
node = Object.assign({}, this.settings.defaultProperties, node);
}
node.expanded = (this.settings.expandUpToLevel !== null) ? node.depth < this.settings.expandUpToLevel : Boolean(node.expanded);
node.parents = [];
node.parentsStateIdentifier = [];
if (node.depth > 0) {
let currentDepth = node.depth;
for (let i = index; i >= 0; i--) {
const currentNode = nodes[i];
if (currentNode.depth < currentDepth) {
node.parents.push(i);
node.parentsStateIdentifier.push(nodes[i].stateIdentifier);
currentDepth = currentNode.depth;
}
}
}
if (typeof node.checked === 'undefined') {
node.checked = false;
}
if (typeof node.focused === 'undefined') {
node.focused = false;
}
return node;
});
// get nodes with depth 0, if there is only 1 then open it and disable toggle
const nodesOnRootLevel = nodes.filter((node) => node.depth === 0);
if (nodesOnRootLevel.length === 1) {
nodes[0].expanded = true;
}
const evt = new CustomEvent('typo3:svg-tree:nodes-prepared', { detail: { nodes: nodes }, bubbles: false });
this.dispatchEvent(evt);
this.nodes = evt.detail.nodes;
}
public nodesRemovePlaceholder() {
const nodeLoader = this.querySelector('.node-loader') as HTMLElement;
if (nodeLoader) {
nodeLoader.style.display = 'none';
}
const componentWrapper = this.closest('.svg-tree');
const treeLoader = componentWrapper?.querySelector('.svg-tree-loader') as HTMLElement;
if (treeLoader) {
treeLoader.style.display = 'none';
}
}
public nodesAddPlaceholder(node: TreeNode = null) {
if (node) {
const nodeLoader = this.querySelector('.node-loader') as HTMLElement;
if (nodeLoader) {
nodeLoader.style.top = '' + (node.y + this.settings.marginTop);
nodeLoader.style.display = 'block';
}
} else {
const componentWrapper = this.closest('.svg-tree');
const treeLoader = componentWrapper?.querySelector('.svg-tree-loader') as HTMLElement;
if (treeLoader) {
treeLoader.style.display = 'block';
}
}
}
/**
* Updates node's data to hide/collapse children
*
* @param {Node} node
*/
public hideChildren(node: TreeNode): void {
node.expanded = false;
this.setExpandedState(node);
this.dispatchEvent(new CustomEvent('typo3:svg-tree:expand-toggle', { detail: { node: node } }));
}
/**
* Updates node's data to show/expand children
*
* @param {Node} node
*/
public showChildren(node: TreeNode): void {
node.expanded = true;
this.setExpandedState(node);
this.dispatchEvent(new CustomEvent('typo3:svg-tree:expand-toggle', { detail: { node: node } }));
}
/**
* Updates the expanded state of the DOM element that belongs to the node.
* This is required because the node is not recreated on update and thus the change in the expanded state
* of the node data is not represented in DOM on hideChildren and showChildren.
*
* @param {Node} node
*/
public setExpandedState(node: TreeNode): void {
const nodeElement = this.getElementFromNode(node);
if (nodeElement) {
if (node.hasChildren) {
nodeElement.setAttribute('aria-expanded', node.expanded ? 'true' : 'false');
} else {
nodeElement.removeAttribute('aria-expanded');
}
}
}
/**
* Refresh view with new data
*/
public refreshTree(): void {
this.loadData();
}
public refreshOrFilterTree(): void {
if (this.searchTerm !== '') {
this.filter(this.searchTerm);
} else {
this.refreshTree();
}
}
/**
* Filters out invisible nodes (collapsed) from the full dataset (this.rootNode)
* and enriches dataset with additional properties
* Visible dataset is stored in this.data
*/
public prepareDataForVisibleNodes(): void {
const blacklist: {[keys: string]: boolean} = {};
this.nodes.forEach((node: TreeNode, index: number): void => {
if (!node.expanded) {
blacklist[index] = true;
}
});
this.data.nodes = this.nodes.filter((node: TreeNode): boolean => {
return node.hidden !== true && !node.parents.some((index: number) => Boolean(blacklist[index]));
});
this.data.links = [];
let pathAboveMounts = 0;
this.data.nodes.forEach((node: TreeNode, i: number) => {
// delete n.children;
node.x = node.depth * this.settings.indentWidth;
if (node.readableRootline) {
pathAboveMounts += this.settings.nodeHeight;
}
node.y = (i * this.settings.nodeHeight) + pathAboveMounts;
if (node.parents[0] !== undefined) {
this.data.links.push({
source: this.nodes[node.parents[0]],
target: node
});
}
if (this.settings.showIcons) {
this.fetchIcon(node.icon);
this.fetchIcon(node.overlayIcon);
}
});
this.svg.attr('height', ((this.data.nodes.length * this.settings.nodeHeight) + (this.settings.nodeHeight / 2) + pathAboveMounts));
}
/**
* Fetch icon from Icon API and store it in this.icons
*/
public fetchIcon(iconName: string, update: boolean = true): void {
if (!iconName) {
return;
}
if (!(iconName in this.icons)) {
this.icons[iconName] = {
identifier: iconName,
icon: null
} as SvgTreeDataIcon;
Icons.getIcon(iconName, Icons.sizes.small, null, null, MarkupIdentifiers.inline).then((icon: string) => {
const result = icon.match(/<svg[\s\S]*<\/svg>/i);
if (result) {
const iconEl = document.createRange().createContextualFragment(result[0]);
this.icons[iconName].icon = iconEl.firstElementChild as SVGElement;
}
if (update) {
this.updateVisibleNodes();
}
});
}
}
/**
* Renders the subset of the tree nodes fitting the viewport (adding, modifying and removing SVG nodes)
*/
public updateVisibleNodes(): void {
const visibleRows = Math.ceil(this.viewportHeight / this.settings.nodeHeight + 1);
const position = Math.floor(Math.max(this.scrollTop - (this.settings.nodeHeight * 2), 0) / this.settings.nodeHeight);
const visibleNodes = this.data.nodes.slice(position, position + visibleRows);
const focusableElement = this.querySelector('[tabindex="0"]');
const focusedNodeInViewport = visibleNodes.find((node: TreeNode) => node.focused);
const checkedNodeInViewport = visibleNodes.find((node: TreeNode) => node.checked);
let nodes = this.nodesContainer.selectAll('.node')
.data(visibleNodes, (node: TreeNode) => node.stateIdentifier);
const nodesBg = this.nodesBgContainer.selectAll('.node-bg')
.data(visibleNodes, (node: TreeNode) => node.stateIdentifier);
const nodesActions = this.nodesActionsContainer.selectAll('.node-action')
.data(visibleNodes, (node: TreeNode) => node.stateIdentifier);
// delete nodes without corresponding data
nodes.exit().remove();
nodesBg.exit().remove();
nodesActions.exit().remove();
// update nodes actions
this.updateNodeActions(nodesActions);
// update nodes background
const nodeBgClass = this.updateNodeBgClass(nodesBg);
nodeBgClass
.attr('class', (node: TreeNode, i: number) => {
return this.getNodeBgClass(node, i, nodeBgClass);
})
.attr('style', (node: TreeNode) => {
return node.backgroundColor ? 'fill: ' + node.backgroundColor + ';' : '';
});
this.updateLinks();
nodes = this.enterSvgElements(nodes);
// update nodes
nodes
.attr('tabindex', (node: TreeNode, index: number) => {
if (typeof focusedNodeInViewport !== 'undefined') {
if (focusedNodeInViewport === node) {
return '0';
}
} else {
if (typeof checkedNodeInViewport !== 'undefined') {
if (checkedNodeInViewport === node) {
return '0';
}
} else {
if (focusableElement === null) {
if (index === 0) {
return '0';
}
} else {
if (d3selection.select(focusableElement).datum() === node) {
return '0';
}
}
}
}
return '-1';
})
.attr('transform', this.getNodeTransform)
.select('.node-name')
.html((node: TreeNode) => this.getNodeLabel(node));
nodes
.select('.node-toggle')
.attr('class', this.getToggleClass)
.attr('visibility', this.getToggleVisibility);
if (this.settings.showIcons) {
nodes
.select('use.node-icon')
.attr('xlink:href', this.getIconId);
nodes
.select('use.node-icon-overlay')
.attr('xlink:href', this.getIconOverlayId);
nodes
.select('use.node-icon-locked')
.attr('xlink:href', (node: TreeNode) => {
return '#icon-' + (node.locked ? 'overlay-backenduser' : '');
});
}
}
public updateNodeBgClass(nodesBg: TreeNodeSelection): TreeNodeSelection {
let nodeHeight = this.settings.nodeHeight;
// IMPORTANT
//
// The SVG spec does not support stroke alignment, and the stroke is always centered on the edge
// this results in blurry edges with 1px borders. Setting shape rendering to crispEdges has
// different results depending on the used browser.
//
// To resolve this issue need to:
// 1. reduce the height -1px - done in SvgTree::updateNodeBgClass
// 2. offset the element by 0.5px - done in SvgTree::getNodeBackgroundTransform
nodeHeight = nodeHeight - 1;
const node = nodesBg.enter()
.append('rect')
.merge(nodesBg as d3selection.Selection<SVGRectElement, TreeNode, any, any>);
return node
.attr('width', '100%')
.attr('height', nodeHeight)
.attr('data-state-id', this.getNodeStateIdentifier)
.attr('transform', (node: TreeNode) => this.getNodeBackgroundTransform(node, this.settings.indentWidth, this.settings.nodeHeight))
.on('mouseover', (evt: MouseEvent, node: TreeNode) => this.onMouseOverNode(node))
.on('mouseout', (evt: MouseEvent, node: TreeNode) => this.onMouseOutOfNode(node))
.on('click', (evt: MouseEvent, node: TreeNode) => {
this.selectNode(node, true);
this.focusNode(node);
this.updateVisibleNodes();
})
.on('contextmenu', (evt: MouseEvent, node: TreeNode) => {
evt.preventDefault();
this.dispatchEvent(new CustomEvent('typo3:svg-tree:node-context', { detail: { node: node } }));
});
}
/**
* Returns icon's href attribute value
*/
public getIconId(node: TreeNode): string {
return '#icon-' + node.icon;
}
/**
* Returns icon's href attribute value
*/
public getIconOverlayId(node: TreeNode): string {
return '#icon-' + node.overlayIcon;
}
/**
* Node selection logic (triggered by different events)
* This represents a dummy method and is usually overridden
* The second argument can be interpreted by the listened events to e.g. not avoid reloading the content frame and instead
* used for just updating the state within the tree
*/
public selectNode(node: TreeNode, propagate: boolean = true): void {
if (!this.isNodeSelectable(node)) {
return;
}
// Disable already selected nodes
this.disableSelectedNodes();
this.disableFocusedNodes();
node.checked = true;
node.focused = true;
this.dispatchEvent(new CustomEvent('typo3:svg-tree:node-selected', { detail: { node: node, propagate: propagate } }));
this.updateVisibleNodes();
}
public filter(searchTerm?: string|null): void {
if (typeof searchTerm === 'string') {
this.searchTerm = searchTerm;
}
this.nodesAddPlaceholder();
if (this.searchTerm && this.settings.filterUrl) {
(new AjaxRequest(this.settings.filterUrl + '&q=' + this.searchTerm))
.get({ cache: 'no-cache' })
.then((response: AjaxResponse) => response.resolve())
.then((json) => {
const nodes = Array.isArray(json) ? json : [];
if (nodes.length > 0) {
if (this.unfilteredNodes === '') {
this.unfilteredNodes = JSON.stringify(this.nodes);
}
this.replaceData(nodes);
}
this.nodesRemovePlaceholder();
})
.catch((error: any) => {
this.errorNotification(error, false);
this.nodesRemovePlaceholder();
throw error;
});
} else {
// restore original state without filters
this.resetFilter();
}
}
public resetFilter(): void
{
this.searchTerm = '';
if (this.unfilteredNodes.length > 0) {
const currentlySelected = this.getSelectedNodes()[0];
if (typeof currentlySelected === 'undefined') {
this.refreshTree();
return;
}
this.nodes = JSON.parse(this.unfilteredNodes);
this.unfilteredNodes = '';
// re-select the node from the identifier because the nodes have been updated
const currentlySelectedNode = this.getNodeByIdentifier(currentlySelected.stateIdentifier);
if (currentlySelectedNode) {
this.selectNode(currentlySelectedNode, false);
this.focusNode(currentlySelectedNode);
// Remove placeholder, in case this method was called from this.filter()
// and there was currently a node selected.
this.nodesRemovePlaceholder();
} else {
this.refreshTree();
}
} else {
this.refreshTree();
}
this.prepareDataForVisibleNodes();
this.updateVisibleNodes();
}
/**
* Displays a notification message and refresh nodes
*/
public errorNotification(error: any = null, refresh: boolean = false): void {
if (this.muteErrorNotifications) {
return;
}
if (Array.isArray(error)) {
error.forEach((message: any) => { Notification.error(
message.title,
message.message
);});
} else {
let title = this.networkErrorTitle;
if (error && error.target && (error.target.status || error.target.statusText)) {
title += ' - ' + (error.target.status || '') + ' ' + (error.target.statusText || '');
}
Notification.error(title, this.networkErrorMessage);
}
if (refresh) {
this.loadData();
}
}
public connectedCallback(): void {
super.connectedCallback();
this.addEventListener('resize', this.updateViewRequested);
this.addEventListener('scroll', this.updateViewRequested);
this.addEventListener('svg-tree:visible', this.updateViewRequested);
window.addEventListener('resize', this.windowResized);
}
public disconnectedCallback(): void {
this.removeEventListener('resize', this.updateViewRequested);
this.removeEventListener('scroll', this.updateViewRequested);
this.removeEventListener('svg-tree:visible', this.updateViewRequested);
window.removeEventListener('resize', this.windowResized);
super.disconnectedCallback();
}
/**
* Returns an array of selected nodes
*/
public getSelectedNodes(): TreeNode[] {
return this.nodes.filter((node: TreeNode) => node.checked);
}
/**
* Returns an array of focused nodes
*/
public getFocusedNodes(): TreeNode[] {
return this.nodes.filter((node: TreeNode) => node.focused);
}
/**
* Disable currently focused nodes
*/
public disableFocusedNodes(): void {
this.getFocusedNodes().forEach((node: TreeNode) => {
if (node.focused === true) {
node.focused = false;
}
});
}
// disable shadow dom for now
protected createRenderRoot(): HTMLElement | ShadowRoot {
return this;
}
protected render(): TemplateResult {
return html`
<div class="node-loader">
<typo3-backend-icon identifier="spinner-circle-light" size="small"></typo3-backend-icon>
</div>
<svg version="1.1"
direction="ltr"
width="100%"
@mouseover=${() => this.isOverSvg = true}
@mouseout=${() => this.isOverSvg = false}
@keydown=${(evt: KeyboardEvent) => this.handleKeyboardInteraction(evt)}>
<g class="nodes-wrapper" transform="translate(${this.settings.indentWidth / 2},${this.settings.nodeHeight / 2})">
<g class="links"></g>
<g class="nodes-bg"></g>
<g class="nodes" role="tree"></g>
<g class="nodes-actions"></g>
</g>
<defs></defs>
</svg>
`;
}
protected firstUpdated(): void {
this.svg = d3selection.select(this.querySelector('svg'));
this.container = d3selection.select(this.querySelector('.nodes-wrapper'))
.attr('transform', 'translate(' + (this.settings.indentWidth / 2) + ',' + (this.settings.nodeHeight / 2) + ')') as any;
this.nodesBgContainer = d3selection.select(this.querySelector('.nodes-bg')) as any;
this.nodesActionsContainer = d3selection.select(this.querySelector('.nodes-actions')) as any;
this.linksContainer = d3selection.select(this.querySelector('.links')) as any;
this.nodesContainer = d3selection.select(this.querySelector('.nodes')) as any;
this.doSetup(this.setup || {});
this.updateView();
}
protected updateViewRequested(): void {
this.updateView();
}
protected updateView(): void {
this.updateScrollPosition();
this.updateVisibleNodes();
if (this.settings.actions && this.settings.actions.length) {
this.nodesActionsContainer.attr('transform', 'translate(' + (this.querySelector('svg').clientWidth - 16 - ((16 * this.settings.actions.length))) + ',0)');
}
}
protected windowResized = (): void => {
if (this.getClientRects().length > 0) {
this.updateView();
}
};
protected disableSelectedNodes(): void {
// Disable already selected nodes
this.getSelectedNodes().forEach((node: TreeNode) => {
if (node.checked === true) {
node.checked = false;
}
});
}
/**
* Ensure to update the actions column to stick to the very end
*/
protected updateNodeActions(nodesActions: TreeNodeSelection): TreeNodeSelection {
if (this.settings.actions && this.settings.actions.length) {
// Remove all existing actions again
this.nodesActionsContainer.selectAll('.node-action').selectChildren().remove();
return nodesActions.enter()
.append('g')
.merge(nodesActions as d3selection.Selection<SVGGElement, TreeNode, any, any>)
.attr('class', 'node-action')
.on('mouseover', (evt: MouseEvent, node: TreeNode) => this.onMouseOverNode(node))
.on('mouseout', (evt: MouseEvent, node: TreeNode) => this.onMouseOutOfNode(node))
.attr('data-state-id', this.getNodeStateIdentifier)
.attr('transform', (node: TreeNode) => this.getNodeActionTransform(node, this.settings.indentWidth, this.settings.nodeHeight));
}
return nodesActions.enter();
}
/**
* This is a quick helper function to create custom action icons.
*/
protected createIconAreaForAction(actionItem: any, iconIdentifier: string): void
{
const icon = actionItem
.append('svg')
.attr('class', 'node-icon-container')
.attr('height', this.settings.icon.containerSize)
.attr('width', this.settings.icon.containerSize)
.attr('x', '0')
.attr('y', '0');
// improve usability by making the click area a 20px square
icon
.append('rect')
.attr('height', this.settings.icon.containerSize)
.attr('width', this.settings.icon.containerSize)
.attr('y', '0')
.attr('x', '0')
.attr('class', 'node-icon-click');
const nodeInner = icon
.append('svg')
.attr('height', this.settings.icon.size)
.attr('width', this.settings.icon.size)
.attr('y', (this.settings.icon.containerSize - this.settings.icon.size) / 2)
.attr('x', (this.settings.icon.containerSize - this.settings.icon.size) / 2)
.attr('class', 'node-icon-inner');
nodeInner
.append('use')
.attr('class', 'node-icon')
.attr('xlink:href', '#icon-' + iconIdentifier);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected isNodeSelectable(node: TreeNode): boolean {
return true;
}
protected appendTextElement(nodes: TreeNodeSelection): TreeNodeSelection {
return nodes
.append('text')
.attr('dx', this.textPosition)
.attr('dy', 5)
.attr('class', 'node-name')
.on('click', (evt: MouseEvent, node: TreeNode) => {
this.selectNode(node, true);
this.focusNode(node);
this.updateVisibleNodes();
});
}
protected nodesUpdate(nodes: TreeNodeSelection): TreeNodeSelection {
nodes = nodes
.enter()
.append('g')
.attr('class', 'node')
.attr('id', (node: TreeNode) => { return 'identifier-' + node.stateIdentifier; })
.attr('role', 'treeitem')
.attr('aria-owns', (node: TreeNode) => { return (node.hasChildren ? 'group-identifier-' + node.stateIdentifier : null); })
.attr('aria-level', this.getNodeDepth)
.attr('aria-setsize', this.getNodeSetsize)
.attr('aria-posinset', this.getNodePositionInSet)
.attr('aria-expanded', (node: TreeNode) => { return (node.hasChildren ? node.expanded : null); })
.attr('transform', this.getNodeTransform)
.attr('data-state-id', this.getNodeStateIdentifier)
.attr('title', this.getNodeTitle)
.on('mouseover', (evt: MouseEvent, node: TreeNode) => this.onMouseOverNode(node))
.on('mouseout', (evt: MouseEvent, node: TreeNode) => this.onMouseOutOfNode(node))
.on('contextmenu', (evt: MouseEvent, node: TreeNode) => {
evt.preventDefault();
this.dispatchEvent(new CustomEvent('typo3:svg-tree:node-context', { detail: { node: node } }));
});
nodes
.append('text')
.text((node: TreeNode) => { return node.readableRootline; })
.attr('class', 'node-rootline')
.attr('dx', 0)
.attr('dy', (this.settings.nodeHeight / 2 * -1))
.attr('visibility', (node: TreeNode) => node.readableRootline ? 'visible' : 'hidden')
;
return nodes;
}
protected getNodeIdentifier(node: TreeNode): string {
return node.identifier;
}
protected getNodeDepth(node: TreeNode): number {
return node.depth;
}
protected getNodeSetsize(node: TreeNode): number {
return node.siblingsCount;
}
protected getNodePositionInSet(node: TreeNode): number {
return node.siblingsPosition;
}
protected getNodeStateIdentifier(node: TreeNode): string {
return node.stateIdentifier;
}
protected getNodeLabel(node: TreeNode): string {
let label = (node.prefix || '') + node.name + (node.suffix || '');
// make a text node out of it, and strip out any HTML (this is because the return value uses html()
// instead of text() which is needed to avoid XSS in a page title
const labelNode = document.createElement('div');
labelNode.textContent = label;
label = labelNode.innerHTML;
if (this.searchTerm) {
const regexp = new RegExp(this.searchTerm, 'gi');
label = label.replace(regexp, '<tspan class="node-highlight-text">$&</tspan>');
}
return label;
}
/**
* Finds node by its stateIdentifier (e.g. "0_360")
*/
protected getNodeByIdentifier(identifier: string): TreeNode|null {
return this.nodes.find((node: TreeNode) => {
return node.stateIdentifier === identifier;
});
}
/**
* Computes the tree node-bg class
*/
protected getNodeBgClass(node: TreeNode, i: number, nodeBgClass: TreeNodeSelection): string {
let bgClass = 'node-bg';
let prevNode = null;
let nextNode = null;
if (typeof nodeBgClass === 'object') {
prevNode = nodeBgClass.data()[i - 1];
nextNode = nodeBgClass.data()[i + 1];
}
if (node.checked) {
bgClass += ' node-selected';
}
if (node.focused) {
bgClass += ' node-focused';
}
if ((prevNode && (node.depth > prevNode.depth)) || !prevNode) {
node.firstChild = true;
bgClass += ' node-first-child';
}
if ((nextNode && (node.depth > nextNode.depth)) || !nextNode) {
node.lastChild = true;
bgClass += ' node-last-child';
}
if (node.class) {
bgClass += ' ' + node.class;
}
return bgClass;
}
protected getNodeTitle(node: TreeNode): string {
return node.tip ? node.tip : 'uid=' + node.identifier;
}
protected getToggleVisibility(node: TreeNode): string {
return node.hasChildren ? 'visible' : 'hidden';
}
protected getToggleClass(node: TreeNode): string {
return 'node-toggle node-toggle--' + (node.expanded ? 'expanded' : 'collapsed')
// Nessesary for testing framework can be removed after testing framework is adapted at some point
+ ' chevron ' + (node.expanded ? 'expanded' : 'collapsed');
}