forked from foundation/foundation-sites
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfoundation.offcanvas.js
602 lines (517 loc) · 18.4 KB
/
foundation.offcanvas.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
'use strict';
import $ from 'jquery';
import { Plugin } from './foundation.core.plugin';
import { onLoad, transitionend, RegExpEscape } from './foundation.core.utils';
import { Keyboard } from './foundation.util.keyboard';
import { MediaQuery } from './foundation.util.mediaQuery';
import { Triggers } from './foundation.util.triggers';
/**
* OffCanvas module.
* @module foundation.offCanvas
* @requires foundation.util.keyboard
* @requires foundation.util.mediaQuery
* @requires foundation.util.triggers
*/
class OffCanvas extends Plugin {
/**
* Creates a new instance of an off-canvas wrapper.
* @class
* @name OffCanvas
* @fires OffCanvas#init
* @param {Object} element - jQuery object to initialize.
* @param {Object} options - Overrides to the default plugin settings.
*/
_setup(element, options) {
this.className = 'OffCanvas'; // ie9 back compat
this.$element = element;
this.options = $.extend({}, OffCanvas.defaults, this.$element.data(), options);
this.contentClasses = { base: [], reveal: [] };
this.$lastTrigger = $();
this.$triggers = $();
this.position = 'left';
this.$content = $();
this.nested = !!(this.options.nested);
this.isInCanvas = false;
// Defines the CSS transition/position classes of the off-canvas content container.
$(['push', 'overlap']).each((index, val) => {
this.contentClasses.base.push('has-transition-'+val);
});
$(['left', 'right', 'top', 'bottom']).each((index, val) => {
this.contentClasses.base.push('has-position-'+val);
this.contentClasses.reveal.push('has-reveal-'+val);
});
// Triggers init is idempotent, just need to make sure it is initialized
Triggers.init($);
MediaQuery._init();
this._init();
this._events();
Keyboard.register('OffCanvas', {
'ESCAPE': 'close'
});
}
/**
* Initializes the off-canvas wrapper by adding the exit overlay (if needed).
* @function
* @private
*/
_init() {
var id = this.$element.attr('id');
this.$element.attr('aria-hidden', 'true');
// Find off-canvas content, either by ID (if specified), by siblings or by closest selector (fallback)
if (this.options.contentId) {
this.$content = $('#'+this.options.contentId);
} else if (this.$element.siblings('[data-off-canvas-content]').length) {
this.$content = this.$element.siblings('[data-off-canvas-content]').first();
} else {
this.$content = this.$element.closest('[data-off-canvas-content]').first();
}
if (!this.options.contentId) {
// Assume that the off-canvas element is nested if it isn't a sibling of the content
this.nested = this.$element.siblings('[data-off-canvas-content]').length === 0;
} else if (this.options.contentId && this.options.nested === null) {
// Warning if using content ID without setting the nested option
// Once the element is nested it is required to work properly in this case
console.warn('Remember to use the nested option if using the content ID option!');
}
if (this.nested === true) {
// Force transition overlap if nested
this.options.transition = 'overlap';
// Remove appropriate classes if already assigned in markup
this.$element.removeClass('is-transition-push');
}
this.$element.addClass(`is-transition-${this.options.transition} is-closed`);
// Find triggers that affect this element and add aria-expanded to them
this.$triggers = $(document)
.find('[data-open="'+id+'"], [data-close="'+id+'"], [data-toggle="'+id+'"]')
.attr('aria-expanded', 'false')
.attr('aria-controls', id);
// Get position by checking for related CSS class
this.position = this.$element.is('.position-left, .position-top, .position-right, .position-bottom') ? this.$element.attr('class').match(/position\-(left|top|right|bottom)/)[1] : this.position;
// Add an overlay over the content if necessary
if (this.options.contentOverlay === true) {
var overlay = document.createElement('div');
var overlayPosition = $(this.$element).css("position") === 'fixed' ? 'is-overlay-fixed' : 'is-overlay-absolute';
overlay.setAttribute('class', 'js-off-canvas-overlay ' + overlayPosition);
this.$overlay = $(overlay);
if(overlayPosition === 'is-overlay-fixed') {
$(this.$overlay).insertAfter(this.$element);
} else {
this.$content.append(this.$overlay);
}
}
// Get the revealOn option from the class.
var revealOnRegExp = new RegExp(RegExpEscape(this.options.revealClass) + '([^\\s]+)', 'g');
var revealOnClass = revealOnRegExp.exec(this.$element[0].className);
if (revealOnClass) {
this.options.isRevealed = true;
this.options.revealOn = this.options.revealOn || revealOnClass[1];
}
// Ensure the `reveal-on-*` class is set.
if (this.options.isRevealed === true && this.options.revealOn) {
this.$element.first().addClass(`${this.options.revealClass}${this.options.revealOn}`);
this._setMQChecker();
}
if (this.options.transitionTime) {
this.$element.css('transition-duration', this.options.transitionTime);
}
let inCanvasFor = this.$element.attr('class').match(/\bin-canvas-for-(\w+)/);
if (inCanvasFor && inCanvasFor.length === 2) {
// Set `inCanvasOn` option if found in-canvas-for-[BREAKPONT] CSS class
this.options.inCanvasOn = inCanvasFor[1];
} else if (this.options.inCanvasOn) {
// Ensure the CSS class is set
this.$element.addClass(`in-canvas-for-${this.options.inCanvasOn}`);
}
if (this.options.inCanvasOn) {
this._checkInCanvas();
}
// Initally remove all transition/position CSS classes from off-canvas content container.
this._removeContentClasses();
}
/**
* Adds event handlers to the off-canvas wrapper and the exit overlay.
* @function
* @private
*/
_events() {
this.$element.off('.zf.trigger .zf.offCanvas').on({
'open.zf.trigger': this.open.bind(this),
'close.zf.trigger': this.close.bind(this),
'toggle.zf.trigger': this.toggle.bind(this),
'keydown.zf.offCanvas': this._handleKeyboard.bind(this)
});
if (this.options.closeOnClick === true) {
var $target = this.options.contentOverlay ? this.$overlay : this.$content;
$target.on({'click.zf.offCanvas': this.close.bind(this)});
}
if (this.options.inCanvasOn) {
$(window).on('changed.zf.mediaquery', () => {
this._checkInCanvas();
});
}
}
/**
* Applies event listener for elements that will reveal at certain breakpoints.
* @private
*/
_setMQChecker() {
var _this = this;
this.onLoadListener = onLoad($(window), function () {
if (MediaQuery.atLeast(_this.options.revealOn)) {
_this.reveal(true);
}
});
$(window).on('changed.zf.mediaquery', function () {
if (MediaQuery.atLeast(_this.options.revealOn)) {
_this.reveal(true);
} else {
_this.reveal(false);
}
});
}
/**
* Checks if InCanvas on current breakpoint and adjust off-canvas accordingly
* @private
*/
_checkInCanvas() {
this.isInCanvas = MediaQuery.atLeast(this.options.inCanvasOn);
if (this.isInCanvas === true) {
this.close();
}
}
/**
* Removes the CSS transition/position classes of the off-canvas content container.
* Removing the classes is important when another off-canvas gets opened that uses the same content container.
* @param {Boolean} hasReveal - true if related off-canvas element is revealed.
* @private
*/
_removeContentClasses(hasReveal) {
if (typeof hasReveal !== 'boolean') {
this.$content.removeClass(this.contentClasses.base.join(' '));
} else if (hasReveal === false) {
this.$content.removeClass(`has-reveal-${this.position}`);
}
}
/**
* Adds the CSS transition/position classes of the off-canvas content container, based on the opening off-canvas element.
* Beforehand any transition/position class gets removed.
* @param {Boolean} hasReveal - true if related off-canvas element is revealed.
* @private
*/
_addContentClasses(hasReveal) {
this._removeContentClasses(hasReveal);
if (typeof hasReveal !== 'boolean') {
this.$content.addClass(`has-transition-${this.options.transition} has-position-${this.position}`);
} else if (hasReveal === true) {
this.$content.addClass(`has-reveal-${this.position}`);
}
}
/**
* Handles the revealing/hiding the off-canvas at breakpoints, not the same as open.
* @param {Boolean} isRevealed - true if element should be revealed.
* @function
*/
reveal(isRevealed) {
if (isRevealed) {
this.close();
this.isRevealed = true;
this.$element.attr('aria-hidden', 'false');
this.$element.off('open.zf.trigger toggle.zf.trigger');
this.$element.removeClass('is-closed');
} else {
this.isRevealed = false;
this.$element.attr('aria-hidden', 'true');
this.$element.off('open.zf.trigger toggle.zf.trigger').on({
'open.zf.trigger': this.open.bind(this),
'toggle.zf.trigger': this.toggle.bind(this)
});
this.$element.addClass('is-closed');
}
this._addContentClasses(isRevealed);
}
/**
* Stops scrolling of the body when OffCanvas is open on mobile Safari and other troublesome browsers.
* @private
*/
_stopScrolling(event) {
return false;
}
// Taken and adapted from http://stackoverflow.com/questions/16889447/prevent-full-page-scrolling-ios
// Only really works for y, not sure how to extend to x or if we need to.
_recordScrollable(event) {
let elem = this; // called from event handler context with this as elem
// If the element is scrollable (content overflows), then...
if (elem.scrollHeight !== elem.clientHeight) {
// If we're at the top, scroll down one pixel to allow scrolling up
if (elem.scrollTop === 0) {
elem.scrollTop = 1;
}
// If we're at the bottom, scroll up one pixel to allow scrolling down
if (elem.scrollTop === elem.scrollHeight - elem.clientHeight) {
elem.scrollTop = elem.scrollHeight - elem.clientHeight - 1;
}
}
elem.allowUp = elem.scrollTop > 0;
elem.allowDown = elem.scrollTop < (elem.scrollHeight - elem.clientHeight);
elem.lastY = event.originalEvent.pageY;
}
_stopScrollPropagation(event) {
let elem = this; // called from event handler context with this as elem
let up = event.pageY < elem.lastY;
let down = !up;
elem.lastY = event.pageY;
if((up && elem.allowUp) || (down && elem.allowDown)) {
event.stopPropagation();
} else {
event.preventDefault();
}
}
/**
* Opens the off-canvas menu.
* @function
* @param {Object} event - Event object passed from listener.
* @param {jQuery} trigger - element that triggered the off-canvas to open.
* @fires OffCanvas#opened
* @todo also trigger 'open' event?
*/
open(event, trigger) {
if (this.$element.hasClass('is-open') || this.isRevealed || this.isInCanvas) { return; }
var _this = this;
if (trigger) {
this.$lastTrigger = trigger;
}
if (this.options.forceTo === 'top') {
window.scrollTo(0, 0);
} else if (this.options.forceTo === 'bottom') {
window.scrollTo(0,document.body.scrollHeight);
}
if (this.options.transitionTime && this.options.transition !== 'overlap') {
this.$element.siblings('[data-off-canvas-content]').css('transition-duration', this.options.transitionTime);
} else {
this.$element.siblings('[data-off-canvas-content]').css('transition-duration', '');
}
this.$element.addClass('is-open').removeClass('is-closed');
this.$triggers.attr('aria-expanded', 'true');
this.$element.attr('aria-hidden', 'false');
this.$content.addClass('is-open-' + this.position);
// If `contentScroll` is set to false, add class and disable scrolling on touch devices.
if (this.options.contentScroll === false) {
$('body').addClass('is-off-canvas-open').on('touchmove', this._stopScrolling);
this.$element.on('touchstart', this._recordScrollable);
this.$element.on('touchmove', this._stopScrollPropagation);
}
if (this.options.contentOverlay === true) {
this.$overlay.addClass('is-visible');
}
if (this.options.closeOnClick === true && this.options.contentOverlay === true) {
this.$overlay.addClass('is-closable');
}
if (this.options.autoFocus === true) {
this.$element.one(transitionend(this.$element), function() {
if (!_this.$element.hasClass('is-open')) {
return; // exit if prematurely closed
}
var canvasFocus = _this.$element.find('[data-autofocus]');
if (canvasFocus.length) {
canvasFocus.eq(0).focus();
} else {
_this.$element.find('a, button').eq(0).focus();
}
});
}
if (this.options.trapFocus === true) {
this.$content.attr('tabindex', '-1');
Keyboard.trapFocus(this.$element);
}
this._addContentClasses();
/**
* Fires when the off-canvas menu opens.
* @event OffCanvas#opened
*/
this.$element.trigger('opened.zf.offCanvas');
}
/**
* Closes the off-canvas menu.
* @function
* @param {Function} cb - optional cb to fire after closure.
* @fires OffCanvas#closed
*/
close(cb) {
if (!this.$element.hasClass('is-open') || this.isRevealed) { return; }
var _this = this;
this.$element.removeClass('is-open');
this.$element.attr('aria-hidden', 'true')
/**
* Fires when the off-canvas menu opens.
* @event OffCanvas#closed
*/
.trigger('closed.zf.offCanvas');
this.$content.removeClass('is-open-left is-open-top is-open-right is-open-bottom');
// If `contentScroll` is set to false, remove class and re-enable scrolling on touch devices.
if (this.options.contentScroll === false) {
$('body').removeClass('is-off-canvas-open').off('touchmove', this._stopScrolling);
this.$element.off('touchstart', this._recordScrollable);
this.$element.off('touchmove', this._stopScrollPropagation);
}
if (this.options.contentOverlay === true) {
this.$overlay.removeClass('is-visible');
}
if (this.options.closeOnClick === true && this.options.contentOverlay === true) {
this.$overlay.removeClass('is-closable');
}
this.$triggers.attr('aria-expanded', 'false');
if (this.options.trapFocus === true) {
this.$content.removeAttr('tabindex');
Keyboard.releaseFocus(this.$element);
}
// Listen to transitionEnd and add class when done.
this.$element.one(transitionend(this.$element), function(e) {
_this.$element.addClass('is-closed');
_this._removeContentClasses();
});
}
/**
* Toggles the off-canvas menu open or closed.
* @function
* @param {Object} event - Event object passed from listener.
* @param {jQuery} trigger - element that triggered the off-canvas to open.
*/
toggle(event, trigger) {
if (this.$element.hasClass('is-open')) {
this.close(event, trigger);
}
else {
this.open(event, trigger);
}
}
/**
* Handles keyboard input when detected. When the escape key is pressed, the off-canvas menu closes, and focus is restored to the element that opened the menu.
* @function
* @private
*/
_handleKeyboard(e) {
Keyboard.handleKey(e, 'OffCanvas', {
close: () => {
this.close();
this.$lastTrigger.focus();
return true;
},
handled: () => {
e.stopPropagation();
e.preventDefault();
}
});
}
/**
* Destroys the OffCanvas plugin.
* @function
*/
_destroy() {
this.close();
this.$element.off('.zf.trigger .zf.offCanvas');
this.$overlay.off('.zf.offCanvas');
if (this.onLoadListener) $(window).off(this.onLoadListener);
}
}
OffCanvas.defaults = {
/**
* Allow the user to click outside of the menu to close it.
* @option
* @type {boolean}
* @default true
*/
closeOnClick: true,
/**
* Adds an overlay on top of `[data-off-canvas-content]`.
* @option
* @type {boolean}
* @default true
*/
contentOverlay: true,
/**
* Target an off-canvas content container by ID that may be placed anywhere. If null the closest content container will be taken.
* @option
* @type {?string}
* @default null
*/
contentId: null,
/**
* Define the off-canvas element is nested in an off-canvas content. This is required when using the contentId option for a nested element.
* @option
* @type {boolean}
* @default null
*/
nested: null,
/**
* Enable/disable scrolling of the main content when an off canvas panel is open.
* @option
* @type {boolean}
* @default true
*/
contentScroll: true,
/**
* Amount of time in ms the open and close transition requires. If none selected, pulls from body style.
* @option
* @type {number}
* @default null
*/
transitionTime: null,
/**
* Type of transition for the OffCanvas menu. Options are 'push', 'detached' or 'slide'.
* @option
* @type {string}
* @default push
*/
transition: 'push',
/**
* Force the page to scroll to top or bottom on open.
* @option
* @type {?string}
* @default null
*/
forceTo: null,
/**
* Allow the OffCanvas to remain open for certain breakpoints.
* @option
* @type {boolean}
* @default false
*/
isRevealed: false,
/**
* Breakpoint at which to reveal. JS will use a RegExp to target standard classes, if changing classnames, pass your class with the `revealClass` option.
* @option
* @type {?string}
* @default null
*/
revealOn: null,
/**
* Breakpoint at which the off-canvas gets moved into canvas content and acts as regular page element.
* @option
* @type {?string}
* @default null
*/
inCanvasOn: null,
/**
* Force focus to the offcanvas on open. If true, will focus the opening trigger on close.
* @option
* @type {boolean}
* @default true
*/
autoFocus: true,
/**
* Class used to force an OffCanvas to remain open. Foundation defaults for this are `reveal-for-large` & `reveal-for-medium`.
* @option
* @type {string}
* @default reveal-for-
* @todo improve the regex testing for this.
*/
revealClass: 'reveal-for-',
/**
* Triggers optional focus trapping when opening an OffCanvas. Sets tabindex of [data-off-canvas-content] to -1 for accessibility purposes.
* @option
* @type {boolean}
* @default false
*/
trapFocus: false
}
export {OffCanvas};