PageTree.ts 9.88 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
 * 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 * as d3selection from 'd3-selection';
import AjaxRequest from 'TYPO3/CMS/Core/Ajax/AjaxRequest';
16
import {SvgTree, TreeNodeSelection} from '../SvgTree';
17
import {TreeNode} from '../Tree/TreeNode';
18
import {PageTreeDragDrop, PageTreeNodeDragHandler} from './PageTreeDragDrop';
19
import {AjaxResponse} from 'TYPO3/CMS/Core/Ajax/AjaxResponse';
Benni Mack's avatar
Benni Mack committed
20
import {KeyTypesEnum as KeyTypes} from '../Enum/KeyTypes';
21
import {customElement} from 'lit-element';
22

23
24
25
26
/**
 * A Tree based on SVG for pages, which has a AJAX-based loading of the tree
 * and also handles search + filter via AJAX.
 */
27
@customElement('typo3-backend-page-tree')
28
export class PageTree extends SvgTree
29
{
30
  public nodeIsEdit: boolean;
31
  public dragDrop: PageTreeDragDrop;
Benni Mack's avatar
Benni Mack committed
32
33
  protected networkErrorTitle: string = TYPO3.lang.pagetree_networkErrorTitle;
  protected networkErrorMessage: string = TYPO3.lang.pagetree_networkErrorDesc;
34

35
36
37
38
39
  public constructor() {
    super();
    this.settings.defaultProperties = {
      hasChildren: false,
      nameSourceField: 'title',
Benni Mack's avatar
Benni Mack committed
40
      itemType: 'pages',
41
42
43
44
45
46
47
48
49
50
51
52
53
54
      prefix: '',
      suffix: '',
      locked: false,
      loaded: false,
      overlayIcon: '',
      selectable: true,
      expanded: false,
      checked: false,
      backgroundColor: '',
      stopPageTree: false,
      class: '',
      readableRootline: '',
      isMountPoint: false,
    };
55
  }
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

  public sendChangeCommand(data: any): void {
    let params = '';
    let targetUid = 0;

    if (data.target) {
      targetUid = data.target.identifier;
      if (data.position === 'after') {
        targetUid = -targetUid;
      }
    }

    if (data.command === 'new') {
      params = '&data[pages][NEW_1][pid]=' + targetUid +
        '&data[pages][NEW_1][title]=' + encodeURIComponent(data.name) +
        '&data[pages][NEW_1][doktype]=' + data.type;

    } else if (data.command === 'edit') {
      params = '&data[pages][' + data.uid + '][' + data.nameSourceField + ']=' + encodeURIComponent(data.title);
    } else {
      if (data.command === 'delete') {
        if (data.uid === window.fsMod.recentIds.web) {
78
          this.selectNode(this.nodes[0]);
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
        }
        params = '&cmd[pages][' + data.uid + '][delete]=1';
      } else {
        params = 'cmd[pages][' + data.uid + '][' + data.command + ']=' + targetUid;
      }
    }

    this.nodesAddPlaceholder();

    (new AjaxRequest(top.TYPO3.settings.ajaxUrls.record_process))
      .post(params, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
      })
      .then((response) => {
        return response.resolve();
      })
      .then((response) => {
        if (response && response.hasErrors) {
Benni Mack's avatar
Benni Mack committed
97
          this.errorNotification(response.messages, false);
98
          this.nodesContainer.selectAll('.node').remove();
99
          this.updateVisibleNodes();
100
101
102
103
104
105
106
107
108
109
110
111
112
113
          this.nodesRemovePlaceholder();
        } else {
          this.refreshOrFilterTree();
        }
      })
      .catch((error) => {
        this.errorNotification(error);
      });
  }

  public showChildren(node: TreeNode) {
    this.loadChildrenOfNode(node);
    super.showChildren(node);
  }
114

115
116
  public updateNodeBgClass(nodeBg: TreeNodeSelection) {
    return super.updateNodeBgClass.call(this, nodeBg).call(this.initializeDragForNode());
117
  }
118
119

  public nodesUpdate(nodes: TreeNodeSelection) {
Benni Mack's avatar
Benni Mack committed
120
    nodes = super.nodesUpdate.call(this, nodes).call(this.initializeDragForNode());
121
122
123
124
125
126
127
    nodes
      .append('text')
      .text('+')
      .attr('class', 'node-stop')
      .attr('dx', 30)
      .attr('dy', 5)
      .attr('visibility', (node: TreeNode) => node.stopPageTree && node.depth !== 0 ? 'visible' : 'hidden')
128
129
130
      .on('click', (evt: MouseEvent, node: TreeNode) => {
        document.dispatchEvent(new CustomEvent('typo3:pagetree:mountPoint', {detail: {pageId: parseInt(node.identifier, 10)}}));
      });
131
132

    return nodes;
133
  }
134
135


