-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathpf-modal.ts
More file actions
320 lines (277 loc) · 10.4 KB
/
pf-modal.ts
File metadata and controls
320 lines (277 loc) · 10.4 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
import { LitElement, html, type TemplateResult } from 'lit';
import { customElement } from 'lit/decorators/custom-element.js';
import { property } from 'lit/decorators/property.js';
import { query } from 'lit/decorators/query.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { classMap } from 'lit/directives/class-map.js';
import { ComposedEvent } from '@patternfly/pfe-core';
import { bound, initializer, observes } from '@patternfly/pfe-core/decorators.js';
import { getRandomId } from '@patternfly/pfe-core/functions/random.js';
import { SlotController } from '@patternfly/pfe-core/controllers/slot-controller.js';
import style from './pf-modal.css';
export class ModalCancelEvent extends ComposedEvent {
constructor() {
super('cancel');
}
}
export class ModalCloseEvent extends ComposedEvent {
constructor() {
super('close');
}
}
export class ModalOpenEvent extends ComposedEvent {
constructor(
/** The trigger element which triggered the modal to open */
public trigger: HTMLElement | null
) {
super('open');
}
}
/**
* A **modal** displays important information to a user without requiring them to navigate
* to a new page.
* @summary Displays information or helps a user focus on a task
* @alias Modal
* @fires {ModalOpenEvent} open - Fires when a user clicks on the trigger or manually opens a modal.
* @fires {ModalCloseEvent} close - Fires when either a user clicks on either the close button or the overlay or manually closes a modal.
*/
@customElement('pf-modal')
export class PfModal extends LitElement {
static override readonly shadowRootOptions: ShadowRootInit = {
...LitElement.shadowRootOptions,
delegatesFocus: true,
};
static readonly styles: CSSStyleSheet[] = [style];
/** Should the dialog close when user clicks outside the dialog? */
protected static closeOnOutsideClick = false;
/**
* The `variant` controls the width of the modal.
* There are three options: `small`, `medium` and `large`. The default is `large`.
*/
@property({ reflect: true }) variant?: 'small' | 'medium' | 'large';
/**
* `position="top"` aligns the dialog with the top of the page
*/
@property({ reflect: true }) position?: 'top';
@property({ type: Boolean, reflect: true }) open = false;
/** Optional ID of the trigger element */
@property() trigger?: string;
/** @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/returnValue */
public returnValue = '';
@query('#overlay') private overlay?: HTMLElement | null;
@query('#dialog') private dialog?: HTMLElement | null;
@query('#close-button') private closeButton?: HTMLElement | null;
#headerId = getRandomId();
#triggerElement: HTMLElement | null = null;
#header: HTMLElement | null = null;
#body: Element[] = [];
#headings: Element[] = [];
#cancelling = false;
#slots = new SlotController(this, null, 'header', 'description', 'footer');
connectedCallback(): void {
super.connectedCallback();
this.addEventListener('keydown', this.onKeydown);
this.addEventListener('click', this.onClick);
}
render(): TemplateResult<1> {
const headerId = (this.#header || this.#headings.length) ? this.#headerId : undefined;
const headerLabel = this.#triggerElement ? this.#triggerElement.innerText : undefined;
const hasHeader = this.#slots.hasSlotted('header');
const hasDescription = this.#slots.hasSlotted('description');
const hasFooter = this.#slots.hasSlotted('footer');
return html`
<section ?hidden=${!this.open}>
<!-- summary: The modal overlay which lies under the dialog and above the page body -->
<div id="overlay" part="overlay" ?hidden=${!this.open}></div>
<!-- summary: The dialog element -->
<div id="dialog"
part="dialog"
tabindex="0"
role="dialog"
aria-labelledby=${ifDefined(headerId)}
aria-label=${ifDefined(headerLabel)}
?hidden="${!this.open}">
<div id="container">
<!-- summary: The container for the dialog content -->
<div id="content" part="content" class=${classMap({ hasHeader, hasDescription, hasFooter })}>
<!-- summary: The container for the optional dialog header -->
<header part="header">
<!-- summary: Heading tag
description: |
The header is an optional slot that appears at the top of the modal window.
It should be a heading tag (h2-h6). -->
<slot name="header"></slot>
<!-- summary: The container for the optional dialog description in the header -->
<div part="description" ?hidden=${!hasDescription}>
<slot name="description"></slot>
</div>
</header>
<!--
summary: Modal dialog content
description: |
The default slot can contain any type of content. When the header is not present,
this unnamed slot appear at the top of the modal window (to the left of the close
button). Otherwise it will appear beneath the header. -->
<slot></slot>
<!-- summary: Actions footer container -->
<footer ?hidden=${!hasFooter} part="footer">
<!-- summary: Optional footer content. Good place to put action buttons. -->
<slot name="footer"></slot>
</footer>
</div>
<!-- summary: The modal's close button -->
<button id="close-button"
part="close-button"
aria-label="Close dialog"
@keydown=${this.onKeydown}
@click=${this.close}>
<svg fill="currentColor" viewBox="0 0 352 512">
<path d="M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"></path>
</svg>
</button>
</div>
</div>
</section>
`;
}
disconnectedCallback(): void {
super.disconnectedCallback();
this.removeEventListener('keydown', this.onKeydown);
this.#triggerElement?.removeEventListener('click', this.onTriggerClick);
}
@initializer()
protected async _init(): Promise<void> {
await this.updateComplete;
this.#header = this.querySelector(`[slot$="header"]`);
this.#body = [...this.querySelectorAll(`*:not([slot])`)];
this.#headings = this.#body.filter(el => el.tagName.slice(0, 1) === 'H');
if (this.#triggerElement) {
this.#triggerElement.addEventListener('click', this.onTriggerClick);
this.removeAttribute('hidden');
}
if (this.#header) {
this.#header.id = this.#headerId;
} else if (this.#headings.length > 0) {
// Get the first heading in the modal if it exists
this.#headings[0].id = this.#headerId;
}
}
@observes('open')
protected async openChanged(oldValue?: boolean, newValue?: boolean): Promise<void> {
// loosening types to prevent running these effects in unexpected circumstances
// eslint-disable-next-line eqeqeq
if (oldValue == null || newValue == null || oldValue == newValue) {
return;
} else if (this.open) {
// This prevents background scroll
document.body.style.overflow = 'hidden';
await this.updateComplete;
// Set the focus to the container
this.dialog?.focus();
this.dispatchEvent(new ModalOpenEvent(this.#triggerElement));
} else {
// Return scrollability
document.body.style.overflow = 'auto';
await this.updateComplete;
if (this.#triggerElement) {
this.#triggerElement.focus();
}
this.dispatchEvent(this.#cancelling ? new ModalCancelEvent() : new ModalCloseEvent());
}
}
@observes('trigger')
protected triggerChanged(): void {
if (this.trigger) {
this.#triggerElement = (this.getRootNode() as Document | ShadowRoot)
.getElementById(this.trigger);
this.#triggerElement?.addEventListener('click', this.onTriggerClick);
}
}
@bound private onTriggerClick(event: MouseEvent) {
event.preventDefault();
// TODO: in non-modal case, toggle the dialog
this.showModal();
}
@bound private onClick(event: MouseEvent) {
const { open, overlay, dialog } = this;
if (open) {
const path = event.composedPath();
const { closeOnOutsideClick } = this.constructor as typeof PfModal;
if (closeOnOutsideClick && path.includes(overlay!) && !path.includes(dialog!)) {
event.preventDefault();
this.cancel();
}
}
}
@bound private onKeydown(event: KeyboardEvent) {
switch (event.key) {
case 'Tab':
if (event.target === this.closeButton) {
event.preventDefault();
this.dialog?.focus();
}
return;
case 'Escape':
case 'Esc':
event.preventDefault();
this.cancel();
return;
case 'Enter':
if (event.target === this.#triggerElement) {
event.preventDefault();
this.showModal();
}
return;
}
}
private async cancel() {
this.#cancelling = true;
this.open = false;
await this.updateComplete;
this.#cancelling = false;
}
setTrigger(element: HTMLElement): void {
this.#triggerElement = element;
this.#triggerElement.addEventListener('click', this.onTriggerClick);
}
/**
* Manually toggles the modal.
* ```js
* modal.toggle();
* ```
*/
@bound toggle(): void {
this.open = !this.open;
}
/**
* Manually opens the modal.
* ```js
* modal.open();
* ```
*/
@bound show(): void {
this.open = true;
}
@bound showModal(): void {
// TODO: non-modal mode
this.show();
}
/**
* Manually closes the modal.
* ```js
* modal.close();
* ```
* @param returnValue dialog return value
*/
@bound close(returnValue?: string): void {
if (typeof returnValue === 'string') {
this.returnValue = returnValue;
}
this.open = false;
}
}
declare global {
interface HTMLElementTagNameMap {
'pf-modal': PfModal;
}
}