-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtabby.js
456 lines (359 loc) · 10.6 KB
/
tabby.js
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
/*!
* tabbyjs v12.0.3
* Lightweight, accessible vanilla JS toggle tabs.
* (c) 2019 Chris Ferdinandi
* MIT License
* http://github.com/cferdinandi/tabby
*/
/**
* Element.matches() polyfill (simple version)
* https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
*/
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}
/**
* Element.closest() polyfill
* https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
*/
if (!Element.prototype.closest) {
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}
Element.prototype.closest = function (s) {
var el = this;
var ancestor = this;
if (!document.documentElement.contains(el)) return null;
do {
if (ancestor.matches(s)) return ancestor;
ancestor = ancestor.parentElement;
} while (ancestor !== null);
return null;
};
}
(function (root, factory) {
if ( typeof define === 'function' && define.amd ) {
define([], (function () {
return factory(root);
}));
} else if ( typeof exports === 'object' ) {
module.exports = factory(root);
} else {
root.Tabby = factory(root);
}
})(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) {
'use strict';
//
// Variables
//
var defaults = {
idPrefix: 'tabby-toggle_',
default: '[data-tabby-default]'
};
//
// Methods
//
/**
* Merge two or more objects together.
* @param {Object} objects The objects to merge together
* @returns {Object} Merged values of defaults and options
*/
var extend = function () {
var merged = {};
Array.prototype.forEach.call(arguments, (function (obj) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) return;
merged[key] = obj[key];
}
}));
return merged;
};
/**
* Emit a custom event
* @param {String} type The event type
* @param {Node} tab The tab to attach the event to
* @param {Node} details Details about the event
*/
var emitEvent = function (tab, details) {
// Create a new event
var event;
if (typeof window.CustomEvent === 'function') {
event = new CustomEvent('tabby', {
bubbles: true,
cancelable: true,
detail: details
});
} else {
event = document.createEvent('CustomEvent');
event.initCustomEvent('tabby', true, true, details);
}
// Dispatch the event
tab.dispatchEvent(event);
};
/**
* Remove roles and attributes from a tab and its content
* @param {Node} tab The tab
* @param {Node} content The tab content
* @param {Object} settings User settings and options
*/
var destroyTab = function (tab, content, settings) {
// Remove the generated ID
if (tab.id.slice(0, settings.idPrefix.length) === settings.idPrefix) {
tab.id = '';
}
// Remove roles
tab.removeAttribute('role');
tab.removeAttribute('aria-controls');
tab.removeAttribute('aria-selected');
tab.removeAttribute('tabindex');
tab.closest('li').removeAttribute('role');
content.removeAttribute('role');
content.removeAttribute('aria-labelledby');
content.removeAttribute('hidden');
};
/**
* Add the required roles and attributes to a tab and its content
* @param {Node} tab The tab
* @param {Node} content The tab content
* @param {Object} settings User settings and options
*/
var setupTab = function (tab, content, settings) {
// Give tab an ID if it doesn't already have one
if (!tab.id) {
tab.id = settings.idPrefix + content.id;
}
// Add roles
tab.setAttribute('role', 'tab');
tab.setAttribute('aria-controls', content.id);
tab.closest('li').setAttribute('role', 'presentation');
content.setAttribute('role', 'tabpanel');
content.setAttribute('aria-labelledby', tab.id);
// Add selected state
if (tab.matches(settings.default)) {
tab.setAttribute('aria-selected', 'true');
} else {
tab.setAttribute('aria-selected', 'false');
tab.setAttribute('tabindex', '-1');
content.setAttribute('hidden', 'hidden');
}
};
/**
* Hide a tab and its content
* @param {Node} newTab The new tab that's replacing it
*/
var hide = function (newTab) {
// Variables
var tabGroup = newTab.closest('[role="tablist"]');
if (!tabGroup) return {};
var tab = tabGroup.querySelector('[role="tab"][aria-selected="true"]');
if (!tab) return {};
var content = document.querySelector(tab.hash);
// Hide the tab
tab.setAttribute('aria-selected', 'false');
tab.setAttribute('tabindex', '-1');
// Hide the content
if (!content) return {previousTab: tab};
content.setAttribute('hidden', 'hidden');
// Return the hidden tab and content
return {
previousTab: tab,
previousContent: content
};
};
/**
* Show a tab and its content
* @param {Node} tab The tab
* @param {Node} content The tab content
*/
var show = function (tab, content) {
tab.setAttribute('aria-selected', 'true');
tab.setAttribute('tabindex', '0');
content.removeAttribute('hidden');
tab.focus();
};
/**
* Toggle a new tab
* @param {Node} tab The tab to show
*/
var toggle = function (tab) {
// Make sure there's a tab to toggle and it's not already active
if (!tab || tab.getAttribute('aria-selected') == 'true') return;
// Variables
var content = document.querySelector(tab.hash);
if (!content) return;
// Hide active tab and content
var details = hide(tab);
// Show new tab and content
show(tab, content);
// Add event details
details.tab = tab;
details.content = content;
// Emit a custom event
emitEvent(tab, details);
};
/**
* Get all of the tabs in a tablist
* @param {Node} tab A tab from the list
* @return {Object} The tabs and the index of the currently active one
*/
var getTabsMap = function (tab) {
var tabGroup = tab.closest('[role="tablist"]');
var tabs = tabGroup ? tabGroup.querySelectorAll('[role="tab"]') : null;
if (!tabs) return;
return {
tabs: tabs,
index: Array.prototype.indexOf.call(tabs, tab)
};
};
/**
* Switch the active tab based on keyboard activity
* @param {Node} tab The currently active tab
* @param {Key} key The key that was pressed
*/
var switchTabs = function (tab, key) {
// Get a map of tabs
var map = getTabsMap(tab);
if (!map) return;
var length = map.tabs.length - 1;
var index;
// Go to previous tab
if (['ArrowUp', 'ArrowLeft', 'Up', 'Left'].indexOf(key) > -1) {
index = map.index < 1 ? length : map.index - 1;
}
// Go to next tab
else if (['ArrowDown', 'ArrowRight', 'Down', 'Right'].indexOf(key) > -1) {
index = map.index === length ? 0 : map.index + 1;
}
// Go to home
else if (key === 'Home') {
index = 0;
}
// Go to end
else if (key === 'End') {
index = length;
}
// Toggle the tab
toggle(map.tabs[index]);
};
/**
* Activate a tab based on the URL
* @param {String} selector The selector for this instantiation
*/
var loadFromURL = function (selector) {
if (window.location.hash.length < 1) return;
var tab = document.querySelector(selector + ' [role="tab"][href*="' + window.location.hash + '"]');
toggle(tab);
};
/**
* Create the Constructor object
*/
var Constructor = function (selector, options) {
//
// Variables
//
var publicAPIs = {};
var settings, tabWrapper;
//
// Methods
//
publicAPIs.destroy = function () {
// Get all tabs
var tabs = tabWrapper.querySelectorAll('a');
// Add roles to tabs
Array.prototype.forEach.call(tabs, (function (tab) {
// Get the tab content
var content = document.querySelector(tab.hash);
if (!content) return;
// Setup the tab
destroyTab(tab, content, settings);
}));
// Remove role from wrapper
tabWrapper.removeAttribute('role');
// Remove event listeners
document.documentElement.removeEventListener('click', clickHandler, true);
tabWrapper.removeEventListener('keydown', keyHandler, true);
// Reset variables
settings = null;
tabWrapper = null;
};
/**
* Setup the DOM with the proper attributes
*/
publicAPIs.setup = function () {
// Variables
tabWrapper = document.querySelector(selector);
if (!tabWrapper) return;
var tabs = tabWrapper.querySelectorAll('a');
// Add role to wrapper
tabWrapper.setAttribute('role', 'tablist');
// Add roles to tabs
Array.prototype.forEach.call(tabs, (function (tab) {
// Get the tab content
var content = document.querySelector(tab.hash);
if (!content) return;
// Setup the tab
setupTab(tab, content, settings);
}));
};
/**
* Toggle a tab based on an ID
* @param {String|Node} id The tab to toggle
*/
publicAPIs.toggle = function (id) {
// Get the tab
var tab = id;
if (typeof id === 'string') {
tab = document.querySelector(selector + ' [role="tab"][href*="' + id + '"]');
}
// Toggle the tab
toggle(tab);
};
/**
* Handle click events
*/
var clickHandler = function (event) {
// Only run on toggles
var tab = event.target.closest(selector + ' [role="tab"]');
if (!tab) return;
// Prevent link behavior
event.preventDefault();
// Toggle the tab
toggle(tab);
};
/**
* Handle keydown events
*/
var keyHandler = function (event) {
// Only run if a tab is in focus
var tab = document.activeElement;
if (!tab.matches(selector + ' [role="tab"]')) return;
// Only run for specific keys
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Up', 'Down', 'Left', 'Right', 'Home', 'End'].indexOf(event.key) < 0) return;
// Switch tabs
switchTabs(tab, event.key);
};
/**
* Initialize the instance
*/
var init = function () {
// Merge user options with defaults
settings = extend(defaults, options || {});
// Setup the DOM
publicAPIs.setup();
// Load a tab from the URL
loadFromURL(selector);
// Add event listeners
document.documentElement.addEventListener('click', clickHandler, true);
tabWrapper.addEventListener('keydown', keyHandler, true);
};
//
// Initialize and return the Public APIs
//
init();
return publicAPIs;
};
//
// Return the Constructor
//
return Constructor;
}));