-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhoudini.js
684 lines (552 loc) · 17 KB
/
houdini.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
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
/*!
* houdinijs v11.0.4
* A simple collapse-and-expand script
* (c) 2019 Chris Ferdinandi
* MIT License
* http://github.com/cferdinandi/houdini
*/
(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.Houdini = factory(root);
}
})(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) {
'use strict';
//
// Variables
//
var defaults = {
// Content
contentClass: 'houdini',
expanded: false,
expandedClass: 'is-expanded',
visibleClass: 'is-visible',
// Toggle Buttons
btnAfter: false,
btnClass: 'houdini-toggle',
btnAttribute: 'data-houdini-toggle',
btnTextAttribute: 'data-houdini-button',
btnLabelAttribute: 'data-houdini-label',
btnPreexisting: 'data-houdini-button-preexisting',
// Accordion
isAccordion: false,
collapseOthers: false,
headingClass: 'houdini-heading',
// Icons
icon: -1,
iconClass: 'houdini-toggle-icon',
iconAttribute: 'data-houdini-icon',
iconShow: '+',
iconHide: '–',
// Custom Events
emitEvents: true
};
//
// 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 {Object} settings The settings object
* @param {Node} content The content element
* @param {Node} btn The toggle button element
*/
var emitEvent = function (type, settings, details) {
if (!settings.emitEvents || typeof window.CustomEvent !== 'function') return;
var event = new CustomEvent(type, {
bubbles: true,
detail: details
});
if (details.content) {
details.content.dispatchEvent(event);
} else {
document.dispatchEvent(event);
}
};
/**
* Add button to accordion headings
* @param {Node} elem The accordion content
* @param {Object} settings The settings object
*/
var wrapInBtn = function (elem, settings) {
// Variables
var heading = document.querySelector('[' + settings.btnAttribute + '="' + elem.id + '"]');
if (!heading) return;
var isExpanded = elem.classList.contains(settings.expandedClass);
// Update heading attributes
heading.classList.add(settings.headingClass);
heading.removeAttribute(settings.btnAttribute);
// Create the icon
var icon = '';
if (settings.icon) {
icon =
'<span' +
' class="' + settings.iconClass + '"' +
' ' + settings.iconAttribute +
'>' +
(isExpanded ? settings.iconHide : settings.iconShow) +
'</span>';
}
// Wrap heading in a button
heading.innerHTML =
'<button' +
' class="' + settings.btnClass + '"' +
' ' + settings.btnAttribute + '="' + elem.id + '"' +
' aria-expanded="' + (isExpanded ? true : false) + '"' +
'>' +
heading.innerHTML +
icon +
'</button>';
return heading;
};
/**
* Get a preexisting button for the content
* @param {Node} elem The disclosure content
* @param {Object} settings The settings object
* @return {Node} The preexisting button
*/
var getExistingBtn = function (elem, settings) {
var btn = document.querySelector('[' + settings.btnAttribute + '="' + elem.id + '"]');
if (!btn) return;
btn.removeAttribute('hidden');
if (btn.tagName.toLowerCase() === 'a') {
btn.setAttribute('role', 'button');
}
btn.setAttribute(settings.btnPreexisting, 'true');
return btn;
};
/**
* Add a new toggle button to the DOM
* @param {Node} elem The disclosure content
* @param {Object} settings The settings object
*/
var addNewBtn = function (elem, settings) {
// Variables
var text = elem.getAttribute(settings.btnTextAttribute);
var isExpanded = elem.classList.contains(settings.expandedClass);
var label = elem.getAttribute(settings.btnLabelAttribute);
// Create the button
var existingBtn = getExistingBtn(elem, settings);
var btn = existingBtn ? existingBtn : document.createElement('button');
// Add button text
if (!existingBtn) {
// btn.textContent = text && text.length > 0 ? text : settings.btnText; // @todo
if (!text || text.length < 1) return;
btn.textContent = text;
}
// Add selectors and labels
btn.setAttribute(settings.btnAttribute, elem.id);
btn.className += ' ' + settings.btnClass;
// Add an icon
var icon = '';
if (settings.icon) {
btn.innerHTML +=
'<span' +
' class="' + settings.iconClass + '"' +
' ' + settings.iconAttribute +
'>' +
(isExpanded ? settings.iconHide : settings.iconShow) +
'</span>';
}
// Add a11y attributes
btn.setAttribute('aria-expanded', isExpanded);
if (label) {
btn.setAttribute('aria-label', label);
}
// Inject into the DOM
if (!existingBtn) {
elem.parentNode.insertBefore(btn, settings.btnAfter ? elem.nextSibling : elem);
}
return btn;
};
/**
* Create the disclosure button
* @param {Node} elem The disclosure content
* @param {Object} settings The settings object
*/
var createBtn = function (elem, settings) {
if (settings.isAccordion) {
return wrapInBtn(elem, settings);
}
return addNewBtn(elem, settings);
};
/**
* Remove button from accordion headings
* @param {Node} elem The accordion content
* @param {Object} settings The settings object
*/
var unwrapInBtn = function (elem, settings) {
// Variables
var btn = document.querySelector('[' + settings.btnAttribute + '="' + elem.id + '"]');
if (!btn) return;
// Update heading attributes
btn.parentNode.classList.remove(settings.headingClass);
btn.parentNode.setAttribute(settings.btnAttribute, elem.id);
// Unwrap heading in a button
var heading = btn.cloneNode(true);
var icon = heading.querySelector('[' + settings.iconAttribute + ']');
if (icon) {
heading.removeChild(icon);
}
btn.parentNode.innerHTML = heading.innerHTML;
};
/**
* Remove toggle button from the DOM
* @param {Node} elem The disclosure content
* @param {Object} settings The settings object
*/
var removeNewBtn = function (elem, settings) {
var btn = document.querySelector('[' + settings.btnAttribute + '="' + elem.id + '"]');
if (!btn) return;
if (btn.hasAttribute(settings.btnPreexisting)) {
btn.setAttribute('hidden', 'hidden');
return;
}
btn.parentNode.removeChild(btn);
};
/**
* Remove button elements
* @param {Node} elem The disclosure content
* @param {Object} settings The settings object
*/
var removeBtn = function (elem, settings) {
if (settings.isAccordion) {
unwrapInBtn(elem, settings);
} else {
removeNewBtn(elem, settings);
}
};
/**
* Collapse a toggle button
* @param {Node} btn The button
* @param {Object} settings The settings object
*/
var collapseBtn = function (btn, settings) {
// Update a11y attributes
btn.setAttribute('aria-expanded', 'false');
btn.removeAttribute('aria-controls');
// Toggle icons
var icon = btn.querySelector('[' + settings.iconAttribute + ']');
if (icon) {
icon.innerHTML = settings.iconShow;
}
};
/**
* Collapse disclosure content
* @param {Node} btn The toggle button
* @param {Node} target The disclosure content
* @param {Object} settings The settings object
*/
var collapseContent = function (btn, target, settings) {
// Update button text
collapseBtn(btn, settings);
// Collapse content
// target.classList.remove(settings.expandedClass);
var elem = target;
// Give the element a height to change from
elem.style.height = elem.scrollHeight + 'px';
// Set the height back to 0
window.setTimeout(function () {
elem.style.height = '0';
}, 1);
// Set the opacity back to 0
elem.classList.remove(settings.visibleClass);
// When the transition is complete, hide it
window.setTimeout(function () {
elem.classList.remove(settings.expandedClass);
}, 150);
// Emit event
emitEvent('houdiniCollapse', settings, {
button: btn,
content: target
});
};
/**
* Collapse open accordion content in a group
* @param {Node} btn The toggle button
* @param {Node} target The disclosure content
* @param {String} selector The selector for this instantiation
* @param {Object} settings The settings object
*/
var collapseOthers = function (btn, target, selector, settings) {
// Only run for accordions where others should be collapsed
if (!settings.isAccordion || !settings.collapseOthers) return;
// Close open content areas
Array.prototype.forEach.call(document.querySelectorAll(selector + '.' + settings.expandedClass), (function (content) {
var btn = document.querySelector('[' + settings.btnAttribute + '="' + content.id + '"]');
collapseContent(btn, content, settings);
}));
};
/**
* Expand a toggle button
* @param {Node} btn The button
* @param {Object} settings The settings object
*/
var expandBtn = function (btn, target, settings) {
// Update a11y attributes
btn.setAttribute('aria-expanded', true);
btn.setAttribute('aria-controls', target.id);
// Toggle icons
var icon = btn.querySelector('[' + settings.iconAttribute + ']');
if (icon) {
icon.innerHTML = settings.iconHide;
}
};
/**
* Expand disclosure content
* @param {Node} btn The button
* @param {Node} target The disclosure content
* @param {Object} settings The settings object
*/
var expandContent = function (btn, target, settings) {
// Update button text
expandBtn(btn, target, settings);
// Expand content
// target.classList.add(settings.expandedClass);
var elem = target;
// Get the natural height of the element
var getHeight = function () {
elem.style.display = 'block'; // Make it visible
var height = elem.scrollHeight + 'px'; // Get it's height
elem.style.display = ''; // Hide it again
return height;
};
var height = getHeight(); // Get the natural height
elem.classList.add(settings.expandedClass); // Make the element active
elem.style.height = height; // Update the max-height
// Once the transition is complete, remove the inline max-height so the content can scale responsively
window.setTimeout(function () {
elem.style.height = '';
elem.classList.add(settings.visibleClass); // Make the element visible
}, 150);
// Update focus
if (settings.btnAfter && !settings.isAccordion) {
target.focus();
}
// Emit event
emitEvent('houdiniExpand', settings, {
button: btn,
content: target
});
};
/**
* Toggle disclosure content visibility
* @param {Node} btn The button
* @param {Node} target The disclosure content
* @param {String} selector The selector for this instantiation
* @param {Object} settings The settings object
* @return {[type]} [description]
*/
var toggleContent = function (btn, selector, settings, event) {
// Variables
var isExpanded = btn.getAttribute('aria-expanded');
var target = document.querySelector('#' + btn.getAttribute(settings.btnAttribute));
if (!target || !target.matches(selector)) return;
// Prevent default click event
// For links or buttons inside a form
if (event) {
event.preventDefault();
}
// Toggle content visibility
// Must explicitly specify true here and use type coercion because value returned is a string
if (isExpanded == 'true') {
collapseContent(btn, target, settings);
} else {
collapseOthers(btn, target, selector, settings);
expandContent(btn, target, settings);
}
};
/**
* Get the content element from the DOM
* @param {String|Node} target The selector
* @param {String} att The data attribute for toggle buttons
* @return {Node} The content element
*/
var getContent = function (target, att) {
var content = target;
// If selector string instead of element
if (typeof target === 'string') {
content = document.querySelector(target);
}
// If button instead of content
if (content && content.matches('[' + att + ']')) {
content = document.querySelector('#' + content.getAttribute(att));
}
return content;
};
/**
* Get the button element from the DOM
* @param {String|Node} target The element or selector string
* @param {String} selector The selector for this instantiation
* @return {Node} The button element
*/
var getBtn = function (target, selector, settings) {
var btn = target;
// If selector string instead of element
if (typeof target === 'string') {
btn = document.querySelector(target);
}
// If content area instead of button
if (btn && btn.matches(selector)) {
btn = document.querySelector('[' + settings.btnAttribute + '="' + btn.id + '"]');
}
return btn;
};
/**
* Restore the DOM to its original state
* @param {String} selector The selector for this instantiation
* @param {Object} settings The settings object
*/
var teardown = function (selector, settings) {
Array.prototype.forEach.call(document.querySelectorAll(selector), (function (content) {
// Remove the toggle button
removeBtn(content, settings);
// Add the content class
content.classList.remove(settings.contentClass);
content.style.height = '';
// Restore default expanded state
if (settings.expandedOnInit.indexOf(content.id) < 0) {
content.classList.remove(settings.expandedClass);
content.classList.remove(settings.visibleClass);
} else {
content.classList.add(settings.expandedClass);
content.classList.add(settings.visibleClass);
}
}));
};
//
// Constructor
//
var Constructor = function (selector, options) {
//
// Variables
//
var publicAPIs = {};
var settings;
//
// Methods
//
/**
* Toggle a disclosure
* @param {String|Node} target The content or button to toggle
*/
publicAPIs.toggle = function (target) {
toggleContent(getBtn(target, selector, settings), selector, settings);
};
/**
* Expand a disclosure
* @param {String|Node} target The content or button to toggle
*/
publicAPIs.expand = function (target) {
expandContent(getBtn(target, selector, settings), getContent(target, settings.btnAttribute), settings);
};
/**
* Collapse a disclosure
* @param {String|Node} target The content or button to toggle
*/
publicAPIs.collapse = function (target) {
var btn = getBtn(target, selector, settings);
var content = getContent(target, settings.btnAttribute);
collapseOthers(btn, content, selector, settings);
collapseContent(btn, content, settings);
};
/**
* Add required markup to the DOM
*/
publicAPIs.setup = function () {
// Add markup
Array.prototype.forEach.call(document.querySelectorAll(selector), (function (content) {
// If already setup, bail
if (content.classList.contains(settings.contentClass)) return;
// Create the toggle button
if (!createBtn(content, settings)) return;
// Add the content class
content.classList.add(settings.contentClass);
// Cache items that are expanded by default
if (content.classList.contains(settings.expandedClass)) {
settings.expandedOnInit.push(content.id);
}
// If the button appears after the content, give it a tabindex so it can be focused
if (settings.btnAfter && !content.getAttribute('tabindex')) {
content.setAttribute('tabindex', -1);
}
// If item should be expanded by default, expand it
if (settings.expanded) {
content.classList.add(settings.expandedClass);
}
}));
// Emit event
emitEvent('houdiniSetup', settings, {
settings: settings
});
};
/**
* Handle click events
*/
var clickHandler = function (event) {
// Only run if clicked element matches our selector
var toggle = event.target.closest('[' + settings.btnAttribute + ']');
if (!toggle) return;
// Show/hide content
toggleContent(toggle, selector, settings, event);
};
/**
* Destroy the current instatiation
*/
publicAPIs.destroy = function () {
document.removeEventListener('click', clickHandler, false);
teardown(selector, settings);
emitEvent('houdiniDestroy', settings, {
settings: settings
});
settings = null;
};
/**
* Initialize the plugin
*/
var init = function () {
// Merge user options into defaults
settings = extend(defaults, options || {});
settings.expandedOnInit = [];
if (settings.icon < 0) {
settings.icon = settings.isAccordion;
}
// Setup the DOM
publicAPIs.setup();
// Add event listener
document.addEventListener('click', clickHandler, false);
// Emit event
emitEvent('houdiniInitialize', settings, {
settings: settings
});
};
// Initialize the plugin
init(options);
// Return the public APIs
return publicAPIs;
};
//
// Return the constructor
//
return Constructor;
}));