1 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
17 * Implement an accessible aria tree widget, from a nested unordered list.
18 * Based on http://oaa-accessibility.org/example/41/.
20 * @module tool_lp/tree
21 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 define(['jquery'], function($) {
25 // Private variables and functions.
27 ITEM: '[role=treeitem]',
28 GROUP: '[role=treeitem]:has([role=group]), [role=treeitem][aria-owns], [role=treeitem][data-requires-ajax=true]',
29 CLOSED_GROUP: '[role=treeitem]:has([role=group])[aria-expanded=false], [role=treeitem][aria-owns][aria-expanded=false], ' +
30 '[role=treeitem][data-requires-ajax=true][aria-expanded=false]',
31 FIRST_ITEM: '[role=treeitem]:first',
32 VISIBLE_ITEM: '[role=treeitem]:visible',
33 UNLOADED_AJAX_ITEM: '[role=treeitem][data-requires-ajax=true][data-loaded=false][aria-expanded=true]'
39 * @param {String} selector
40 * @param {function} selectCallback Called when the active node is changed.
42 var Tree = function(selector, selectCallback) {
43 this.treeRoot = $(selector);
45 this.treeRoot.data('activeItem', null);
46 this.selectCallback = selectCallback;
62 // Apply the standard default initialisation for all nodes, starting with the tree root.
63 this.initialiseNodes(this.treeRoot);
64 // Make the first item the active item for the tree so that it is added to the tab order.
65 this.setActiveItem(this.treeRoot.find(SELECTORS.FIRST_ITEM));
66 // Create the cache of the visible items.
67 this.refreshVisibleItemsCache();
68 // Create the event handlers for the tree.
69 this.bindEventHandlers();
72 Tree.prototype.registerEnterCallback = function(callback) {
73 this.enterCallback = callback;
77 * Find all visible tree items and save a cache of them on the tree object.
79 * @method refreshVisibleItemsCache
81 Tree.prototype.refreshVisibleItemsCache = function() {
82 this.treeRoot.data('visibleItems', this.treeRoot.find(SELECTORS.VISIBLE_ITEM));
86 * Get all visible tree items.
88 * @method getVisibleItems
89 * @return {Object} visible items
91 Tree.prototype.getVisibleItems = function() {
92 return this.treeRoot.data('visibleItems');
96 * Mark the given item as active within the tree and fire the callback for when the active item is set.
98 * @method setActiveItem
99 * @param {object} item jquery object representing an item on the tree.
101 Tree.prototype.setActiveItem = function(item) {
102 var currentActive = this.treeRoot.data('activeItem');
103 if (item === currentActive) {
107 // Remove previous active from tab order.
109 currentActive.attr('tabindex', '-1');
110 currentActive.attr('aria-selected', 'false');
112 item.attr('tabindex', '0');
113 item.attr('aria-selected', 'true');
115 // Set the new active item.
116 this.treeRoot.data('activeItem', item);
118 if (typeof this.selectCallback === 'function') {
119 this.selectCallback(item);
124 * Determines if the given item is a group item (contains child tree items) in the tree.
126 * @method isGroupItem
127 * @param {object} item jquery object representing an item on the tree.
130 Tree.prototype.isGroupItem = function(item) {
131 return item.is(SELECTORS.GROUP);
135 * Determines if the given item is a group item (contains child tree items) in the tree.
137 * @method isGroupItem
138 * @param {object} item jquery object representing an item on the tree.
141 Tree.prototype.getGroupFromItem = function(item) {
142 var ariaowns = this.treeRoot.find('#' + item.attr('aria-owns'));
143 var plain = item.children('[role=group]');
144 if (ariaowns.length > plain.length) {
152 * Determines if the given group item (contains child tree items) is collapsed.
154 * @method isGroupCollapsed
155 * @param {object} item jquery object representing a group item on the tree.
158 Tree.prototype.isGroupCollapsed = function(item) {
159 return item.attr('aria-expanded') === 'false';
163 * Determines if the given group item (contains child tree items) can be collapsed.
165 * @method isGroupCollapsible
166 * @param {object} item jquery object representing a group item on the tree.
169 Tree.prototype.isGroupCollapsible = function(item) {
170 return item.attr('data-collapsible') !== 'false';
174 * Performs the tree initialisation for all child items from the given node,
175 * such as removing everything from the tab order and setting aria selected
178 * @method initialiseNodes
179 * @param {object} node jquery object representing a node.
181 Tree.prototype.initialiseNodes = function(node) {
182 this.removeAllFromTabOrder(node);
183 this.setAriaSelectedFalseOnItems(node);
185 // Get all ajax nodes that have been rendered as expanded but haven't loaded the child items yet.
187 node.find(SELECTORS.UNLOADED_AJAX_ITEM).each(function() {
188 var unloadedNode = $(this);
189 // Collapse and then expand to trigger the ajax loading.
190 thisTree.collapseGroup(unloadedNode);
191 thisTree.expandGroup(unloadedNode);
196 * Removes all child DOM elements of the given node from the tab order.
198 * @method removeAllFromTabOrder
199 * @param {object} node jquery object representing a node.
201 Tree.prototype.removeAllFromTabOrder = function(node) {
202 node.find('*').attr('tabindex', '-1');
203 this.getGroupFromItem($(node)).find('*').attr('tabindex', '-1');
207 * Find all child tree items from the given node and set the aria selected attribute to false.
209 * @method setAriaSelectedFalseOnItems
210 * @param {object} node jquery object representing a node.
212 Tree.prototype.setAriaSelectedFalseOnItems = function(node) {
213 node.find(SELECTORS.ITEM).attr('aria-selected', 'false');
217 * Expand all group nodes within the tree.
219 * @method expandAllGroups
221 Tree.prototype.expandAllGroups = function() {
224 this.treeRoot.find(SELECTORS.CLOSED_GROUP).each(function() {
225 var groupNode = $(this);
227 thisTree.expandGroup($(this)).done(function() {
228 thisTree.expandAllChildGroups(groupNode);
234 * Find all child group nodes from the given node and expand them.
236 * @method expandAllChildGroups
237 * @param {Object} item is the jquery id of the group.
239 Tree.prototype.expandAllChildGroups = function(item) {
242 this.getGroupFromItem(item).find(SELECTORS.CLOSED_GROUP).each(function() {
243 var groupNode = $(this);
245 thisTree.expandGroup($(this)).done(function() {
246 thisTree.expandAllChildGroups(groupNode);
252 * Expand a collapsed group.
254 * Handles expanding nodes that are ajax loaded (marked with a data-requires-ajax attribute).
256 * @method expandGroup
257 * @param {Object} item is the jquery id of the parent item of the group.
258 * @return {Object} a promise that is resolved when the group has been expanded.
260 Tree.prototype.expandGroup = function(item) {
261 var promise = $.Deferred();
262 // Ignore nodes that are explicitly maked as not expandable or are already expanded.
263 if (item.attr('data-expandable') !== 'false' && this.isGroupCollapsed(item)) {
264 // If this node requires ajax load and we haven't already loaded it.
265 if (item.attr('data-requires-ajax') === 'true' && item.attr('data-loaded') !== 'true') {
266 item.attr('data-loaded', false);
267 // Get the closes ajax loading module specificed in the tree.
268 var moduleName = item.closest('[data-ajax-loader]').attr('data-ajax-loader');
270 // Flag this node as loading.
271 const p = item.find('p');
272 p.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);
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 p.removeClass('loading');
288 this.finishExpandingGroup(item);
298 * Perform the necessary DOM changes to display a group item.
300 * @method finishExpandingGroup
301 * @param {Object} item is the jquery id of the parent item of the group.
303 Tree.prototype.finishExpandingGroup = function(item) {
305 var group = this.getGroupFromItem(item);
306 group.removeAttr('aria-hidden');
307 item.attr('aria-expanded', 'true');
309 // Update the list of visible items.
310 this.refreshVisibleItemsCache();
314 * Collapse an expanded group.
316 * @method collapseGroup
317 * @param {Object} item is the jquery id of the parent item of the group.
319 Tree.prototype.collapseGroup = function(item) {
320 // If the item is not collapsible or already collapsed then do nothing.
321 if (!this.isGroupCollapsible(item) || this.isGroupCollapsed(item)) {
325 // Collapse the group.
326 var group = this.getGroupFromItem(item);
327 group.attr('aria-hidden', 'true');
328 item.attr('aria-expanded', 'false');
330 // Update the list of visible items.
331 this.refreshVisibleItemsCache();
335 * Expand or collapse a group.
337 * @method toggleGroup
338 * @param {Object} item is the jquery id of the parent item of the group.
340 Tree.prototype.toggleGroup = function(item) {
341 if (item.attr('aria-expanded') === 'true') {
342 this.collapseGroup(item);
344 this.expandGroup(item);
349 * Handle a key down event - ie navigate the tree.
351 * @method handleKeyDown
352 * @param {Event} e The event.
354 // This function should be simplified. In the meantime..
355 // eslint-disable-next-line complexity
356 Tree.prototype.handleKeyDown = function(e) {
357 var item = $(e.target);
358 var currentIndex = this.getVisibleItems().index(item);
360 if ((e.altKey || e.ctrlKey || e.metaKey) || (e.shiftKey && e.keyCode != this.keys.tab)) {
366 case this.keys.home: {
367 // Jump to first item in tree.
368 this.getVisibleItems().first().focus();
373 case this.keys.end: {
374 // Jump to last visible item.
375 this.getVisibleItems().last().focus();
380 case this.keys.enter: {
381 var links = item.children('a').length ? item.children('a') : item.children().not(SELECTORS.GROUP).find('a');
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.
388 this.enterCallback(item);
390 window.location.href = links.first().attr('href');
392 } else if (this.isGroupItem(item)) {
393 this.toggleGroup(item, true);
399 case this.keys.space: {
400 if (this.isGroupItem(item)) {
401 this.toggleGroup(item, true);
402 } else if (item.children('a').length) {
403 var firstLink = item.children('a').first();
405 if (firstLink.data('overrides-tree-activation-key-handler')) {
406 firstLink.triggerHandler(e);
413 case this.keys.left: {
414 var focusParent = function(tree) {
415 // Get the immediate visible parent group item that contains this element.
416 tree.getVisibleItems().filter(function() {
417 return tree.getGroupFromItem($(this)).has(item).length;
421 // If this is a group item then collapse it and focus the parent group
422 // in accordance with the aria spec.
423 if (this.isGroupItem(item)) {
424 if (this.isGroupCollapsed(item)) {
427 this.collapseGroup(item);
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)) {
440 if (this.isGroupCollapsed(item)) {
441 this.expandGroup(item);
443 // Move to the first item in the child group.
444 this.getGroupFromItem(item).find(SELECTORS.ITEM).first().focus();
453 if (currentIndex > 0) {
454 var prev = this.getVisibleItems().eq(currentIndex - 1);
462 case this.keys.down: {
464 if (currentIndex < this.getVisibleItems().length - 1) {
465 var next = this.getVisibleItems().eq(currentIndex + 1);
473 case this.keys.asterisk: {
474 // Expand all groups.
475 this.expandAllGroups();
483 * Handle a click (select).
485 * @method handleClick
486 * @param {Event} e The event.
488 Tree.prototype.handleClick = function(e) {
489 if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
494 // Get the closest tree item from the event target.
495 var item = $(e.target).closest('[role="treeitem"]');
496 if (!item.is(e.currentTarget)) {
500 // Update the active item.
503 // If the item is a group node.
504 if (this.isGroupItem(item)) {
505 this.toggleGroup(item);
510 * Handle a focus event.
512 * @method handleFocus
513 * @param {Event} e The event.
515 Tree.prototype.handleFocus = function(e) {
516 this.setActiveItem($(e.target));
520 * Bind the event listeners we require.
522 * @method bindEventHandlers
524 Tree.prototype.bindEventHandlers = function() {
525 // Bind event handlers to the tree items. Use event delegates to allow
526 // for dynamically loaded parts of the tree.
528 click: this.handleClick.bind(this),
529 keydown: this.handleKeyDown.bind(this),
530 focus: this.handleFocus.bind(this),
534 return /** @alias module:core/tree */ Tree;