-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathLeftAndMain.Tree.js
More file actions
748 lines (679 loc) · 25.5 KB
/
LeftAndMain.Tree.js
File metadata and controls
748 lines (679 loc) · 25.5 KB
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
/**
* File: LeftAndMain.Tree.js
*/
import $ from 'jquery';
const updateRovingTabindex = ($tree, $targetAnchor) => {
if (!$targetAnchor || !$targetAnchor.length) {
return;
}
if (!$tree || !$tree.length) {
return;
}
const $links = $tree.find('a');
const $toggles = $tree.find('li > .jstree-icon--arrow');
$links.attr('tabindex', -1);
$toggles.attr('tabindex', -1);
$targetAnchor.attr('tabindex', 0);
};
const resetTabindexToCurrentPage = ($tree) => {
if (!$tree || !$tree.length) {
return;
}
const $currentPage = $tree.find('a[aria-current="page"]').first();
const $links = $tree.find('a');
const $toggles = $tree.find('li > .jstree-icon--arrow');
$links.attr('tabindex', -1);
$toggles.attr('tabindex', -1);
if ($currentPage.length) {
$currentPage.attr('tabindex', 0);
} else {
const $firstPage = $tree.find('li[data-id]').not('[data-id="0"]').first().find('> a').first();
if ($firstPage.length) {
$firstPage.attr('tabindex', 0);
}
}
};
const updateTreeAriaExpanded = ($treeNode, expanded) => {
if (!$treeNode || !$treeNode.length) {
return;
}
const ariaExpanded = expanded ? 'true' : 'false';
$treeNode
.children('a[role="treeitem"][aria-expanded], strong[role="treeitem"][aria-expanded]')
.attr('aria-expanded', ariaExpanded);
$treeNode
.children('.jstree-icon--arrow[role="button"]')
.attr('aria-expanded', ariaExpanded);
};
// this conditional check is so that we can unit test the functions above in this file without needing to
// load in jquery.entwine
if (typeof $.entwine === 'function') {
$.entwine('ss.tree', function($){
$('.cms-tree').entwine({
Hints: null,
IsUpdatingTree: false,
CanMoveCheckCompleted: false,
IsLoaded: false,
onadd: function(){
this._super();
// Don't reapply (expensive) tree behaviour if already present
if($.isNumeric(this.data('jstree_instance_id'))) return;
var hints = this.attr('data-hints');
if(hints) this.setHints($.parseJSON(hints));
const moveNodeCallback = function(e, data) {
let movedNode = data.rslt.o,
newParentNode = data.rslt.np,
newParentID = $(newParentNode).data('id') || 0,
nodeID = $(movedNode).data('id'),
siblingIDs = $.map($(movedNode).siblings().addBack(), function (el) {
return $(el).data('id');
});
if(self.getIsUpdatingTree()) return;
// run asynchronous logic separately
if (!self.getCanMoveCheckCompleted()) {
self.canMove(data).then((success) => {
if (success) {
self.setCanMoveCheckCompleted(true);
moveNodeCallback(e, data);
} else {
// undo
$.jstree.rollback(data.rlbk);
}
});
return;
}
self.setCanMoveCheckCompleted(false);
$.ajax({
'url': $.path.addSearchParams(
self.data('urlSavetreenode'),
self.data('extraParams')
),
'type': 'POST',
'data': {
ID: nodeID,
ParentID: newParentID,
SiblingIDs: siblingIDs
},
success: function() {
// We only need to update the ParentID if the current page we're on is the page being moved
if ($('.cms-edit-form :input[name=ID]').val() == nodeID) {
$('.cms-edit-form :input[name=ParentID]').val(newParentID);
}
self.updateNodesFromServer([nodeID]);
},
statusCode: {
403: function() {
$.jstree.rollback(data.rlbk);
}
}
});
};
var self = this;
this
.jstree(this.getTreeConfig())
.on('loaded.jstree', function(e, data) {
self.setIsLoaded(true);
// Add ajax settings after init period to avoid unnecessary initial ajax load
// of existing tree in DOM - see load_node_html()
data.inst._set_settings({'html_data': {'ajax': {
'url': self.data('urlTree'),
'data': function(node) {
var params = self.data('searchparams') || [];
// Avoid duplication of parameters
params = $.grep(params, function(n, i) {return (n.name != 'ID' && n.name != 'value');});
params.push({name: 'ID', value: $(node).data("id") ? $(node).data("id") : 0});
params.push({name: 'ajax', value: 1});
return params;
}
}}});
self.updateFromEditForm();
self.css('visibility', 'visible');
// Only show checkboxes with .multiple class
data.inst.hide_checkboxes();
})
.on('before.jstree', function(e, data) {
if(data.func == 'start_drag') {
// Don't allow drag'n'drop if multi-select is enabled'
if(!self.hasClass('draggable') || self.hasClass('multiselect')) {
e.stopImmediatePropagation();
return false;
}
}
if($.inArray(data.func, ['check_node', 'uncheck_node'])) {
// don't allow check and uncheck if parent is disabled
var node = $(data.args[0]).parents('li:first');
var allowedChildren = node.find('li:not(.disabled)');
// if there are child nodes that aren't disabled, allow expanding the tree
if(node.hasClass('disabled') && allowedChildren == 0) {
e.stopImmediatePropagation();
return false;
}
}
})
.on('move_node.jstree', moveNodeCallback)
// Make some jstree events delegatable
.on('select_node.jstree check_node.jstree uncheck_node.jstree', function(e, data) {
// Clear out namespace before triggering so entwine handlers are called
e.namespace = '';
$(document).triggerHandler(e, data);
})
// Update roving tabindex when a node is selected for keyboard accessibility
// Skip if root node is selected (e.g. mouse click on toggle) to preserve existing tabindex
.on('select_node.jstree', function(e, data) {
if (data.rslt && data.rslt.obj && data.rslt.obj.attr('id') === 'record-0') {
return;
}
resetTabindexToCurrentPage(self);
})
.on('open_node.jstree close_node.jstree', function(e, data) {
var node = data && data.rslt ? data.rslt.obj : null;
if ((!node || !$(node).length) && data && data.args && data.args.length) {
node = data.args[0];
}
if ((!node || !$(node).length) && data && data.node) {
node = data.node;
}
updateTreeAriaExpanded($(node), e.type === 'open_node');
})
.on('keydown', function(e) {
var key = e.key;
var target = e.target;
// Helper to get the toggle element (.jstree-icon--arrow) for a li node
var getDirectToggle = function($li) {
var toggle = $li.children('.jstree-icon--arrow')[0];
return toggle || null;
};
// Helper to get the direct anchor (<a>) for a li node
var getDirectAnchor = function($li) {
var a = $li.children('a')[0];
return a || null;
};
// Find previous visible node for ArrowUp
var getPrevVisible = function($li) {
// previous sibling's deepest visible descendant
var $prev = $li.prev('li');
if ($prev.length) {
while ($prev.hasClass('jstree-open') && $prev.find('> ul > li').length) {
$prev = $prev.find('> ul > li').last();
}
return getDirectAnchor($prev);
}
// otherwise parent (but not root node)
var $parent = $li.parents('li').first();
if ($parent.length && $parent.attr('id') !== 'record-0') {
return getDirectAnchor($parent);
}
return null;
};
// Find next visible node for ArrowDown
var getNextVisible = function($li) {
// first child if open
if ($li.hasClass('jstree-open')) {
var $child = $li.find('> ul > li').first();
if ($child.length) {
return getDirectAnchor($child);
}
}
// next sibling
var $next = $li.next('li');
if ($next.length) {
return getDirectAnchor($next);
}
// next ancestor sibling (but skip root node)
var $ancestors = $li.parents('li').not('#record-0');
for (var i = 0; i < $ancestors.length; i++) {
var $ancestor = $($ancestors[i]);
var $nextAncestor = $ancestor.next('li');
if ($nextAncestor.length) {
return getDirectAnchor($nextAncestor);
}
}
return null;
};
// Handle key events
var $li = $(target).closest('li');
if (key === 'Enter') {
// Enter already follows links, though for toggle icons it toggles
if ($(target).hasClass('jstree-icon')) {
$(this).jstree('toggle_node', $li);
}
} else if (key === ' ') {
// If in batch actions mode (tree has .multiple class) and on a link, toggle checkbox
if ($(this).hasClass('multiple') && $(target).is('a')) {
if ($li.hasClass('jstree-checked')) {
$(this).jstree('uncheck_node', $li);
} else {
$(this).jstree('check_node', $li);
}
e.preventDefault();
} else if ($(target).hasClass('jstree-icon')) {
// Pressing space toggles show/hide children if on the icon
$(this).jstree('toggle_node', $li);
}
} else if (key === 'ArrowLeft') {
// If node is open, close it
if ($li.hasClass('jstree-open')) {
$(this).jstree('close_node', $li);
} else {
// If node is closed, focus on parent (but not root)
var $parent = $li.parents('li').first();
if ($parent.length && $parent.attr('id') !== 'record-0') {
var parentTarget = getDirectAnchor($parent);
if (parentTarget) {
updateRovingTabindex(self, $(parentTarget));
parentTarget.focus();
}
}
}
} else if (key === 'ArrowRight') {
if ($li.hasClass('jstree-open')) {
// If node is already open, focus on the first child
var $child = $li.find('> ul > li').first();
if ($child.length) {
var childAnchor = getDirectAnchor($child);
if (childAnchor) {
updateRovingTabindex(self, $(childAnchor));
childAnchor.focus();
}
}
} else {
// If node is closed, open it
$(this).jstree('open_node', $li);
}
} else if (key === 'ArrowUp') {
var prev = getPrevVisible($li);
if (prev) {
updateRovingTabindex(self, $(prev));
prev.focus();
}
} else if (key === 'ArrowDown') {
var next = getNextVisible($li);
if (next) {
updateRovingTabindex(self, $(next));
next.focus();
}
} else if (key === 'Home') {
// Focus on first page node (not root)
var $firstPage = self.find('li[data-id]').not('[data-id="0"]').first();
if ($firstPage.length) {
var firstAnchor = getDirectAnchor($firstPage);
if (firstAnchor) {
updateRovingTabindex(self, $(firstAnchor));
firstAnchor.focus();
}
}
} else if (key === 'End') {
// Focus on last visible node
var $allVisible = self.find('li:visible');
if ($allVisible.length) {
var $last = $allVisible.last();
var lastAnchor = getDirectAnchor($last);
if (lastAnchor) {
updateRovingTabindex(self, $(lastAnchor));
lastAnchor.focus();
}
}
}
});
},
onremove: function(){
this.jstree('destroy');
this._super();
},
'from .cms-container': {
onafterstatechange: function(e){
this.updateFromEditForm();
// No need to refresh tree nodes, we assume only form submits cause state changes
}
},
'from .cms-container form': {
onaftersubmitform: function(e){
const id = $('.cms-edit-form :input[name=ID]').val();
const node = this.find(`[data-id=${id}]`);
let ids = [+id];
node.find('li').each(function () {
ids.push($(this).data('id'));
});
// Break ids up into reasonable chunks
const chunks = [];
let chunkSize = 50;
while(ids.length) {
const chunk = ids.slice(0, chunkSize);
chunks.push(chunk);
ids = ids.slice(chunkSize);
}
chunks.map((chunk) => this.updateNodesFromServer(chunk, false))
.reduce((chain, curr) => chain.then(curr), Promise.resolve());
}
},
/**
* Validates the moving of a node
* @param {Object} data provided by the move_node.jstree event
* @returns {Promise<boolean>} Returning false will prevent the node from moving
*/
canMove: async function(data) {
return Promise.resolve(true);
},
getTreeConfig: function() {
var self = this;
return {
'core': {
'initially_open': ['record-0'],
'animation': 0,
'html_titles': true
},
'html_data': {
// 'ajax' will be set on 'loaded.jstree' event
},
'ui': {
"select_limit" : 1,
'initially_select': [this.find('.current').attr('id')]
},
"crrm": {
'move': {
// Check if a node is allowed to be moved.
// Caution: Runs on every drag over a new node
'check_move': function(data) {
var movedNode = $(data.o), newParent = $(data.np),
isMovedOntoContainer = data.ot.get_container()[0] == data.np[0],
movedNodeClass = movedNode.getClassname(),
newParentClass = newParent.getClassname(),
// Check allowedChildren of newParent or against root node rules
hints = self.getHints(),
disallowedChildren = [],
hintKey = newParentClass ? newParentClass : 'Root',
hint = (hints && typeof hints[hintKey] != 'undefined') ? hints[hintKey] : null;
// Special case for VirtualPage: Check that original page type is an allowed child
if(hint && movedNode.attr('class').match(/VirtualPage-([^\s]*)/)) movedNodeClass = RegExp.$1;
if(hint) disallowedChildren = (typeof hint.disallowedChildren != 'undefined') ? hint.disallowedChildren : [];
var isAllowed = (
// Don't allow moving the root node
movedNode.data('id') !== 0
// Archived pages can't be moved
&& !movedNode.hasClass('status-archived')
// Only allow moving node inside the root container, not before/after it
&& (!isMovedOntoContainer || data.p == 'inside')
// Children are generally allowed on parent
&& !newParent.hasClass('nochildren')
// movedNode is allowed as a child
&& (!disallowedChildren.length || $.inArray(movedNodeClass, disallowedChildren) == -1)
);
return isAllowed;
}
}
},
'dnd': {
"drop_target" : false,
"drag_target" : false
},
'checkbox': {
'two_state': true
},
'themes': {
'theme': 'apple',
'url': $('body').data('frameworkpath') + '/admin/thirdparty/jstree/themes/apple/style.css'
},
// Caution: SilverStripe has disabled $.vakata.css.add_sheet() for performance reasons,
// which means you need to add any CSS manually to framework/admin/scss/_tree.css
'plugins': [
'html_data', 'ui', 'dnd', 'crrm', 'themes',
'checkbox' // checkboxes are hidden unless .multiple is set
]
};
},
/**
* Function:
* search
*
* Parameters:
* (Object) data Pass empty data to cancel search
* (Function) callback Success callback
*/
search: function(params, callback) {
if(params) this.data('searchparams', params);
else this.removeData('searchparams');
this.jstree('refresh', -1, callback);
},
/**
* Function: getNodeByID
*
* Parameters:
* (Int) id
*
* Returns
* DOMElement
*/
getNodeByID: function(id) {
return this.find('*[data-id='+id+']');
},
/**
* Creates a new node from the given HTML.
* Wrapping around jstree API because we want the flexibility to define
* the node's <li> ourselves. Places the node in the tree
* according to data.ParentID.
*
* Parameters:
* (String) HTML New node content (<li>)
* (Object) Map of additional data, e.g. ParentID
* (Function) Success callback
*/
createNode: function(html, data, callback) {
var self = this,
parentNode = data.ParentID !== void 0 ? self.getNodeByID(data.ParentID) : false, // Explicitly check for undefined as 0 is a valid ParentID
newNode = $(html);
// Extract the state for the new node from the properties taken from the provided HTML template.
// This will correctly initialise the behaviour of the node for ajax loading of children.
var properties = {data: ''};
if(newNode.hasClass('jstree-open')) {
properties.state = 'open';
} else if(newNode.hasClass('jstree-closed')) {
properties.state = 'closed';
}
this.jstree(
'create_node',
parentNode.length ? parentNode : -1,
'last',
properties,
function(node) {
var origClasses = node.attr('class');
// Copy attributes
for(var i=0; i<newNode[0].attributes.length; i++){
var attr = newNode[0].attributes[i];
node.attr(attr.name, attr.value);
}
// Substitute html from request for that generated by jstree
node.addClass(origClasses).html(newNode.html());
if (callback) {
callback(node);
}
}
);
},
/**
* Updates a node's state in the tree,
* including all of its HTML, as well as its position.
*
* Parameters:
* (DOMElement) Existing node
* (String) HTML New node content (<li>)
* (Object) Map of additional data, e.g. ParentID
*/
updateNode: function(node, html, data) {
// Strip any HTML comments out of the input data, in case of e.g. source file comments
html = html.replace(/<!--[\s\S]*?-->/g, '');
var self = this, newNode = $(html);
var nextNode = data.NextID ? this.getNodeByID(data.NextID) : false;
var prevNode = data.PrevID ? this.getNodeByID(data.PrevID) : false;
var parentNode = data.ParentID ? this.getNodeByID(data.ParentID) : false;
// Store some of the node properties before we update them
var parentOpen = this.jstree('is_open', parentNode);
// Copy attributes. We can't replace the node completely
// without removing or detaching its children nodes.
$.each(['id', 'style', 'class', 'data-pagetype'], function(i, attrName) {
node.attr(attrName, newNode.attr(attrName));
});
// Replace inner content
var origChildren = node.children('ul').detach();
node.html(newNode.html()).append(origChildren);
if (nextNode && nextNode.length) {
this.jstree('move_node', node, nextNode, 'before');
}
else if (prevNode && prevNode.length) {
this.jstree('move_node', node, prevNode, 'after');
}
else {
this.jstree('move_node', node, parentNode.length ? parentNode : -1);
}
// Restore some of the node properties after the nodes are replaced
if (parentOpen) {
this.jstree('open_node', parentNode);
} else {
this.jstree('close_node', parentNode);
}
},
/**
* Sets the current state based on the form the tree is managing.
*/
updateFromEditForm: function() {
var node, id = $('.cms-edit-form :input[name=ID]').val();
if(id) {
node = this.getNodeByID(id);
if(node.length) {
this.jstree('deselect_all');
this.jstree('select_node', node);
} else {
// If form is showing an ID that doesn't exist in the tree,
// get it from the server
this.updateNodesFromServer([id]);
}
} else {
// If no ID exists in a form view, we're displaying the tree on its own,
// hence to page should show as active
this.jstree('deselect_all');
}
},
/**
* Reloads the view of one or more tree nodes
* from the server, ensuring that their state is up to date
* (icon, title, hierarchy, badges, etc).
* This is easier, more consistent and more extensible
* than trying to correct all aspects via DOM modifications,
* based on the sparse data available in the current edit form.
*
* Parameters:
* (Array) List of IDs to retrieve
*/
updateNodesFromServer: function(ids, blocking = true) {
if (!this.getIsLoaded()) return;
if(blocking && this.getIsUpdatingTree()) return;
var self = this;
this.setIsUpdatingTree(true);
self.jstree('save_selected');
self.jstree('open_node', this.getNodeByID(0));
self.jstree('save_opened');
self.jstree('save_selected');
var selected = self.jstree('get_selected');
return new Promise(resolve => {
$.ajax({
url: $.path.addSearchParams(this.data('urlUpdatetreenodes'), 'ids=' + ids.join(',')),
dataType: 'json',
success: function (data, xhr) {
resolve(data);
$.each(data, function (nodeId, nodeData) {
var node = self.getNodeByID(nodeId);
// If no node data is given, assume the node has been removed
if (!nodeData) {
self.jstree('delete_node', node);
return;
}
// Check if node exists, create if necessary
if (node.length) {
self.updateNode(node, nodeData.html, nodeData);
} else {
// If the parent node can't be found, it might have not been loaded yet.
// This can happen for deep trees which require ajax loading.
// Assumes that the new node has been submitted to the server already.
if (nodeData.ParentID && !self.find('li[data-id=' + nodeData.ParentID + ']').length) {
self.jstree('load_node', -1);
} else {
self.createNode(nodeData.html, nodeData, (node) => {
// If there's no currently selected node and we're only updating 1
// node, assume we want that node selected
if (!selected.length && ids.length === 1) {
selected = node;
}
});
}
}
});
if (selected.length) {
self.jstree('deselect_all');
self.jstree('reopen');
self.jstree('select_node', selected);
}
},
complete: function () {
self.setIsUpdatingTree(false);
}
});
});
}
});
$('.cms-tree.multiple').entwine({
onmatch: function() {
this._super();
this.jstree('show_checkboxes');
},
onunmatch: function() {
this._super();
this.jstree('uncheck_all');
this.jstree('hide_checkboxes');
},
/**
* Function: getSelectedIDs
*
* Returns:
* (Array)
*/
getSelectedIDs: function() {
return $(this)
.jstree('get_checked')
.not('.disabled')
.map(function() {
return $(this).data('id');
})
.get();
}
});
$('.cms-tree li').entwine({
/**
* Function: setEnabled
*
* Parameters:
* (bool)
*/
setEnabled: function(bool) {
this.toggleClass('disabled', !(bool));
},
/**
* Function: getClassname
*
* Returns PHP class for this element. Useful to check business rules like valid drag'n'drop targets.
*/
getClassname: function() {
var matches = this.attr('class').match(/class-([^\s]*)/i);
return matches ? matches[1] : '';
},
/**
* Function: getID
*
* Returns:
* (Number)
*/
getID: function() {
return this.data('id');
}
});
});
}
export { updateRovingTabindex, resetTabindexToCurrentPage, updateTreeAriaExpanded };