/
bs-modal.js
674 lines (584 loc) · 15.1 KB
/
bs-modal.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
import { action, computed } from '@ember/object';
import { assert } from '@ember/debug';
import Component from '@glimmer/component';
import { next, schedule } from '@ember/runloop';
import { inject as service } from '@ember/service';
import transitionEnd from 'ember-bootstrap/utils/transition-end';
import { getDestinationElement } from 'ember-bootstrap/utils/dom';
import { guidFor } from '@ember/object/internals';
import usesTransition from 'ember-bootstrap/utils/decorators/uses-transition';
import isFastBoot from 'ember-bootstrap/utils/is-fastboot';
import deprecateSubclassing from 'ember-bootstrap/utils/deprecate-subclassing';
import arg from '../utils/decorators/arg';
import { tracked } from '@glimmer/tracking';
function nextRunloop() {
return new Promise((resolve) => next(resolve));
}
function afterRender() {
return new Promise((resolve) => schedule('afterRender', resolve));
}
/**
Component for creating [Bootstrap modals](http://getbootstrap.com/javascript/#modals) with custom markup.
### Usage
```hbs
<BsModal @onSubmit={{action "submit"}} as |Modal|>
<Modal.header>
<h4 class="modal-title"><i class="glyphicon glyphicon-alert"></i> Alert</h4>
</Modal.header>
<Modal.body>
Are you absolutely sure you want to do that???
</Modal.body>
<Modal.footer as |footer|>
<BsButton @onClick={{action Modal.close}} @type="danger">Oh no, forget it!</BsButton>
<BsButton @onClick={{action Modal.submit}} @type="success">Yeah!</BsButton>
</Modal.footer>
</BsModal>
```
The component yields references to the following contextual components, that you can use to further customize the output:
* [modal.body](Components.ModalBody.html)
* [modal.header](Components.ModalHeader.html)
* [modal.footer](Components.ModalFooter.html)
Furthermore references to the following actions are yielded:
* `close`: triggers the `onHide` action and closes the modal
* `submit`: triggers the `onSubmit` action (or the submit event on a form if present in the body element)
### Further reading
See the documentation of the [bs-modal-simple](Components.ModalSimple.html) component for further examples.
*Note that only invoking the component in a template as shown above is considered part of its public API. Extending from it (subclassing) is generally not supported, and may break at any time.*
@class Modal
@namespace Components
@extends Glimmer.Component
@public
*/
@deprecateSubclassing
export default class Modal extends Component {
@service('-document')
document;
/**
* @property _isOpen
* @private
*/
_isOpen = false;
/**
* Set to false to disable fade animations.
*
* @property fade
* @type boolean
* @default true
* @public
*/
get _fade() {
let isFB = isFastBoot(this);
return this.args.fade === undefined ? !isFB : this.args.fade;
}
/**
* Used to apply Bootstrap's visibility classes.
*
* @property showModal
* @type boolean
* @default false
* @private
*/
@tracked
showModal = this.open && (!this._fade || isFastBoot(this));
/**
* Render modal markup?
*
* @property inDom
* @type boolean
* @default false
* @private
*/
@tracked
inDom = this.open;
/**
* @property paddingLeft
* @type number|undefined
* @private
*/
@tracked
paddingLeft;
/**
* @property paddingRight
* @type number|undefined
* @private
*/
@tracked
paddingRight;
/**
* Visibility of the modal. Toggle to show/hide with CSS transitions.
*
* When the modal is closed by user interaction this property will not update by using two-way bindings in order
* to follow DDAU best practices. If you want to react to such changes, subscribe to the `onHide` action
*
* @property open
* @type boolean
* @default true
* @public
*/
@arg
open = true;
/**
* Use a semi-transparent modal background to hide the rest of the page.
*
* @property backdrop
* @type boolean
* @default true
* @public
*/
@arg
backdrop = true;
/**
* @property showBackdrop
* @type boolean
* @private
*/
@tracked
showBackdrop = this.open && this.backdrop;
/**
* Closes the modal when escape key is pressed.
*
* @property keyboard
* @type boolean
* @default true
* @public
*/
@arg
keyboard = true;
/**
* [BS4 only!] Vertical position, either 'top' (default) or 'center'
* 'center' will apply the `modal-dialog-centered` class
*
* @property position
* @type {string}
* @default 'top'
* @public
*/
@arg
position = 'top';
/**
* [BS4 only!] Allows scrolling within the modal body
* 'true' will apply the `modal-dialog-scrollable` class
*
* @property scrollable
* @type boolean
* @default false
* @public
*/
@arg
scrollable = false;
/**
* @property dialogComponent
* @type {String}
* @private
*/
/**
* @property headerComponent
* @type {String}
* @private
*/
/**
* @property bodyComponent
* @type {String}
* @private
*/
/**
* @property footerComponent
* @type {String}
* @private
*/
/**
* The id of the `.modal` element.
*
* @property modalId
* @type string
* @readonly
* @private
*/
get modalId() {
return `${guidFor(this)}-modal`;
}
/**
* The id of the backdrop element.
*
* @property backdropId
* @type string
* @readonly
* @private
*/
get backdropId() {
return `${guidFor(this)}-backdrop`;
}
/**
* Property for size styling, set to null (default), 'lg' or 'sm'
*
* Also see the [Bootstrap docs](http://getbootstrap.com/javascript/#modals-sizes)
*
* @property size
* @type String
* @public
*/
/**
* If true clicking on the backdrop will close the modal.
*
* @property backdropClose
* @type boolean
* @default true
* @public
*/
@arg
backdropClose = true;
/**
* If true component will render in place, rather than be wormholed.
*
* @property renderInPlace
* @type boolean
* @default false
* @public
*/
@arg
renderInPlace = false;
/**
* @property _renderInPlace
* @type boolean
* @private
*/
get _renderInPlace() {
return this.renderInPlace || !this.destinationElement;
}
/**
* The duration of the fade transition
*
* @property transitionDuration
* @type number
* @default 300
* @public
*/
@arg
transitionDuration = 300;
/**
* The duration of the backdrop fade transition
*
* @property backdropTransitionDuration
* @type number
* @default 150
* @public
*/
@arg
backdropTransitionDuration = 150;
/**
* Use CSS transitions?
*
* @property usesTransition
* @type boolean
* @readonly
* @private
*/
@usesTransition('_fade')
usesTransition;
destinationElement = getDestinationElement(this);
/**
* The DOM element of the `.modal` element.
*
* @property modalElement
* @type object
* @readonly
* @private
*/
get modalElement() {
return document.getElementById(this.modalId);
}
/**
* The DOM element of the backdrop element.
*
* @property backdropElement
* @type object
* @readonly
* @private
*/
get backdropElement() {
return document.getElementById(this.backdropId);
}
/**
* The action to be sent when the modal footer's submit button (if present) is pressed.
* Note that if your modal body contains a form (e.g. [Components.Form](Components.Form.html)) this action will
* not be triggered. Instead a submit event will be triggered on the form itself. See the class description for an
* example.
*
* @property onSubmit
* @type function
* @public
*/
/**
* The action to be sent when the modal is closing.
* This will be triggered by pressing the modal header's close button (x button) or the modal footer's close button.
* Note that this will happen before the modal is hidden from the DOM, as the fade transitions will still need some
* time to finish. Use the `onHidden` if you need the modal to be hidden when the action triggers.
*
* You can return false to prevent closing the modal automatically, and do that in your action by
* setting `open` to false.
*
* @property onHide
* @type function
* @public
*/
/**
* The action to be sent after the modal has been completely hidden (including the CSS transition).
*
* @property onHidden
* @type function
* @default null
* @public
*/
/**
* The action to be sent when the modal is opening.
* This will be triggered immediately after the modal is shown (so it's safe to access the DOM for
* size calculations and the like). This means that if fade=true, it will be shown in between the
* backdrop animation and the fade animation.
*
* @property onShow
* @type function
* @default null
* @public
*/
/**
* The action to be sent after the modal has been completely shown (including the CSS transition).
*
* @property onShown
* @type function
* @public
*/
@action
close() {
if (this.args.onHide?.() !== false) {
this.hide();
}
}
@action
doSubmit() {
// replace modalId by :scope selector if supported by all target browsers
let modalId = this.modalId;
let forms = this.modalElement.querySelectorAll(`#${modalId} .modal-body form`);
if (forms.length > 0) {
// trigger submit event on body forms
let event = document.createEvent('Events');
event.initEvent('submit', true, true);
Array.prototype.slice.call(forms).forEach((form) => form.dispatchEvent(event));
} else {
// if we have no form, we send a submit action
this.args.onSubmit?.();
}
}
/**
* Show the modal
*
* @method show
* @private
*/
async show() {
if (this._isOpen) {
return;
}
this._isOpen = true;
this.addBodyClass();
this.resize();
this.inDom = true;
await this.handleBackdrop();
if (this.isDestroyed) {
return;
}
this.checkScrollbar();
this.setScrollbar();
await afterRender();
const { modalElement } = this;
if (!modalElement) {
return;
}
modalElement.scrollTop = 0;
this.adjustDialog();
this.showModal = true;
this.args.onShow?.();
if (this.usesTransition) {
await transitionEnd(modalElement, this.transitionDuration);
}
this.args.onShown?.();
}
/**
* Hide the modal
*
* @method hide
* @private
*/
async hide() {
if (!this._isOpen) {
return;
}
this._isOpen = false;
this.resize();
this.showModal = false;
if (this.usesTransition) {
await transitionEnd(this.modalElement, this.transitionDuration);
}
await this.hideModal();
}
/**
* Clean up after modal is hidden and call onHidden
*
* @method hideModal
* @private
*/
async hideModal() {
if (this.isDestroyed) {
return;
}
await this.handleBackdrop();
this.removeBodyClass();
this.resetAdjustments();
this.resetScrollbar();
this.inDom = false;
this.args.onHidden?.();
}
/**
* SHow/hide the backdrop
*
* @method handleBackdrop
* @param callback
* @private
*/
async handleBackdrop() {
const { usesTransition } = this;
if (this.open && this.backdrop) {
this.showBackdrop = true;
await nextRunloop();
if (usesTransition) {
const { backdropElement } = this;
assert('Backdrop element should be in DOM', backdropElement);
await transitionEnd(backdropElement, this.backdropTransitionDuration);
}
} else if (!this.open && this.backdrop) {
if (usesTransition) {
const { backdropElement } = this;
assert('Backdrop element should be in DOM', backdropElement);
await transitionEnd(backdropElement, this.backdropTransitionDuration);
}
if (this.isDestroyed) {
return;
}
this.showBackdrop = false;
}
}
/**
* Attach/Detach resize event listeners
*
* @method resize
* @private
*/
resize() {
if (this.open) {
window.addEventListener('resize', this.adjustDialog, false);
} else {
window.removeEventListener('resize', this.adjustDialog, false);
}
}
/**
* @method adjustDialog
* @private
*/
@action
adjustDialog() {
let modalIsOverflowing = this.modalElement.scrollHeight > document.documentElement.clientHeight;
this.paddingLeft = !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : undefined;
this.paddingRight = this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : undefined;
}
/**
* @method resetAdjustments
* @private
*/
resetAdjustments() {
this.paddingLeft = undefined;
this.paddingRight = undefined;
}
/**
* @method checkScrollbar
* @private
*/
checkScrollbar() {
let fullWindowWidth = window.innerWidth;
if (!fullWindowWidth) {
// workaround for missing window.innerWidth in IE8
let documentElementRect = document.documentElement.getBoundingClientRect();
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left);
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth;
}
/**
* @method setScrollbar
* @private
*/
setScrollbar() {
let bodyPad = parseInt(document.body.style.paddingRight || 0, 10);
this._originalBodyPad = document.body.style.paddingRight || '';
if (this.bodyIsOverflowing) {
document.body.style.paddingRight = bodyPad + this.scrollbarWidth;
}
}
/**
* @method resetScrollbar
* @private
*/
resetScrollbar() {
document.body.style.paddingRight = this._originalBodyPad;
}
addBodyClass() {
// special handling for FastBoot, where real `document` is not available
if (isFastBoot(this)) {
// a SimpleDOM instance with just a subset of the DOM API!
let document = this.document;
let existingClasses = document.body.getAttribute('class') || '';
if (!existingClasses.includes('modal-open')) {
document.body.setAttribute('class', `modal-open ${existingClasses}`);
}
} else {
document.body.classList.add('modal-open');
}
}
removeBodyClass() {
// no need for FastBoot support here
document.body.classList.remove('modal-open');
}
/**
* @property scrollbarWidth
* @type number
* @readonly
* @private
*/
@computed('modalElement')
get scrollbarWidth() {
let scrollDiv = document.createElement('div');
scrollDiv.className = 'modal-scrollbar-measure';
let modalEl = this.modalElement;
modalEl.parentNode.insertBefore(scrollDiv, modalEl.nextSibling);
let scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
scrollDiv.parentNode.removeChild(scrollDiv);
return scrollbarWidth;
}
willDestroy() {
super.willDestroy(...arguments);
if (typeof FastBoot === 'undefined') {
window.removeEventListener('resize', this.adjustDialog, false);
this.removeBodyClass();
this.resetScrollbar();
}
}
@action
handleVisibilityChanges() {
if (isFastBoot(this)) {
this.addBodyClass();
return;
}
if (this.args.open !== false) {
this.show();
} else {
this.hide();
}
}
}