SelectTreeElement.ts 9.52 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 {Tooltip} from 'bootstrap';
Benjamin Franzke's avatar
Benjamin Franzke committed
16
17
import {html, LitElement, TemplateResult} from 'lit';
import {customElement} from 'lit/decorators';
18
19
import {lll} from 'TYPO3/CMS/Core/lit-helper';
import 'TYPO3/CMS/Backend/Element/IconElement';
20
import './SelectTree';
21
22
import FormEngineValidation = require('TYPO3/CMS/Backend/FormEngineValidation');
import {TreeNode} from 'TYPO3/CMS/Backend/Tree/TreeNode';
23
24

const toolbarComponentName: string = 'typo3-backend-form-selecttree-toolbar';
25

26
export class SelectTreeElement {
27
  private readonly recordField: HTMLInputElement = null;
28
  private readonly tree: SelectTree = null;
29
30

  constructor(treeWrapperId: string, treeRecordFieldId: string, callback: Function) {
31
    this.recordField = <HTMLInputElement>document.getElementById(treeRecordFieldId);
32
33
34
    const treeWrapper = <HTMLElement>document.getElementById(treeWrapperId);
    this.tree = document.createElement('typo3-backend-form-selecttree') as SelectTree;
    this.tree.classList.add('svg-tree-wrapper');
35
36
37
    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(); } );
38
39

    const settings = {
40
      id: treeWrapperId,
41
      dataUrl: this.generateRequestUrl(),
42
43
44
45
46
      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,
47
      unselectableElements: [] as Array<any>
48
    };
49
    this.tree.addEventListener('svg-tree:initialized', () => {
50
51
      const toolbarElement = document.createElement(toolbarComponentName) as TreeToolbar;
      toolbarElement.tree = this.tree;
52
      this.tree.prepend(toolbarElement);
53
    });
54
55
    this.tree.setup = settings;
    treeWrapper.append(this.tree);
56
57
    this.listenForVisibleTree();
  }
58

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

  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,
80
      dataStructureIdentifier: this.recordField.dataset.datastructureidentifier,
81
82
83
84
85
86
87
88
      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,
    };
89
    return TYPO3.settings.ajaxUrls.record_tree_data + '&' + new URLSearchParams(params);
90
  }
91
92
93
94
95
96
97

  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();
98
    this.tree.setup.input.dispatchEvent(new Event('change', {bubbles: true, cancelable: true}));
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
  }

  /**
   * 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);

    // Initialise "value" attribute of input field after load and revalidate form engine fields
    this.saveCheckboxes();
    // @todo Unsure if this has ever worked before from `TYPO3.FormEngine.Validation`
    FormEngineValidation.validateField(this.recordField);
  }

  /**
   * 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;
        });
      }
    });
  }
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

@customElement(toolbarComponentName)
class TreeToolbar extends LitElement {
  public tree: SelectTree;
  private settings = {
    collapseAllBtn: 'collapse-all-btn',
    expandAllBtn: 'expand-all-btn',
    searchInput: 'search-input',
    toggleHideUnchecked: 'hide-unchecked-btn'
  };

  /**
   * State of the hide unchecked toggle button
   *
   * @type {boolean}
   */
  private hideUncheckedState: boolean = false;

  // disable shadow dom for now
  protected createRenderRoot(): HTMLElement | ShadowRoot {
    return this;
  }

  protected firstUpdated(): void {
    this.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((tooltipTriggerEl: HTMLElement) => new Tooltip(tooltipTriggerEl));
  }

  protected render(): TemplateResult {
    return html`
      <div class="tree-toolbar btn-toolbar">
        <div class="input-group">
          <span class="input-group-addon input-group-icon filter">
            <typo3-backend-icon identifier="actions-filter" size="small"></typo3-backend-icon>
          </span>
191
          <input type="text" class="form-control ${this.settings.searchInput}" placeholder="${lll('tcatree.findItem')}" @input="${(evt: InputEvent) => this.filter(evt)}">
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
        </div>
        <div class="btn-group">
          <button type="button" data-bs-toggle="tooltip" class="btn btn-default ${this.settings.expandAllBtn}" title="${lll('tcatree.expandAll')}" @click="${() => this.expandAll()}">
            <typo3-backend-icon identifier="apps-pagetree-category-expand-all" size="small"></typo3-backend-icon>
          </button>
          <button type="button" data-bs-toggle="tooltip" class="btn btn-default ${this.settings.collapseAllBtn}" title="${lll('tcatree.collapseAll')}" @click="${() => this.collapseAll()}">
            <typo3-backend-icon identifier="apps-pagetree-category-collapse-all" size="small"></typo3-backend-icon>
          </button>
          <button type="button" data-bs-toggle="tooltip" class="btn btn-default ${this.settings.toggleHideUnchecked}" title="${lll('tcatree.toggleHideUnchecked')}" @click="${() => this.toggleHideUnchecked()}">
            <typo3-backend-icon identifier="apps-pagetree-category-toggle-hide-checked" size="small"></typo3-backend-icon>
          </button>
        </div>
      </div>
    `;
  }
207

208
209
210
211
212
  /**
   * Collapse children of root node
   */
  private collapseAll() {
    this.tree.collapseAll();
213
  }
214
215
216
217
218
219

  /**
   * Expand all nodes
   */
  private expandAll() {
    this.tree.expandAll();
220
  }
221

222
  private filter(event: InputEvent): void {
223
    const inputEl = <HTMLInputElement>event.target;
224
    this.tree.filter(inputEl.value.trim());
225
226
227
228
229
230
231
232
233
234
  }

  /**
   * Show only checked items
   */
  private toggleHideUnchecked(): void {
    this.hideUncheckedState = !this.hideUncheckedState;
    if (this.hideUncheckedState) {
      this.tree.nodes.forEach((node: any) => {
        if (node.checked) {
235
          this.tree.showParents(node);
236
237
238
239
240
241
242
243
244
245
246
          node.expanded = true;
          node.hidden = false;
        } else {
          node.hidden = true;
          node.expanded = false;
        }
      });
    } else {
      this.tree.nodes.forEach((node: any) => node.hidden = false);
    }
    this.tree.prepareDataForVisibleNodes();
247
    this.tree.updateVisibleNodes();
248
249
  }
}