136
137
138
139
140
141
142
143
  /**
   * Make the DOM element of the node given as parameter focusable and focus it
   */
  public switchFocusNode(node: TreeNode) {
    // Focus node only if it's not currently in edit mode
    if (!this.nodeIsEdit) {
      this.switchFocus(this.getNodeElement(node));
    }
144
145
146
147
148
149
150
151
152
  }

  /**
   * Initializes a drag&drop when called on the page tree. Should be moved somewhere else at some point
   */
  public initializeDragForNode() {
    return this.dragDrop.connectDragHandler(new PageTreeNodeDragHandler(this, this.dragDrop))
  }

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
  public removeEditedText() {
    const inputWrapper = d3selection.selectAll('.node-edit');
    if (inputWrapper.size()) {
      try {
        inputWrapper.remove();
        this.nodeIsEdit = false;
      } catch (e) {
        // ...
      }
    }
  }

  /**
   * Loads child nodes via Ajax (used when expanding a collapsed node)
   *
   * @param parentNode
   * @return {boolean}
   */
  protected loadChildrenOfNode(parentNode: TreeNode) {
    if (parentNode.loaded) {
      return;
    }

    this.nodesAddPlaceholder();
    (new AjaxRequest(this.settings.dataUrl + '&pid=' + parentNode.identifier + '&mount=' + parentNode.mountPoint + '&pidDepth=' + parentNode.depth))
      .get({cache: 'no-cache'})
      .then((response: AjaxResponse) => response.resolve())
      .then((json: any) => {
        let nodes = Array.isArray(json) ? json : [];
        // first element is a parent
        nodes.shift();
        const index = this.nodes.indexOf(parentNode) + 1;
        // adding fetched node after parent
        nodes.forEach((node: TreeNode, offset: number) => {
          this.nodes.splice(index + offset, 0, node);
        });

        parentNode.loaded = true;
        this.setParametersNode();
        this.prepareDataForVisibleNodes();
193
        this.updateVisibleNodes();
194
195
196
197
198
199
200
201
202
203
204
        this.nodesRemovePlaceholder();

        this.switchFocusNode(parentNode);
      })
      .catch((error: any) => {
        this.errorNotification(error, false)
        this.nodesRemovePlaceholder();
        throw error;
      });
  }

205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
  /**
   * Event handler for double click on a node's label
   * Changed text position if there is 'stop page tree' option
   */
  protected appendTextElement(nodes: TreeNodeSelection): TreeNodeSelection {
    let clicks = 0;
    return super.appendTextElement(nodes)
      .attr('dx', (node) => {
        let position = this.textPosition;
        if (node.stopPageTree && node.depth !== 0) {
          position += 15;
        }
        if (node.locked) {
          position += 15;
        }
        return position;
      })
      .on('click', (event, node: TreeNode) => {
        if (node.identifier === '0') {
224
          this.selectNode(node);
225
226
227
228
229
          return;
        }
        if (++clicks === 1) {
          setTimeout(() => {
            if (clicks === 1) {
230
              this.selectNode(node);
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
            } else {
              this.editNodeLabel(node);
            }
            clicks = 0;
          }, 300);
        }
      });
  };

  private sendEditNodeLabelCommand(node: TreeNode) {
    const params = '&data[pages][' + node.identifier + '][' + node.nameSourceField + ']=' + encodeURIComponent(node.newName);

    // remove old node from svg tree
    this.nodesAddPlaceholder(node);

    (new AjaxRequest(top.TYPO3.settings.ajaxUrls.record_process))
      .post(params, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
      })
      .then((response) => {
        return response.resolve();
      })
      .then((response) => {
        if (response && response.hasErrors) {
Benni Mack's avatar
Benni Mack committed
255
          this.errorNotification(response.messages, false);
256
257
258
        } else {
          node.name = node.newName;
        }
Benni Mack's avatar
Benni Mack committed
259
        this.refreshOrFilterTree();
260
261
      })
      .catch((error) => {
Benni Mack's avatar
Benni Mack committed
262
        this.errorNotification(error, true);
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
      });
  }

  private editNodeLabel(node: TreeNode) {
    if (!node.allowEdit) {
      return;
    }
    this.removeEditedText();
    this.nodeIsEdit = true;

    d3selection.select(this.svg.node().parentNode as HTMLElement)
      .append('input')
      .attr('class', 'node-edit')
      .style('top', () => {
        const top = node.y + this.settings.marginTop;
        return top + 'px';
      })
      .style('left', (node.x + this.textPosition + 5) + 'px')
      .style('width', this.settings.width - (node.x + this.textPosition + 20) + 'px')
      .style('height', this.settings.nodeHeight + 'px')
      .attr('type', 'text')
      .attr('value', node.name)
Benni Mack's avatar
Benni Mack committed
285
      .on('keydown', (event: KeyboardEvent) => {
286
287
        // @todo Migrate to `evt.code`, see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code
        const code = event.keyCode;
Benni Mack's avatar
Benni Mack committed
288
289
290
291
292
293

        if (code === KeyTypes.ENTER || code === KeyTypes.TAB) {
          const target = event.target as HTMLInputElement;
          const newName = target.value.trim();
          this.nodeIsEdit = false;
          this.removeEditedText();
294
295
296
          if (newName.length && (newName !== node.name)) {
            node.nameSourceField = node.nameSourceField || 'title';
            node.newName = newName;
Benni Mack's avatar
Benni Mack committed
297
            this.sendEditNodeLabelCommand(node);
298
          }
Benni Mack's avatar
Benni Mack committed
299
300
301
        } else if (code === KeyTypes.ESCAPE) {
          this.nodeIsEdit = false;
          this.removeEditedText();
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
        }
      })
      .on('blur', (evt: FocusEvent) => {
        if (!this.nodeIsEdit) {
          return;
        }
        const target = evt.target as HTMLInputElement;
        const newName = target.value.trim();
        if (newName.length && (newName !== node.name)) {
          node.nameSourceField = node.nameSourceField || 'title';
          node.newName = newName;
          this.sendEditNodeLabelCommand(node);
        }
        this.removeEditedText();
      })
      .node()
      .select();
  }
}