-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUiModalComponent.js
More file actions
640 lines (556 loc) · 21.2 KB
/
UiModalComponent.js
File metadata and controls
640 lines (556 loc) · 21.2 KB
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
/**
* Requires
*/
import { UiComponent } from '@squirrel-forge/ui-core';
import {
EventDispatcher,
Exception,
afterPaint,
bindNodeList,
getFocusable,
tabFocusLock,
trimChar
} from '@squirrel-forge/ui-util';
/**
* Ui modal component exception
* @class
* @extends Exception
*/
class UiModalComponentException extends Exception {}
/**
* Ui modal shown callback
* @callback UiModalCallbackShow
* @param {Function} complete - Function to call when animation is completed
* @param {Object|UiModalComponent} - Modal component instance
* @return {void}
*/
/**
* Ui modal hidden callback
* @callback UiModalCallbackHide
* @param {Function} complete - Function to call when animation is completed
* @param {Object|UiModalComponent} - Modal component instance
* @return {void}
*/
/**
* Ui modal id getter function
* @typedef {Function} modalIdGetter
* @param {HTMLElement} opener - Trigger element
* @param {Function} defaultIdGetter - Default id getter function
* @return {string|null} - Modal id
*/
/**
* Ui modal settings
* @typedef {Object} UiModalSettings
* @property {documentElement|HTMLElement} context - Context element, default: document.documentElement
* @property {string} openInContextClass - Class set on context when modal is open, default: 'ui-modal-context--active'
* @property {('modal'|'alert'|'confirm'|'prompt')} mode - Interaction mode, might require a corresponding plugin, should be set via the UiModalComponent.mode = <string>, default 'modal'
* @property {Array<mode>} availableModes - Available modes, default: [ 'modal' ]
* @property {string} modeClass - Mode class prefix, default: 'ui-modal--'
* @property {boolean} restrictFocus - Restrict tab focus to modal content, default: true
* @property {boolean|Array<mode>} focusOnShown - Focus first contained element when shown, default: true
* @property {boolean|Array<mode>} focusLast - Focus last contained element when shown, focusOnShown must be active, default: false
* @property {boolean} focusResetOnHidden - Reset focus to the element that was focused before opening the modal, default: true
* @property {boolean|Array<mode>} easyHide - Hide on click outside dialog or keyboard escape key, default: true
* @property {UiModalAnimators} animator - Custom animators
* @property {UiModalDomReferences} dom - Dom references
*/
/**
* Ui modal custom animators
* @typedef {Object} UiModalAnimators
* @property {null|UiModalCallbackShow} show - Show modal animator
* @property {null|UiModalCallbackHide} hide - Hide modal animator
* @property {number} speed - Animation speed in ms, default: 300
*/
/**
* Ui modal dom references
* @typedef {Object} UiModalDomReferences
* @property {string} native - Native dialog reference, default: 'dialog'
* @property {string} dialog - Dialog, default: '.ui-modal__dialog'
* @property {null|string} focusable - Focusable elements, uses the tabFocusLock default selector if not set, default: null
* @property {string} title - Modal title, default: '.ui-modal__dialog-title'
* @property {string} content - Modal content, default: '.ui-modal__dialog-content'
* @property {string} close - Close buttons, default: '[data-modal="ctrl:close"]'
*/
/**
* Ui modal component states
* @typedef {Object} UiModalStates
* @property {ComponentStateDefinition} initialized - Initialized state
* @property {ComponentStateDefinition} closed - Modal closed state
* @property {ComponentStateDefinition} open - Modal open state
* @property {ComponentStateDefinition} animating - Modal transition/animating state
*/
/**
* Ui modal available plugins
* @typedef {Array<(UiModalPluginAlert|UiModalPluginConfirm|UiModalPluginPrompt)>} UiModalPlugins
*/
/**
* Ui modal component
* @class
* @extends UiComponent
*/
export class UiModalComponent extends UiComponent {
/**
* Last focus origin
* @private
* @property
* @type {null|HTMLElement}
*/
#origin = null;
/**
* Bind modal opener links
* @param {Array<UiModalComponent>} modals - List of modals
* @param {document|HTMLElement} context - Selection context
* @param {string} selector - Opener trigger selector
* @param {modalIdGetter|Function|null} getModalId - Modal id getter function
* @return {void}
*/
static bindOpeners(
modals,
context = document,
selector = '[data-modal="ctrl:open"]',
getModalId = null
) {
// Modals must always be an array
if ( !( modals instanceof Array ) ) {
throw new UiModalComponentException( 'Argument modals must be an Array of UiModalComponent instances' );
}
// Context must allow us to select elements
if ( typeof context.querySelectorAll !== 'function' ) {
throw new UiModalComponentException( 'Argument context must supply a querySelectorAll method' );
}
// Element selected from context must always be a list
const openers = context.querySelectorAll( selector );
if ( !( openers instanceof NodeList || openers instanceof Array ) ) {
throw new UiModalComponentException( 'Argument context.querySelectorAll must return a NodeList or Array' );
}
/**
* Default modal id getter
* @param {HTMLElement} opener - Modal trigger
* @return {string|null} - Modal id
*/
const defaultIdGetter = ( opener ) => {
const attributes = [ 'data-modal-id', 'aria-controls', 'href', 'value' ];
for ( let i = 0; i < attributes.length; i++ ) {
if ( opener.hasAttribute( attributes[ i ] ) ) {
const attr_value = opener.getAttribute( attributes[ i ] );
if ( attr_value ) return trimChar( attr_value, '#' );
}
}
return null;
};
// If there is no custom id getter use the default
if ( typeof getModalId !== 'function' ) getModalId = defaultIdGetter;
// Bind all openers
for ( let i = 0; i < openers.length; i++ ) {
const opener = openers[ i ];
opener.addEventListener( 'click', ( event ) => {
event.preventDefault();
const modal_id = getModalId( opener, defaultIdGetter );
if ( typeof modal_id !== 'string' || !modal_id.length ) {
throw new UiModalComponentException( 'Failed to get target modal id on opener' );
}
for ( let j = 0; j < modals.length; j++ ) {
if ( modals[ j ].dom.id === modal_id ) {
modals[ j ].open = true;
return;
}
}
throw new UiModalComponentException( 'Modal opener could not find the target modal for: ' + modal_id );
} );
}
}
/**
* Element selector getter
* @public
* @return {string} - Element selector
*/
static get selector() {
return '[is="ui-modal"]:not([data-state])';
}
/**
* Constructor
* @constructor
* @param {HTMLElement|HTMLElement} element - Block element
* @param {null|UiModalSettings|Object} settings - Config object
* @param {Object} defaults - Default config
* @param {Array<UiModalSettings|Object>} extend - Extend default config
* @param {UiModalStates|Object} states - States definition
* @param {UiModalPlugins|Array<Function|Array<Function,*>>} plugins - Plugins to load
* @param {null|UiComponent} parent - Parent object
* @param {null|console|Object} debug - Debug object
* @param {boolean} init - Run init method
*/
constructor(
element,
settings = null,
defaults = null,
extend = null,
states = null,
plugins = null,
parent = null,
debug = null,
init = true
) {
/**
* Default config
* @type {UiModalSettings}
*/
defaults = defaults || {
// Event prefix
eventPrefix : 'modal.',
// Context element
// @type {documentElement|HTMLElement}
context : document.documentElement,
// Class set on context when modal is open
// @type {string}
openInContextClass : 'ui-modal-context--active',
// Interaction mode, should be set via the UiModalComponent.mode = <string>
// @type {('modal')}
mode : 'modal',
// Available modes
// @type {Array<mode>}
availableModes : [ 'modal' ],
// Mode class prefix
// @type {string}
modeClass : 'ui-modal--',
// Restrict tab focus to modal content
// @type {boolean}
restrictFocus : true,
// Focus first contained element when shown
// @type {boolean|Array<config.mode>}
focusOnShown : true,
// Focus last contained element when shown, focusOnShown must be active
// @type {boolean|Array<config.mode>}
focusLast : false,
// Reset focus to the element that was focused before opening the modal
// @type {boolean}
focusResetOnHidden : true,
// Hide on click outside dialog or keyboard escape key
// @type {boolean|Array<config.mode>}
easyHide : true,
// Custom animators
// @type {Object}
animator : {
// Show modal animator
// @type {null|UiModalCallbackShow}
show : null,
// Hide modal animator
// @type {null|UiModalCallbackHide}
hide : null,
// Animation speed, default: 300ms
// @type {number}
speed : null,
// Control visibility, default: true
// @type {boolean}
vis : true,
},
// Dom references
// @type {Object}
dom : {
// Native dialog reference
// @type {string}
native : 'dialog',
// Dialog
// @type {string}
dialog : '.ui-modal__dialog',
// Focusable elements, uses the tabFocusLock default selector if not set
// @type {null|string}
focusable : null,
// Modal title
// @type {string}
title : '.ui-modal__dialog-title',
// Modal title
// @type {string}
content : '.ui-modal__dialog-content',
// Close buttons
// @type {string}
close : '[data-modal="ctrl:close"]',
}
};
/**
* Default states
* @type {Object}
*/
states = states || {
initialized : { classOn : 'ui-modal--initialized' },
closed : { classOn : 'ui-modal--closed', unsets : [ 'open' ] },
open : { classOn : 'ui-modal--open', unsets : [ 'closed' ] },
animating : { global : false, classOn : 'ui-modal--animating' },
};
// Initialize parent
super( element, settings, defaults, extend, states, plugins, parent, debug, init );
}
/**
* Initialize component
* @public
* @return {void}
*/
init() {
// Check context compatibility
if ( !EventDispatcher.isCompat( this.config.get( 'context' ) ) ) {
throw new UiModalComponentException( 'Option context must be an EventTarget compatible object' );
}
// Default aria properties
const native = this.getDomRefs( 'native', false );
if ( !native ) {
this.dom.setAttribute( 'role', 'dialog' );
this.dom.setAttribute( 'aria-modal', 'true' );
}
// Initialize tab focus locking
tabFocusLock( this.dom, () => { return this.open && this.config.get( 'restrictFocus' ); }, true, this.config.get( 'dom.focusable' ) );
// Bind events
this.bind();
// Initial hidden state
if ( this.config.get( 'animator.vis' ) ) this.dom.style.display = 'none';
if ( native ) native.removeAttribute( 'open' );
( native || this.dom ).setAttribute( 'aria-hidden', 'true' );
this.states.set( 'closed' );
const context_class = this.config.get( 'openInContextClass' );
if ( context_class ) this.config.get( 'context' ).classList.remove( context_class );
// Complete init and set mode class and attribute
super.init( () => {
this.dom.classList.add( this.config.get( 'modeClass' ) + this.mode );
this.dom.setAttribute( 'data-mode', this.mode );
} );
}
/**
* Bind component related events
* @public
* @return {void}
*/
bind() {
// Component events
this.addEventList( [
[ 'click', () => { if ( this._modeOptionActive( 'easyHide' ) ) this.hide(); } ],
[ 'modal.shown', () => { this.#focus_on_shown(); } ],
] );
this.dialog.addEventListener( 'click', ( event ) => {
if ( this._modeOptionActive( 'easyHide' ) ) event.stopPropagation();
} );
// Allow for close by escape key if enabled
document.addEventListener( 'keyup', ( event ) => {
if ( ( event.keyCode === 27 || event.key === 'Escape' ) && this.open ) {
if ( this._modeOptionActive( 'easyHide' ) ) this.hide();
}
} );
// Close buttons
bindNodeList( this.getDomRefs( 'close' ), [
[ 'click', ( event ) => {
event.preventDefault();
this.hide();
} ]
] );
}
/**
* Check if given config mode is true or true by mode
* @protected
* @param {string} name - Config option name
* @return {boolean} - Option enabled
*/
_modeOptionActive( name ) {
const option = this.config.get( name );
if ( option === true ) return true;
if ( option instanceof Array ) {
if ( option.includes( '!' + this.mode ) ) return false;
if ( option.includes( this.mode ) ) return true;
if ( option.includes( 'all!' ) ) return true;
}
return false;
}
/**
* Focus first available element after modal.shown event
* @private
* @return {void}
*/
#focus_on_shown() {
if ( this._modeOptionActive( 'focusOnShown' ) ) {
const element = getFocusable( this.dom, this._modeOptionActive( 'focusLast' ), this.config.get( 'dom.focusable' ) );
if ( element ) element.focus();
}
}
/**
* Mode getter
* @public
* @return {string} - Mode name
*/
get mode() {
return this.config.get( 'mode' );
}
/**
* Mode setter
* @public
* @param {string} name - Mode name
* @return {void}
*/
set mode( name ) {
const modes = this.config.get( 'availableModes' );
if ( !name || !modes.includes( name ) ) {
throw new UiModalComponentException( 'Unknown mode "' + mode + '"' );
}
if ( this.mode !== name ) {
this.dom.classList.remove( this.config.get( 'modeClass' ) + this.mode );
this.config.set( 'mode', name );
this.dom.classList.add( this.config.get( 'modeClass' ) + name );
this.dom.setAttribute( 'data-mode', name );
}
}
/**
* Open state getter
* @public
* @return {boolean} - True if open
*/
get open() {
return this.states.global === 'open';
}
/**
* Open state setter
* @public
* @param {boolean} state - State
* @return {void}
*/
set open( state ) {
if ( typeof state !== 'boolean' ) {
throw new UiModalComponentException( this.constructor.name + '.open must be of type boolean' );
}
if ( this.open !== state ) {
if ( this.open ) {
this.hide();
} else {
this.show();
}
}
}
/**
* Animating state getter
* @public
* @return {boolean} - True if animating
*/
get animating() {
return this.states.is( 'animating' );
}
/**
* Dialog element getter
* @public
* @return {HTMLElement} - Dialog element
*/
get dialog() {
return this.getDomRefs( 'dialog', false );
}
/**
* Title element getter
* @public
* @return {HTMLElement} - Title element
*/
get title() {
return this.getDomRefs( 'title', false );
}
/**
* Content element getter
* @public
* @return {HTMLElement} - Content element
*/
get content() {
return this.getDomRefs( 'content', false );
}
/**
* Bind show/hide transition complete/fallback
* @private
* @param {Function} complete - Complete handler
* @return {void}
*/
#bind_transition_complete( complete ) {
let speed = this.config.get( 'animator.speed' );
speed = typeof speed === 'number' ? speed : 300;
// Has transitionend event
const hasTransitions = typeof this.dom.style.transition !== 'undefined';
// Complete event via transition event
if ( hasTransitions && speed ) {
this.dom.addEventListener( 'transitionend', complete, { once : true } );
}
// Complete event via timeout
if ( !hasTransitions || !speed ) {
window.setTimeout( complete, speed + 1 );
}
}
/**
* Show modal
* @param {null|HTMLElement} origin - Last focused element before opening
* @param {boolean} events - Fire events
* @return {void}
*/
show( origin = null, events = true ) {
if ( !this.open && !this.states.is( 'animating' ) ) {
this.#origin = origin instanceof HTMLElement ? origin : document.activeElement || null;
this.states.set( 'animating' );
// Check if we can show
if ( events && !this.dispatchEvent( ( this.config.get( 'eventPrefix' ) || '' ) + 'show', null, true, true ) ) {
this.states.unset( 'animating' );
return;
}
// Get animation callback
let animator = this.config.get( 'animator.show' );
if ( typeof animator !== 'function' ) {
animator = ( complete ) => {
this.#bind_transition_complete( complete );
};
}
// Make visible
if ( this.config.get( 'animator.vis' ) ) this.dom.style.display = '';
// When visible start animation
// Element will be part of the render tree after the next frame draw to ensure transitions run cleanly
afterPaint( () => {
// Set props and states
const native = this.getDomRefs( 'native', false );
if ( native ) native.setAttribute( 'open', '' );
( native || this.dom ).setAttribute( 'aria-hidden', 'false' );
this.states.set( 'open' );
const context_class = this.config.get( 'openInContextClass' );
if ( context_class ) this.config.get( 'context' ).classList.add( context_class );
// Run animator
animator( () => {
this.states.unset( 'animating' );
if ( events ) this.dispatchEvent( ( this.config.get( 'eventPrefix' ) || '' ) + 'shown' );
}, this );
} );
}
}
/**
* Hide panel
* @param {boolean} events - Fire events
* @return {void}
*/
hide( events = true ) {
if ( this.open && !this.states.is( 'animating' ) ) {
this.states.set( 'animating' );
// Check if we can hide
if ( events && !this.dispatchEvent( ( this.config.get( 'eventPrefix' ) || '' ) + 'hide', null, true, true ) ) {
this.states.unset( 'animating' );
return;
}
// Get animation callback
let animator = this.config.get( 'animator.hide' );
if ( typeof animator !== 'function' ) {
animator = ( complete ) => {
this.#bind_transition_complete( complete );
};
}
// Set props and states
const native = this.getDomRefs( 'native', false );
if ( native ) native.removeAttribute( 'open' );
( native || this.dom ).setAttribute( 'aria-hidden', 'true' );
this.states.set( 'closed' );
const context_class = this.config.get( 'openInContextClass' );
if ( context_class ) this.config.get( 'context' ).classList.remove( context_class );
// Run animator
animator( () => {
this.states.unset( 'animating' );
if ( this.config.get( 'animator.vis' ) ) this.dom.style.display = 'none';
if ( this.#origin && this.config.get( 'focusResetOnHidden' ) ) {
this.#origin.focus();
}
if ( events ) this.dispatchEvent( ( this.config.get( 'eventPrefix' ) || '' ) + 'hidden' );
this.#origin = null;
}, this );
}
}
}