MDL-70580 core: Tree nodes should check if they were clicked directly
[moodle.git] / lib / amd / src / tree.js
CommitLineData
f8895446
JO
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
17 * Implement an accessible aria tree widget, from a nested unordered list.
6759dc35 18 * Based on http://oaa-accessibility.org/example/41/.
f8895446
JO
19 *
20 * @module tool_lp/tree
21 * @package core
22 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25define(['jquery'], function($) {
26 // Private variables and functions.
27 var SELECTORS = {
28 ITEM: '[role=treeitem]',
4838a196
CB
29 GROUP: '[role=treeitem]:has([role=group]), [role=treeitem][aria-owns], [role=treeitem][data-requires-ajax=true]',
30 CLOSED_GROUP: '[role=treeitem]:has([role=group])[aria-expanded=false], [role=treeitem][aria-owns][aria-expanded=false], ' +
31 '[role=treeitem][data-requires-ajax=true][aria-expanded=false]',
f8895446
JO
32 FIRST_ITEM: '[role=treeitem]:first',
33 VISIBLE_ITEM: '[role=treeitem]:visible',
34 UNLOADED_AJAX_ITEM: '[role=treeitem][data-requires-ajax=true][data-loaded=false][aria-expanded=true]'
35 };
36
37 /**
6759dc35 38 * Constructor.
f8895446
JO
39 *
40 * @param {String} selector
41 * @param {function} selectCallback Called when the active node is changed.
42 */
43 var Tree = function(selector, selectCallback) {
44 this.treeRoot = $(selector);
45
46 this.treeRoot.data('activeItem', null);
47 this.selectCallback = selectCallback;
f8895446
JO
48 this.keys = {
49 tab: 9,
50 enter: 13,
51 space: 32,
52 pageup: 33,
53 pagedown: 34,
54 end: 35,
55 home: 36,
56 left: 37,
57 up: 38,
58 right: 39,
59 down: 40,
60 asterisk: 106
61 };
62
6759dc35 63 // Apply the standard default initialisation for all nodes, starting with the tree root.
f8895446 64 this.initialiseNodes(this.treeRoot);
6759dc35 65 // Make the first item the active item for the tree so that it is added to the tab order.
f8895446
JO
66 this.setActiveItem(this.treeRoot.find(SELECTORS.FIRST_ITEM));
67 // Create the cache of the visible items.
68 this.refreshVisibleItemsCache();
69 // Create the event handlers for the tree.
70 this.bindEventHandlers();
71 };
72
ff40c7d3
AG
73 Tree.prototype.registerEnterCallback = function(callback) {
74 this.enterCallback = callback;
75 };
76
f8895446
JO
77 /**
78 * Find all visible tree items and save a cache of them on the tree object.
79 *
80 * @method refreshVisibleItemsCache
81 */
82 Tree.prototype.refreshVisibleItemsCache = function() {
83 this.treeRoot.data('visibleItems', this.treeRoot.find(SELECTORS.VISIBLE_ITEM));
84 };
85
6759dc35
SL
86 /**
87 * Get all visible tree items.
88 *
89 * @method getVisibleItems
c96f55e6 90 * @return {Object} visible items
6759dc35 91 */
f8895446
JO
92 Tree.prototype.getVisibleItems = function() {
93 return this.treeRoot.data('visibleItems');
6759dc35 94 };
f8895446
JO
95
96 /**
6759dc35 97 * Mark the given item as active within the tree and fire the callback for when the active item is set.
f8895446
JO
98 *
99 * @method setActiveItem
6759dc35 100 * @param {object} item jquery object representing an item on the tree.
f8895446
JO
101 */
102 Tree.prototype.setActiveItem = function(item) {
103 var currentActive = this.treeRoot.data('activeItem');
104 if (item === currentActive) {
105 return;
106 }
107
108 // Remove previous active from tab order.
a057ba59 109 if (currentActive) {
f8895446
JO
110 currentActive.attr('tabindex', '-1');
111 currentActive.attr('aria-selected', 'false');
112 }
113 item.attr('tabindex', '0');
114 item.attr('aria-selected', 'true');
115
116 // Set the new active item.
117 this.treeRoot.data('activeItem', item);
118
119 if (typeof this.selectCallback === 'function') {
120 this.selectCallback(item);
121 }
122 };
123
124 /**
6759dc35 125 * Determines if the given item is a group item (contains child tree items) in the tree.
f8895446
JO
126 *
127 * @method isGroupItem
6759dc35 128 * @param {object} item jquery object representing an item on the tree.
f8895446
JO
129 * @returns {bool}
130 */
131 Tree.prototype.isGroupItem = function(item) {
132 return item.is(SELECTORS.GROUP);
133 };
134
4838a196
CB
135 /**
136 * Determines if the given item is a group item (contains child tree items) in the tree.
137 *
138 * @method isGroupItem
139 * @param {object} item jquery object representing an item on the tree.
140 * @returns {bool}
141 */
142 Tree.prototype.getGroupFromItem = function(item) {
ff40c7d3
AG
143 var ariaowns = this.treeRoot.find('#' + item.attr('aria-owns'));
144 var plain = item.children('[role=group]');
145 if (ariaowns.length > plain.length) {
146 return ariaowns;
147 } else {
148 return plain;
149 }
4838a196
CB
150 };
151
5697de18
RW
152 /**
153 * Determines if the given group item (contains child tree items) is collapsed.
154 *
155 * @method isGroupCollapsed
156 * @param {object} item jquery object representing a group item on the tree.
157 * @returns {bool}
158 */
159 Tree.prototype.isGroupCollapsed = function(item) {
160 return item.attr('aria-expanded') === 'false';
161 };
162
163 /**
164 * Determines if the given group item (contains child tree items) can be collapsed.
165 *
166 * @method isGroupCollapsible
167 * @param {object} item jquery object representing a group item on the tree.
168 * @returns {bool}
169 */
170 Tree.prototype.isGroupCollapsible = function(item) {
171 return item.attr('data-collapsible') !== 'false';
172 };
173
f8895446
JO
174 /**
175 * Performs the tree initialisation for all child items from the given node,
176 * such as removing everything from the tab order and setting aria selected
177 * on items.
178 *
179 * @method initialiseNodes
6759dc35 180 * @param {object} node jquery object representing a node.
f8895446
JO
181 */
182 Tree.prototype.initialiseNodes = function(node) {
183 this.removeAllFromTabOrder(node);
184 this.setAriaSelectedFalseOnItems(node);
185
6759dc35 186 // Get all ajax nodes that have been rendered as expanded but haven't loaded the child items yet.
f8895446
JO
187 var thisTree = this;
188 node.find(SELECTORS.UNLOADED_AJAX_ITEM).each(function() {
189 var unloadedNode = $(this);
190 // Collapse and then expand to trigger the ajax loading.
191 thisTree.collapseGroup(unloadedNode);
192 thisTree.expandGroup(unloadedNode);
193 });
194 };
195
196 /**
197 * Removes all child DOM elements of the given node from the tab order.
198 *
199 * @method removeAllFromTabOrder
6759dc35 200 * @param {object} node jquery object representing a node.
f8895446
JO
201 */
202 Tree.prototype.removeAllFromTabOrder = function(node) {
203 node.find('*').attr('tabindex', '-1');
4838a196 204 this.getGroupFromItem($(node)).find('*').attr('tabindex', '-1');
f8895446
JO
205 };
206
207 /**
6759dc35 208 * Find all child tree items from the given node and set the aria selected attribute to false.
f8895446
JO
209 *
210 * @method setAriaSelectedFalseOnItems
6759dc35 211 * @param {object} node jquery object representing a node.
f8895446
JO
212 */
213 Tree.prototype.setAriaSelectedFalseOnItems = function(node) {
214 node.find(SELECTORS.ITEM).attr('aria-selected', 'false');
215 };
216
217 /**
218 * Expand all group nodes within the tree.
219 *
220 * @method expandAllGroups
221 */
222 Tree.prototype.expandAllGroups = function() {
4838a196
CB
223 var thisTree = this;
224
225 this.treeRoot.find(SELECTORS.CLOSED_GROUP).each(function() {
226 var groupNode = $(this);
227
228 thisTree.expandGroup($(this)).done(function() {
229 thisTree.expandAllChildGroups(groupNode);
230 });
231 });
6759dc35 232 };
f8895446
JO
233
234 /**
235 * Find all child group nodes from the given node and expand them.
236 *
237 * @method expandAllChildGroups
4838a196 238 * @param {Object} item is the jquery id of the group.
f8895446 239 */
4838a196 240 Tree.prototype.expandAllChildGroups = function(item) {
f8895446
JO
241 var thisTree = this;
242
4838a196
CB
243 this.getGroupFromItem(item).find(SELECTORS.CLOSED_GROUP).each(function() {
244 var groupNode = $(this);
245
246 thisTree.expandGroup($(this)).done(function() {
247 thisTree.expandAllChildGroups(groupNode);
f8895446
JO
248 });
249 });
250 };
251
252 /**
6759dc35
SL
253 * Expand a collapsed group.
254 *
255 * Handles expanding nodes that are ajax loaded (marked with a data-requires-ajax attribute).
f8895446
JO
256 *
257 * @method expandGroup
6759dc35
SL
258 * @param {Object} item is the jquery id of the parent item of the group.
259 * @return {Object} a promise that is resolved when the group has been expanded.
f8895446
JO
260 */
261 Tree.prototype.expandGroup = function(item) {
262 var promise = $.Deferred();
263 // Ignore nodes that are explicitly maked as not expandable or are already expanded.
5697de18 264 if (item.attr('data-expandable') !== 'false' && this.isGroupCollapsed(item)) {
f8895446
JO
265 // If this node requires ajax load and we haven't already loaded it.
266 if (item.attr('data-requires-ajax') === 'true' && item.attr('data-loaded') !== 'true') {
267 item.attr('data-loaded', false);
268 // Get the closes ajax loading module specificed in the tree.
269 var moduleName = item.closest('[data-ajax-loader]').attr('data-ajax-loader');
270 var thisTree = this;
271 // Flag this node as loading.
272 item.addClass('loading');
273 // Require the ajax module (must be AMD) and try to load the items.
274 require([moduleName], function(loader) {
275 // All ajax module must implement a "load" method.
276 loader.load(item).done(function() {
277 item.attr('data-loaded', true);
278
279 // Set defaults on the newly constructed part of the tree.
280 thisTree.initialiseNodes(item);
281 thisTree.finishExpandingGroup(item);
282 // Make sure no child elements of the item we just loaded are tabbable.
283 item.removeClass('loading');
284 promise.resolve();
285 });
286 });
287 } else {
288 this.finishExpandingGroup(item);
289 promise.resolve();
290 }
291 } else {
292 promise.resolve();
293 }
f8895446
JO
294 return promise;
295 };
296
297 /**
6759dc35 298 * Perform the necessary DOM changes to display a group item.
f8895446
JO
299 *
300 * @method finishExpandingGroup
6759dc35 301 * @param {Object} item is the jquery id of the parent item of the group.
f8895446
JO
302 */
303 Tree.prototype.finishExpandingGroup = function(item) {
f8895446 304 // Expand the group.
4838a196 305 var group = this.getGroupFromItem(item);
7cc18dc2 306 group.removeAttr('aria-hidden');
f8895446
JO
307 item.attr('aria-expanded', 'true');
308
309 // Update the list of visible items.
310 this.refreshVisibleItemsCache();
311 };
312
313 /**
314 * Collapse an expanded group.
315 *
316 * @method collapseGroup
6759dc35 317 * @param {Object} item is the jquery id of the parent item of the group.
f8895446
JO
318 */
319 Tree.prototype.collapseGroup = function(item) {
5697de18
RW
320 // If the item is not collapsible or already collapsed then do nothing.
321 if (!this.isGroupCollapsible(item) || this.isGroupCollapsed(item)) {
f8895446
JO
322 return;
323 }
324
4838a196
CB
325 // Collapse the group.
326 var group = this.getGroupFromItem(item);
327 group.attr('aria-hidden', 'true');
f8895446
JO
328 item.attr('aria-expanded', 'false');
329
330 // Update the list of visible items.
331 this.refreshVisibleItemsCache();
332 };
333
334 /**
335 * Expand or collapse a group.
336 *
337 * @method toggleGroup
6759dc35 338 * @param {Object} item is the jquery id of the parent item of the group.
f8895446
JO
339 */
340 Tree.prototype.toggleGroup = function(item) {
341 if (item.attr('aria-expanded') === 'true') {
342 this.collapseGroup(item);
343 } else {
344 this.expandGroup(item);
345 }
346 };
347
348 /**
349 * Handle a key down event - ie navigate the tree.
350 *
351 * @method handleKeyDown
f8895446
JO
352 * @param {Event} e The event.
353 */
037de719
DP
354 // This function should be simplified. In the meantime..
355 // eslint-disable-next-line complexity
357909b2
AN
356 Tree.prototype.handleKeyDown = function(e) {
357 var item = $(e.target);
f8895446
JO
358 var currentIndex = this.getVisibleItems().index(item);
359
fd838797 360 if ((e.altKey || e.ctrlKey || e.metaKey) || (e.shiftKey && e.keyCode != this.keys.tab)) {
f8895446 361 // Do nothing.
eeaf19eb 362 return;
f8895446
JO
363 }
364
365 switch (e.keyCode) {
366 case this.keys.home: {
367 // Jump to first item in tree.
368 this.getVisibleItems().first().focus();
369
eeaf19eb
MH
370 e.preventDefault();
371 return;
f8895446
JO
372 }
373 case this.keys.end: {
374 // Jump to last visible item.
375 this.getVisibleItems().last().focus();
376
eeaf19eb
MH
377 e.preventDefault();
378 return;
f8895446
JO
379 }
380 case this.keys.enter: {
4838a196 381 var links = item.children('a').length ? item.children('a') : item.children().not(SELECTORS.GROUP).find('a');
f8895446 382 if (links.length) {
eeaf19eb
MH
383 if (links.first().data('overrides-tree-activation-key-handler')) {
384 // If the link overrides handling of activation keys, let it do so.
385 links.first().triggerHandler(e);
386 } else if (typeof this.enterCallback === 'function') {
387 // Use callback if there is one.
ff40c7d3
AG
388 this.enterCallback(item);
389 } else {
390 window.location.href = links.first().attr('href');
391 }
f8895446
JO
392 } else if (this.isGroupItem(item)) {
393 this.toggleGroup(item, true);
394 }
395
eeaf19eb
MH
396 e.preventDefault();
397 return;
f8895446
JO
398 }
399 case this.keys.space: {
400 if (this.isGroupItem(item)) {
401 this.toggleGroup(item, true);
eeaf19eb
MH
402 } else if (item.children('a').length) {
403 var firstLink = item.children('a').first();
404
405 if (firstLink.data('overrides-tree-activation-key-handler')) {
406 firstLink.triggerHandler(e);
407 }
f8895446
JO
408 }
409
eeaf19eb
MH
410 e.preventDefault();
411 return;
f8895446
JO
412 }
413 case this.keys.left: {
5697de18
RW
414 var focusParent = function(tree) {
415 // Get the immediate visible parent group item that contains this element.
4838a196
CB
416 tree.getVisibleItems().filter(function() {
417 return tree.getGroupFromItem($(this)).has(item).length;
418 }).focus();
5697de18
RW
419 };
420
f8895446
JO
421 // If this is a goup item then collapse it and focus the parent group
422 // in accordance with the aria spec.
423 if (this.isGroupItem(item)) {
5697de18
RW
424 if (this.isGroupCollapsed(item)) {
425 focusParent(this);
426 } else {
427 this.collapseGroup(item);
428 }
429 } else {
430 focusParent(this);
f8895446
JO
431 }
432
eeaf19eb
MH
433 e.preventDefault();
434 return;
f8895446
JO
435 }
436 case this.keys.right: {
437 // If this is a group item then expand it and focus the first child item
438 // in accordance with the aria spec.
439 if (this.isGroupItem(item)) {
5697de18
RW
440 if (this.isGroupCollapsed(item)) {
441 this.expandGroup(item);
442 } else {
f8895446 443 // Move to the first item in the child group.
4838a196 444 this.getGroupFromItem(item).find(SELECTORS.ITEM).first().focus();
5697de18 445 }
f8895446
JO
446 }
447
eeaf19eb
MH
448 e.preventDefault();
449 return;
f8895446
JO
450 }
451 case this.keys.up: {
452
453 if (currentIndex > 0) {
454 var prev = this.getVisibleItems().eq(currentIndex - 1);
455
456 prev.focus();
457 }
458
eeaf19eb
MH
459 e.preventDefault();
460 return;
f8895446
JO
461 }
462 case this.keys.down: {
463
464 if (currentIndex < this.getVisibleItems().length - 1) {
465 var next = this.getVisibleItems().eq(currentIndex + 1);
466
467 next.focus();
468 }
6759dc35 469
eeaf19eb
MH
470 e.preventDefault();
471 return;
f8895446
JO
472 }
473 case this.keys.asterisk: {
474 // Expand all groups.
f8895446 475 this.expandAllGroups();
eeaf19eb
MH
476 e.preventDefault();
477 return;
f8895446
JO
478 }
479 }
f8895446
JO
480 };
481
482 /**
483 * Handle a click (select).
484 *
485 * @method handleClick
f8895446
JO
486 * @param {Event} e The event.
487 */
357909b2 488 Tree.prototype.handleClick = function(e) {
fd838797 489 if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
f8895446 490 // Do nothing.
599eed0f 491 return;
f8895446
JO
492 }
493
357909b2
AN
494 var item = $(e.target);
495
496 if (e.target !== e.currentTarget) {
497 return;
498 }
499
f8895446
JO
500 // Update the active item.
501 item.focus();
502
503 // If the item is a group node.
504 if (this.isGroupItem(item)) {
505 this.toggleGroup(item);
506 }
f8895446
JO
507 };
508
509 /**
6759dc35 510 * Handle a focus event.
f8895446
JO
511 *
512 * @method handleFocus
f8895446
JO
513 * @param {Event} e The event.
514 */
357909b2
AN
515 Tree.prototype.handleFocus = function(e) {
516 this.setActiveItem($(e.target));
f8895446
JO
517 };
518
519 /**
520 * Bind the event listeners we require.
521 *
522 * @method bindEventHandlers
523 */
524 Tree.prototype.bindEventHandlers = function() {
f8895446
JO
525 // Bind event handlers to the tree items. Use event delegates to allow
526 // for dynamically loaded parts of the tree.
527 this.treeRoot.on({
357909b2
AN
528 click: this.handleClick.bind(this),
529 keydown: this.handleKeyDown.bind(this),
530 focus: this.handleFocus.bind(this),
f8895446
JO
531 }, SELECTORS.ITEM);
532 };
533
534 return /** @alias module:tool_lp/tree */ Tree;
535});