-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathexpressive-modal.ts
623 lines (565 loc) · 19.2 KB
/
expressive-modal.ts
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
/**
* @license
*
* Copyright IBM Corp. 2020, 2024
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { html, LitElement, SVGTemplateResult, TemplateResult } from 'lit';
import { property, query, state } from 'lit/decorators.js';
import { EXPRESSIVE_MODAL_MODE, EXPRESSIVE_MODAL_SIZE } from './defs';
import { classMap } from 'lit/directives/class-map.js';
import C4DCarousel from '../carousel/carousel';
import C4DExpressiveModalCloseButton from './expressive-modal-close-button';
import settings from '@carbon/ibmdotcom-utilities/es/utilities/settings/settings.js';
import HostListener from '@carbon/web-components/es/globals/decorators/host-listener.js';
import HostListenerMixin from '@carbon/web-components/es/globals/mixins/host-listener.js';
import on from '@carbon/web-components/es/globals/mixins/on.js';
import { selectorTabbable } from '@carbon/web-components/es/globals/settings.js';
import StableSelectorMixin from '../../globals/mixins/stable-selector';
import styles from './expressive-modal.scss';
import { carbonElement as customElement } from '@carbon/web-components/es/globals/decorators/carbon-element.js';
const { prefix, stablePrefix: c4dPrefix } = settings;
/* eslint-disable no-bitwise */
const PRECEDING =
Node.DOCUMENT_POSITION_PRECEDING | Node.DOCUMENT_POSITION_CONTAINS;
const FOLLOWING =
Node.DOCUMENT_POSITION_FOLLOWING | Node.DOCUMENT_POSITION_CONTAINED_BY;
const WITHIN = Node.DOCUMENT_POSITION_CONTAINED_BY;
/* eslint-enable no-bitwise */
// TODO: Wait for `.d.ts` update to support `ResizeObserver`
// @ts-ignore
const onResize: ResizeObserverCallback = ([entry]) => {
const { target, contentRect } = entry;
const { width, height } = contentRect;
const modalContent = target as HTMLDivElement;
modalContent.style.setProperty('--modal-vh', `${height}px`);
modalContent.style.setProperty('--modal-vw', `${width}px`);
};
/**
* The table mapping slot name with the private property name that indicates the existence of the slot content.
*/
const slotExistencePropertyNames = {
header: '_hasHeader',
footer: '_hasFooter',
};
/**
* Expressive modal.
*
* @element c4d-expressive-modal
* @fires c4d-expressive-modal-beingclosed
* The custom event fired before this modal is being closed upon a user gesture.
* Cancellation of this event stops the user-initiated action of closing this modal.
* @fires c4d-expressive-modal-closed - The custom event fired after this modal is closed upon a user gesture.
* @slot header - The header content.
* @slot footer - The footer content.
* @csspart modal-header - The modal header. Usage: `c4d-expressive-modal::part(modal-header)`
* @csspart modal-body - The modal body. Usage: `c4d-expressive-modal::part(modal-body)`
* @csspart sentinel-button - Taget all Sentinels buttons Usage: `c4d-expressive-modal::part(sentinel-button)`
* @csspart sentinel-button--start - Button labled START. Usage: `c4d-expressive-modal::part(sentinel-button--start)`
* @csspart sentinel-button--end - Button labled END. Usage: `c4d-expressive-modal::part(sentinel-button--end)`
* @csspart modal-container - The modal container. Usage: `c4d-expressive-modal::part(modal-container)`
* @csspart footer-container - The footer container. Usage: `c4d-expressive-modal::part(footer-container)`
*/
@customElement(`${c4dPrefix}-expressive-modal`)
class C4DExpressiveModal extends StableSelectorMixin(
HostListenerMixin(LitElement)
) {
/**
* `true` if there is a header content.
*/
@state()
private _hasHeader = false;
/**
* `true` if there is a body content.
*/
@state()
private _hasBody = false;
/**
* `true` if there is a footer content.
*/
@state()
private _hasFooter = false;
/**
* The element that had focus before this modal gets open.
*/
private _launcher: Element | null = null;
/**
* Collection of elements to search for focusable elements.
*/
hasFocusableElements: [C4DExpressiveModal | C4DCarousel] = [this];
/**
* Returns all focusable elements within this component and its shadowroot
*/
get focusableElements() {
const { selectorCloseButton, selectorTabbable: selectorTabbableForModal } =
this.constructor as typeof C4DExpressiveModal;
return [
...Array.from(
(this.shadowRoot?.querySelectorAll(
selectorCloseButton
) as NodeListOf<HTMLElement>) || []
),
...Array.from(
this.querySelectorAll(
selectorTabbableForModal
) as NodeListOf<HTMLElement>
),
];
}
get _focusableElements() {
const { hasFocusableElements } = this;
const focusableElements: [HTMLElement?] = [];
hasFocusableElements.forEach((el) => {
if (el.focusableElements) {
focusableElements.push(...el.focusableElements);
}
});
return Array.from(new Set(focusableElements)).sort((a, b) => {
const comparison = a!.compareDocumentPosition(b!);
/* eslint-disable no-bitwise */
if (comparison & PRECEDING) {
return 1;
}
if (comparison & FOLLOWING) {
return -1;
}
/* eslint-enable no-bitwise */
return 0;
});
}
/**
* Node to track focus going outside of modal content.
*/
@query('#start-sentinel')
private _startSentinelNode!: HTMLAnchorElement;
/**
* Node to track focus going outside of modal content.
*/
@query('#end-sentinel')
private _endSentinelNode!: HTMLAnchorElement;
@query(`.${prefix}--modal-content`)
modalContent?: HTMLDivElement;
@query(`.${c4dPrefix}-ce--modal__body`)
modalBody?: HTMLDivElement;
// TODO: Wait for `.d.ts` update to support `ResizeObserver`
// @ts-ignore
private _resizeObserver = new ResizeObserver(
onResize as ResizeObserverCallback
);
/**
* Handles `click` event on this element.
*
* @param event The event.
*/
@HostListener('click')
// @ts-ignore: The decorator refers to this method but TS thinks this method is not referred to
private _handleClick = (event: MouseEvent) => {
if (event.composedPath().indexOf(this.shadowRoot!) < 0) {
this._handleUserInitiatedClose(event.target);
}
};
/* eslint-disable no-bitwise */
/**
* Handles the `focusin` event on the start and end sentinels
*
* @param event The event.
* @param event.target The event target.
* @param event.relatedTarget The event relatedTarget.
*/
protected _handleFocusIn = ({ target, relatedTarget }) => {
const { tryFocusElems } = this.constructor as typeof C4DExpressiveModal;
let focusFromWithin = false;
if (target && relatedTarget) {
const comparedToThis = this.compareDocumentPosition(relatedTarget);
const comparedToShadowRoot =
this.shadowRoot!.compareDocumentPosition(relatedTarget);
// If relatedTarget is descendent of `this` or `this.shadowRoot`.
if (comparedToThis & WITHIN || comparedToShadowRoot & WITHIN) {
focusFromWithin = true;
}
}
const {
_endSentinelNode: endSentinelNode,
_startSentinelNode: startSentinelNode,
_focusableElements: focusableElements,
} = this;
if (focusFromWithin) {
if (target === startSentinelNode) {
tryFocusElems(focusableElements as [HTMLElement], true, this);
} else if (target === endSentinelNode) {
tryFocusElems(focusableElements as [HTMLElement], false, this);
}
} else {
tryFocusElems(focusableElements as [HTMLElement], false, this);
}
};
/**
* Handles `focusout` event on this element.
*
* @param event The event.
* @param event.target The event target.
* @param event.relatedTarget The event relatedTarget.
*/
@HostListener('focusout')
// @ts-ignore: The decorator refers to this method but TS thinks this method is not referred to
private _handleFocusOut = ({ target, relatedTarget }) => {
// Don't attempt to wrap focus if the modal isn't open.
if (!this.open) {
return;
}
// If no target/relatedTarget, focus has entered/left the window. Do nothing.
if (!target || !relatedTarget) {
return;
}
const { tryFocusElems } = this.constructor as typeof C4DExpressiveModal;
const { _focusableElements: focusableElements } = this;
// See if element gaining focus is inside `this` or `this.shadowRoot`.
const positionToModal =
this.compareDocumentPosition(relatedTarget) |
(this.shadowRoot?.compareDocumentPosition(relatedTarget) || 0);
const positionToPrevious = target.compareDocumentPosition(relatedTarget);
const relatedTargetIsContained = Boolean(positionToModal & WITHIN);
// If focusing outside of `this`, cycle focus
if (!relatedTargetIsContained && !(relatedTarget === this)) {
if (positionToPrevious & PRECEDING) {
tryFocusElems(focusableElements as [HTMLElement], true, this);
} else if (positionToPrevious & FOLLOWING) {
tryFocusElems(focusableElements as [HTMLElement], false, this);
}
}
};
/* eslint-enable no-bitwise */
@HostListener('document:keydown')
// @ts-ignore: The decorator refers to this method but TS thinks this method is not referred to
private _handleKeydown = ({ key, target }: KeyboardEvent) => {
if (key === 'Esc' || key === 'Escape') {
this._handleUserInitiatedClose(target);
}
};
/**
* Handles `click` event on the modal container.
*
* @param event The event.
*/
private _handleClickContainer(event: MouseEvent) {
if (
(event.target as Element).matches(
(this.constructor as typeof C4DExpressiveModal).selectorCloseButton
)
) {
this._handleUserInitiatedClose(event.target);
}
}
/**
* Handles `slotchange` event.
*/
private _handleSlotChange({ target }: Event) {
const { name } = target as HTMLSlotElement;
const hasContent = (target as HTMLSlotElement)
.assignedNodes()
.some((node) => {
// Allow non-empty text nodes.
if (node.nodeType === Node.TEXT_NODE && node!.textContent!.trim()) {
return true;
}
// Allow only element nodes that don't have a .cds--visually-hidden
// class.
if (node instanceof Element) {
return !node.classList.contains('cds--visually-hidden');
}
// No opinion on other cases.
return true;
});
this[slotExistencePropertyNames[name] || '_hasBody'] = hasContent;
}
/**
* Handles user-initiated close request of this modal.
*
* @param triggeredBy The element that triggered this close request.
*/
private _handleUserInitiatedClose(triggeredBy: EventTarget | null) {
if (this.open) {
const init = {
bubbles: true,
cancelable: true,
composed: true,
detail: {
triggeredBy,
},
};
const { eventBeforeClose, eventClose } = this
.constructor as typeof C4DExpressiveModal;
if (this.dispatchEvent(new CustomEvent(eventBeforeClose, init))) {
this.open = false;
this.dispatchEvent(new CustomEvent(eventClose, init));
}
this.setAttribute('aria-hidden', 'true');
}
}
/**
* @param timeout The number of milliseconds as the longest time waiting for `transitionend` event.
* @returns A promise that is resolves when `transitionend` on the host element fires.
*/
private _waitForTransitionEnd(timeout = 1000) {
return new Promise((resolve) => {
let done = false;
let hTransitionEnd;
const handleResolve = () => {
if (hTransitionEnd) {
hTransitionEnd.release();
hTransitionEnd = null;
}
if (!done) {
resolve(undefined);
done = true;
}
};
on(this, 'transitionend', handleResolve);
setTimeout(handleResolve, timeout);
});
}
/**
* @returns The header content.
*/
protected _renderHeader(): TemplateResult | SVGTemplateResult | void {
const {
_hasHeader: hasHeader,
_hasBody: hasBody,
_hasFooter: hasFooter,
} = this;
const headerClasses = classMap({
[`${c4dPrefix}-ce--modal__header--with-body`]:
hasHeader && (hasBody || hasFooter),
});
return html`
<div
id="${prefix}--modal-header"
class="${headerClasses}"
part="modal-header">
<slot name="header"></slot>
</div>
`;
}
/**
* @returns The body content.
*/
protected _renderBody(): TemplateResult | SVGTemplateResult | void {
const { _hasBody: hasBody, _hasFooter: hasFooter } = this;
const bodyClasses = classMap({
[`${c4dPrefix}-ce--modal__body`]: true,
[`${c4dPrefix}-ce--modal__body--with-footer`]: hasBody && hasFooter,
});
return html`
<div class="${bodyClasses}" part="modal-body"><slot></slot></div>
`;
}
/**
* @returns The footer content.
*/
// eslint-disable-next-line class-methods-use-this
protected _renderFooter(): TemplateResult | SVGTemplateResult | void {
return html`
<div part="footer-container"><slot name="footer"></slot></div>
`;
}
/**
* The additional CSS class names for the container <div> of the element.
*/
@property({ attribute: 'container-class' })
containerClass = '';
/**
* `true` if the modal should be open.
*/
@property({ type: Boolean, reflect: true })
open = false;
/**
* The size variant.
*/
@property({ reflect: true, attribute: 'expressive-size' })
size = EXPRESSIVE_MODAL_SIZE.REGULAR;
/**
* The mode variant.
*/
@property({ reflect: true, attribute: 'mode' })
mode = EXPRESSIVE_MODAL_MODE.DEFAULT;
render() {
const {
size,
_handleClickContainer: handleClickContainer,
_handleSlotChange: handleSlotChange,
_handleFocusIn: handleFocusIn,
} = this;
const containerClass = this.containerClass
.split(' ')
.filter(Boolean)
.reduce((acc, item) => ({ ...acc, [item]: true }), {});
const containerClasses = classMap({
[`${prefix}--modal-container`]: true,
[`${prefix}--modal-container--fullwidth`]:
size === EXPRESSIVE_MODAL_SIZE.FULL_WIDTH,
...containerClass,
});
return html`
<button
id="start-sentinel"
class="${prefix}--visually-hidden"
part="sentinel-button sentinel-button--start"
@focusin="${handleFocusIn}">
START
</button>
<div
class="${containerClasses}"
part="modal-container"
tabindex="-1"
role="dialog"
aria-labelledby="${c4dPrefix}--modal-header"
@click="${handleClickContainer}"
@slotchange="${handleSlotChange}">
<div class="${prefix}--modal-content" part="modal-content">
${this._renderHeader()}${this._renderBody()}${this._renderFooter()}
</div>
</div>
<button
id="end-sentinel"
class="${prefix}--visually-hidden"
part="sentinel-button sentinel-button--end"
@focusin="${handleFocusIn}">
END
</button>
`;
}
protected firstUpdated() {
if (this.modalContent) {
this._resizeObserver.observe(this.modalContent);
}
}
async updated(changedProperties) {
const { _focusableElements: focusableElements, size } = this;
const { selectorCloseButton, tryFocusElems } = this
.constructor as typeof C4DExpressiveModal;
if (changedProperties.has('size')) {
const closeButton = this.querySelector(selectorCloseButton);
if (closeButton) {
(closeButton as C4DExpressiveModalCloseButton).size = size;
}
}
if (changedProperties.has('open')) {
if (this.open) {
this.ownerDocument.body.style.overflow = 'hidden';
this.removeAttribute('aria-hidden');
this._launcher = this.ownerDocument!.activeElement;
await this._waitForTransitionEnd();
const primaryFocusNode = this.querySelector(
(this.constructor as typeof C4DExpressiveModal).selectorPrimaryFocus
);
if (primaryFocusNode) {
// For cases where a `carbon-web-components` component (e.g. `<cds-btn>`) being `primaryFocusNode`,
// where its first update/render cycle that makes it focusable happens after `<cds-modal>`'s first update/render cycle
(primaryFocusNode as HTMLElement).focus();
} else {
tryFocusElems(focusableElements as [HTMLElement], true, this);
}
} else if (
this._launcher &&
typeof (this._launcher as HTMLElement).focus === 'function'
) {
(this._launcher as HTMLElement).focus();
this.ownerDocument.body.style.overflow = '';
this._launcher = null;
}
}
return super.updated(changedProperties);
}
/**
* A selector selecting buttons that should close this modal.
*/
static get selectorCloseButton() {
return `[data-modal-close],${prefix}-modal-close-button,${c4dPrefix}-expressive-modal-close-button`;
}
/**
* A selector selecting tabbable nodes.
*/
static get selectorTabbable() {
return `
${selectorTabbable},
${c4dPrefix}-button,
${c4dPrefix}-expressive-modal,
${c4dPrefix}-expressive-modal-close-button
`;
}
/**
* A selector selecting the nodes that should be focused when modal gets open.
*/
static get selectorPrimaryFocus() {
return `
[data-modal-primary-focus],
${c4dPrefix}-expressive-modal-footer ${c4dPrefix}-button[kind="primary"]
`;
}
static get stableSelector() {
return `${c4dPrefix}--expressive-modal`;
}
/**
* The name of the custom event fired before this modal is being closed upon a user gesture.
* Cancellation of this event stops the user-initiated action of closing this modal.
*/
static get eventBeforeClose() {
return `${c4dPrefix}-expressive-modal-beingclosed`;
}
/**
* The name of the custom event fired after this modal is closed upon a user gesture.
*/
static get eventClose() {
return `${c4dPrefix}-expressive-modal-closed`;
}
/**
* Tries to focus on the given elements and bails out if one of the is successful.
*
* @param elems The elements.
* @param reverse `true` to go through the list in reverse order.
* @param fallback element to focus on if none
* @returns `true` if one of the attempts is successful, `false` otherwise.
*/
static tryFocusElems(
elems: NodeListOf<HTMLElement> | [HTMLElement],
reverse = false,
fallback: HTMLElement | null = null
) {
if (!reverse) {
for (let i = 0; i < elems.length; ++i) {
const elem = elems[i];
if (
elem.offsetWidth ||
elem.offsetHeight ||
elem.getClientRects().length
) {
elem.focus();
if ((elem.getRootNode() as Document).activeElement === elem) {
return true;
}
}
}
} else {
for (let i = elems.length - 1; i >= 0; --i) {
const elem = elems[i];
if (
elem.offsetWidth ||
elem.offsetHeight ||
elem.getClientRects().length
) {
elem.focus();
if ((elem.getRootNode() as Document).activeElement === elem) {
return true;
}
}
}
}
fallback?.focus();
return false;
}
static styles = styles; // `styles` here is a `CSSResult` generated by custom WebPack loader
}
/* @__GENERATE_REACT_CUSTOM_ELEMENT_TYPE__ */
export default C4DExpressiveModal;