SelectTreeElement.ts 5.94 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
/*
* 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!
*/

14
import type {SelectTree} from './SelectTree';
15
import type {SelectTreeToolbar} from './SelectTreeToolbar';
16
import './SelectTree';
17
18
import './SelectTreeToolbar';
import 'TYPO3/CMS/Backend/Element/IconElement';
19
import {TreeNode} from 'TYPO3/CMS/Backend/Tree/TreeNode';
20

21
export class SelectTreeElement {
22
  private readonly recordField: HTMLInputElement = null;
23
  private readonly tree: SelectTree = null;
24
25

  constructor(treeWrapperId: string, treeRecordFieldId: string, callback: Function) {
26
    this.recordField = <HTMLInputElement>document.getElementById(treeRecordFieldId);
27
28
29
    const treeWrapper = <HTMLElement>document.getElementById(treeWrapperId);
    this.tree = document.createElement('typo3-backend-form-selecttree') as SelectTree;
    this.tree.classList.add('svg-tree-wrapper');
30
31
32
    this.tree.addEventListener('typo3:svg-tree:nodes-prepared', this.loadDataAfter);
    this.tree.addEventListener('typo3:svg-tree:node-selected', this.selectNode);
    this.tree.addEventListener('typo3:svg-tree:node-selected', () => { callback(); } );
33
34

    const settings = {
35
      id: treeWrapperId,
36
      dataUrl: this.generateRequestUrl(),
37
38
39
40
41
      readOnlyMode: parseInt(this.recordField.dataset.readOnly, 10) === 1,
      input: this.recordField,
      exclusiveNodesIdentifiers: this.recordField.dataset.treeExclusiveKeys,
      validation: JSON.parse(this.recordField.dataset.formengineValidationRules)[0],
      expandUpToLevel: this.recordField.dataset.treeExpandUpToLevel,
42
      unselectableElements: [] as Array<any>
43
    };
44
    this.tree.addEventListener('svg-tree:initialized', () => {
45
46
47
48
49
      if (this.recordField.dataset.treeShowToolbar) {
        const toolbarElement = document.createElement('typo3-backend-form-selecttree-toolbar') as SelectTreeToolbar;
        toolbarElement.tree = this.tree;
        this.tree.prepend(toolbarElement);
      }
50
    });
51
52
    this.tree.setup = settings;
    treeWrapper.append(this.tree);
53
54
    this.listenForVisibleTree();
  }
55

56
57
58
59
60
  /**
   * If the Select item is in an invisible tab, it needs to be rendered once the tab
   * becomes visible.
   */
  private listenForVisibleTree(): void {
61
    if (!this.tree.offsetParent) {
62
      // Search for the parents that are tab containers
63
      let idOfTabContainer = this.tree.closest('.tab-pane').getAttribute('id');
64
65
      if (idOfTabContainer) {
        let btn = document.querySelector('[aria-controls="' + idOfTabContainer + '"]');
66
        btn.addEventListener('shown.bs.tab', () => { this.tree.dispatchEvent(new Event('svg-tree:visible')); });
67
      }
68
69
70
71
72
73
74
75
76
    }
  }

  private generateRequestUrl(): string {
    const params = {
      tableName: this.recordField.dataset.tablename,
      fieldName: this.recordField.dataset.fieldname,
      uid: this.recordField.dataset.uid,
      recordTypeValue: this.recordField.dataset.recordtypevalue,
77
      dataStructureIdentifier: this.recordField.dataset.datastructureidentifier,
78
79
80
81
82
83
84
85
      flexFormSheetName: this.recordField.dataset.flexformsheetname,
      flexFormFieldName: this.recordField.dataset.flexformfieldname,
      flexFormContainerName: this.recordField.dataset.flexformcontainername,
      flexFormContainerIdentifier: this.recordField.dataset.flexformcontaineridentifier,
      flexFormContainerFieldName: this.recordField.dataset.flexformcontainerfieldname,
      flexFormSectionContainerIsNew: this.recordField.dataset.flexformsectioncontainerisnew,
      command: this.recordField.dataset.command,
    };
86
    return TYPO3.settings.ajaxUrls.record_tree_data + '&' + new URLSearchParams(params);
87
  }
88
89
90
91
92
93
94

  private selectNode = (evt: CustomEvent) => {
    const node = evt.detail.node as TreeNode;
    this.updateAncestorsIndeterminateState(node);
    // check all nodes again, to ensure correct display of indeterminate state
    this.calculateIndeterminate(this.tree.nodes);
    this.saveCheckboxes();
95
    this.tree.setup.input.dispatchEvent(new Event('change', {bubbles: true, cancelable: true}));
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
  }

  /**
   * Resets the node.indeterminate for the whole tree.
   * It's done once after loading data.
   * Later indeterminate state is updated just for the subset of nodes
   */
  private loadDataAfter = () => {
    this.tree.nodes = this.tree.nodes.map((node: TreeNode) => {
      node.indeterminate = false;
      return node;
    });
    this.calculateIndeterminate(this.tree.nodes);
  }

  /**
   * Sets a comma-separated list of selected nodes identifiers to configured input
   */
  private saveCheckboxes = (): void => {
    if (typeof this.recordField === 'undefined') {
      return;
    }
    this.recordField.value = this.tree.getSelectedNodes().map((node: TreeNode): string => node.identifier).join(',');
  }

  /**
   * Updates the indeterminate state for ancestors of the current node
   */
  private updateAncestorsIndeterminateState(node: TreeNode): void {
    // foreach ancestor except node itself
    let indeterminate = false;
    node.parents.forEach((index: number) => {
      const node = this.tree.nodes[index];
      node.indeterminate = (node.checked || node.indeterminate || indeterminate);
      // check state for the next level
      indeterminate = (node.checked || node.indeterminate || node.checked || node.indeterminate);
    });
  }

  /**
   * Sets indeterminate state for a subtree.
   * It relays on the tree to have indeterminate state reset beforehand.
   */
  private calculateIndeterminate(nodes: TreeNode[]): void {
    nodes.forEach((node: TreeNode) => {
      if ((node.checked || node.indeterminate) && node.parents && node.parents.length > 0) {
        node.parents.forEach((parentNodeIndex: number) => {
          nodes[parentNodeIndex].indeterminate = true;
        });
      }
    });
  }
148
}