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
22 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 define(['jquery'], function($) {
26 // Private variables and functions.
28 ITEM: '[role=treeitem]',
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]',
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]'
40 * @param {String} selector
41 * @param {function} selectCallback Called when the active node is changed.
43 var Tree = function(selector, selectCallback) {
44 this.treeRoot = $(selector);
46 this.treeRoot.data('activeItem', null);
47 this.selectCallback = selectCallback;
63 // Apply the standard default initialisation for all nodes, starting with the tree root.
64 this.initialiseNodes(this.treeRoot);
65 // Make the first item the active item for the tree so that it is added to the tab order.
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();
73 Tree.prototype.registerEnterCallback = function(callback) {
74 this.enterCallback = callback;
78 * Find all visible tree items and save a cache of them on the tree object.
80 * @method refreshVisibleItemsCache
82 Tree.prototype.refreshVisibleItemsCache = function() {
83 this.treeRoot.data('visibleItems', this.treeRoot.find(SELECTORS.VISIBLE_ITEM));
87 * Get all visible tree items.
89 * @method getVisibleItems
90 * @return {Object} visible items
92 Tree.prototype.getVisibleItems = function() {
93 return this.treeRoot.data('visibleItems');
97 * Mark the given item as active within the tree and fire the callback for when the active item is set.
99 * @method setActiveItem
100 * @param {object} item jquery object representing an item on the tree.
102 Tree.prototype.setActiveItem = function(item) {
103 var currentActive = this.treeRoot.data('activeItem');
104 if (item === currentActive) {
108 // Remove previous active from tab order.
110 currentActive.attr('tabindex', '-1');
111 currentActive.attr('aria-selected', 'false');
113 item.attr('tabindex', '0');
114 item.attr('aria-selected', 'true');
116 // Set the new active item.
117 this.treeRoot.data('activeItem', item);
119 if (typeof this.selectCallback === 'function') {
120 this.selectCallback(item);
125 * Determines if the given item is a group item (contains child tree items) in the tree.
127 * @method isGroupItem
128 * @param {object} item jquery object representing an item on the tree.
131 Tree.prototype.isGroupItem = function(item) {
132 return item.is(SELECTORS.GROUP);
136 * Determines if the given item is a group item (contains child tree items) in the tree.
138 * @method isGroupItem
139 * @param {object} item jquery object representing an item on the tree.
142 Tree.prototype.getGroupFromItem = function(item) {
143 var ariaowns = this.treeRoot.find('#' + item.attr('aria-owns'));
144 var plain = item.children('[role=group]');
145 if (ariaowns.length > plain.length) {
153 * Determines if the given group item (contains child tree items) is collapsed.
155 * @method isGroupCollapsed
156 * @param {object} item jquery object representing a group item on the tree.
159 Tree.prototype.isGroupCollapsed = function(item) {
160 return item.attr('aria-expanded') === 'false';
164 * Determines if the given group item (contains child tree items) can be collapsed.
166 * @method isGroupCollapsible
167 * @param {object} item jquery object representing a group item on the tree.
170 Tree.prototype.isGroupCollapsible = function(item) {
171 return item.attr('data-collapsible') !== 'false';
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
179 * @method initialiseNodes
180 * @param {object} node jquery object representing a node.
182 Tree.prototype.initialiseNodes = function(node) {
183 this.removeAllFromTabOrder(node);
184 this.setAriaSelectedFalseOnItems(node);
186 // Get all ajax nodes that have been rendered as expanded but haven't loaded the child items yet.
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);
197 * Removes all child DOM elements of the given node from the tab order.
199 * @method removeAllFromTabOrder
200 * @param {object} node jquery object representing a node.
202 Tree.prototype.removeAllFromTabOrder = function(node) {
203 node.find('*').attr('tabindex', '-1');
204 this.getGroupFromItem($(node)).find('*').attr('tabindex', '-1');
208 * Find all child tree items from the given node and set the aria selected attribute to false.
210 * @method setAriaSelectedFalseOnItems
211 * @param {object} node jquery object representing a node.
213 Tree.prototype.setAriaSelectedFalseOnItems = function(node) {
214 node.find(SELECTORS.ITEM).attr('aria-selected', 'false');
218 * Expand all group nodes within the tree.
220 * @method expandAllGroups
222 Tree.prototype.expandAllGroups = function() {
225 this.treeRoot.find(SELECTORS.CLOSED_GROUP).each(function() {
226 var groupNode = $(this);
228 thisTree.expandGroup($(this)).done(function() {
229 thisTree.expandAllChildGroups(groupNode);
235 * Find all child group nodes from the given node and expand them.
237 * @method expandAllChildGroups
238 * @param {Object} item is the jquery id of the group.
240 Tree.prototype.expandAllChildGroups = function(item) {
243 this.getGroupFromItem(item).find(SELECTORS.CLOSED_GROUP).each(function() {
244 var groupNode = $(this);
246 thisTree.expandGroup($(this)).done(function() {
247 thisTree.expandAllChildGroups(groupNode);
253 * Expand a collapsed group.
255 * Handles expanding nodes that are ajax loaded (marked with a data-requires-ajax attribute).
257 * @method expandGroup
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.
261 Tree.prototype.expandGroup = function(item) {
262 var promise = $.Deferred();
263 // Ignore nodes that are explicitly maked as not expandable or are already expanded.
264 if (item.attr('data-expandable') !== 'false' && this.isGroupCollapsed(item)) {
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');
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);
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');
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 {Object} item is the jquery id of the parent item of the group.
353 * @param {Event} e The event.
355 // This function should be simplified. In the meantime..
356 // eslint-disable-next-line complexity
357 Tree.prototype.handleKeyDown = function(item, e) {
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 goup 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 {Object} item The jquery id of the parent item of the group.
487 * @param {Event} e The event.
489 Tree.prototype.handleClick = function(item, e) {
491 if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
496 // Update the active item.
499 // If the item is a group node.
500 if (this.isGroupItem(item)) {
501 this.toggleGroup(item);
506 * Handle a focus event.
508 * @method handleFocus
509 * @param {Object} item The jquery id of the parent item of the group.
510 * @param {Event} e The event.
512 Tree.prototype.handleFocus = function(item) {
514 this.setActiveItem(item);
518 * Bind the event listeners we require.
520 * @method bindEventHandlers
522 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.
529 return thisObj.handleClick($(this), e);
531 keydown: function(e) {
532 return thisObj.handleKeyDown($(this), e);
535 return thisObj.handleFocus($(this));
540 return /** @alias module:tool_lp/tree */ Tree;