shoelace/src/components/dialog/dialog.ts

318 wiersze
10 KiB
TypeScript
Czysty Zwykły widok Historia

import { LitElement, html, unsafeCSS } from 'lit';
import { customElement, property, query, state } from 'lit/decorators';
2021-03-06 17:01:39 +00:00
import { classMap } from 'lit-html/directives/class-map';
2021-03-15 11:56:15 +00:00
import { ifDefined } from 'lit-html/directives/if-defined';
import { animateTo, stopAnimations } from '../../internal/animate';
2021-03-18 13:04:23 +00:00
import { event, EventEmitter, watch } from '../../internal/decorators';
2021-02-26 14:09:13 +00:00
import { lockBodyScrolling, unlockBodyScrolling } from '../../internal/scroll';
import { hasSlot } from '../../internal/slot';
import { isPreventScrollSupported } from '../../internal/support';
import Modal from '../../internal/modal';
import { setDefaultAnimation, getAnimation } from '../../utilities/animation-registry';
import styles from 'sass:./dialog.scss';
2021-02-26 14:09:13 +00:00
const hasPreventScroll = isPreventScrollSupported();
let id = 0;
/**
* @since 2.0
* @status stable
*
* @dependency sl-icon-button
*
* @slot - The dialog's content.
* @slot label - The dialog's label. Alternatively, you can use the label prop.
* @slot footer - The dialog's footer, usually one or more buttons representing various options.
*
* @part base - The component's base wrapper.
* @part overlay - The overlay.
* @part panel - The dialog panel (where the dialog and its content is rendered).
* @part header - The dialog header.
* @part title - The dialog title.
* @part close-button - The close button.
* @part body - The dialog body.
* @part footer - The dialog footer.
*
* @customProperty --width - The preferred width of the dialog. Note that the dialog will shrink to accommodate smaller screens.
* @customProperty --header-spacing - The amount of padding to use for the header.
* @customProperty --body-spacing - The amount of padding to use for the body.
* @customProperty --footer-spacing - The amount of padding to use for the footer.
*
* @animation dialog.show - The animation to use when showing the dialog.
* @animation dialog.hide - The animation to use when hiding the dialog.
* @animation dialog.overlay.show - The animation to use when showing the dialog's overlay.
* @animation dialog.overlay.hide - The animation to use when hiding the dialog's overlay.
2021-02-26 14:09:13 +00:00
*/
2021-03-18 13:04:23 +00:00
@customElement('sl-dialog')
2021-03-09 00:14:32 +00:00
export default class SlDialog extends LitElement {
2021-03-06 17:01:39 +00:00
static styles = unsafeCSS(styles);
@query('.dialog') dialog: HTMLElement;
@query('.dialog__panel') panel: HTMLElement;
@query('.dialog__overlay') overlay: HTMLElement;
2021-02-26 14:09:13 +00:00
private componentId = `dialog-${++id}`;
private hasInitialized = false;
2021-02-26 14:09:13 +00:00
private modal: Modal;
private originalTrigger: HTMLElement | null;
2021-02-26 14:09:13 +00:00
@state() private hasFooter = false;
2021-03-06 17:01:39 +00:00
2021-02-26 14:09:13 +00:00
/** Indicates whether or not the dialog is open. You can use this in lieu of the show/hide methods. */
2021-03-06 17:01:39 +00:00
@property({ type: Boolean, reflect: true }) open = false;
2021-02-26 14:09:13 +00:00
/**
* The dialog's label as displayed in the header. You should always include a relevant label even when using
* `no-header`, as it is required for proper accessibility.
*/
2021-03-06 17:01:39 +00:00
@property({ reflect: true }) label = '';
2021-02-26 14:09:13 +00:00
/**
* Disables the header. This will also remove the default close button, so please ensure you provide an easy,
* accessible way for users to dismiss the dialog.
*/
2021-03-06 17:01:39 +00:00
@property({ attribute: 'no-header', type: Boolean, reflect: true }) noHeader = false;
/** Emitted when the dialog opens. Calling `event.preventDefault()` will prevent it from being opened. */
@event('sl-show') slShow: EventEmitter<void>;
/** Emitted after the dialog opens and all transitions are complete. */
@event('sl-after-show') slAfterShow: EventEmitter<void>;
/** Emitted when the dialog closes. Calling `event.preventDefault()` will prevent it from being closed. */
@event('sl-hide') slHide: EventEmitter<void>;
/** Emitted after the dialog closes and all transitions are complete. */
@event('sl-after-hide') slAfterHide: EventEmitter<void>;
/**
* Emitted when the dialog opens and the panel gains focus. Calling `event.preventDefault()` will prevent focus and
* allow you to set it on a different element in the dialog, such as an input or button.
*/
@event('sl-initial-focus') slInitialFocus: EventEmitter<void>;
/** Emitted when the overlay is clicked. Calling `event.preventDefault()` will prevent the dialog from closing. */
@event('sl-overlay-dismiss') slOverlayDismiss: EventEmitter<void>;
connectedCallback() {
super.connectedCallback();
2021-02-26 14:09:13 +00:00
this.modal = new Modal(this);
2021-02-26 14:09:13 +00:00
this.handleSlotChange();
// Show on init if open
if (this.open) {
this.show();
}
}
async firstUpdated() {
// Set initial visibility
this.dialog.hidden = !this.open;
// Set the initialized flag after the first update is complete
await this.updateComplete;
this.hasInitialized = true;
}
2021-03-06 17:01:39 +00:00
disconnectedCallback() {
super.disconnectedCallback();
2021-02-26 14:09:13 +00:00
unlockBodyScrolling(this);
}
/** Shows the dialog */
async show() {
if (!this.hasInitialized) {
2021-02-26 14:09:13 +00:00
return;
}
2021-03-06 17:01:39 +00:00
const slShow = this.slShow.emit();
2021-02-26 14:09:13 +00:00
if (slShow.defaultPrevented) {
this.open = false;
return;
}
this.originalTrigger = document.activeElement as HTMLElement;
2021-02-26 14:09:13 +00:00
this.open = true;
this.modal.activate();
lockBodyScrolling(this);
await Promise.all([stopAnimations(this.dialog), stopAnimations(this.overlay)]);
this.dialog.hidden = false;
// Browsers that support el.focus({ preventScroll }) can set initial focus immediately
if (hasPreventScroll) {
const slInitialFocus = this.slInitialFocus.emit();
if (!slInitialFocus.defaultPrevented) {
this.panel.focus({ preventScroll: true });
2021-02-26 14:09:13 +00:00
}
}
const panelAnimation = getAnimation(this, 'dialog.show');
const overlayAnimation = getAnimation(this, 'dialog.overlay.show');
await Promise.all([
animateTo(this.panel, panelAnimation.keyframes, panelAnimation.options),
animateTo(this.overlay, overlayAnimation.keyframes, overlayAnimation.options)
]);
// Browsers that don't support el.focus({ preventScroll }) have to wait for the animation to finish before initial
// focus to prevent scrolling issues. See: https://caniuse.com/mdn-api_htmlelement_focus_preventscroll_option
if (!hasPreventScroll) {
const slInitialFocus = this.slInitialFocus.emit();
if (!slInitialFocus.defaultPrevented) {
this.panel.focus({ preventScroll: true });
}
}
this.slAfterShow.emit();
2021-02-26 14:09:13 +00:00
}
/** Hides the dialog */
async hide() {
if (!this.hasInitialized) {
2021-02-26 14:09:13 +00:00
return;
}
2021-03-06 17:01:39 +00:00
const slHide = this.slHide.emit();
2021-02-26 14:09:13 +00:00
if (slHide.defaultPrevented) {
this.open = true;
return;
}
this.open = false;
this.modal.deactivate();
await Promise.all([stopAnimations(this.dialog), stopAnimations(this.overlay)]);
const panelAnimation = getAnimation(this, 'dialog.hide');
const overlayAnimation = getAnimation(this, 'dialog.overlay.hide');
await Promise.all([
animateTo(this.panel, panelAnimation.keyframes, panelAnimation.options),
animateTo(this.overlay, overlayAnimation.keyframes, overlayAnimation.options)
]);
this.dialog.hidden = true;
unlockBodyScrolling(this);
// Restore focus to the original trigger
const trigger = this.originalTrigger;
if (trigger && typeof trigger.focus === 'function') {
setTimeout(() => trigger.focus());
}
this.slAfterHide.emit();
2021-02-26 14:09:13 +00:00
}
handleCloseClick() {
this.hide();
}
handleKeyDown(event: KeyboardEvent) {
if (event.key === 'Escape') {
event.stopPropagation();
2021-02-26 14:09:13 +00:00
this.hide();
}
}
2021-03-06 20:09:12 +00:00
@watch('open')
handleOpenChange() {
this.open ? this.show() : this.hide();
}
2021-02-26 14:09:13 +00:00
handleOverlayClick() {
2021-03-06 17:01:39 +00:00
const slOverlayDismiss = this.slOverlayDismiss.emit();
2021-02-26 14:09:13 +00:00
if (!slOverlayDismiss.defaultPrevented) {
this.hide();
}
}
handleSlotChange() {
this.hasFooter = hasSlot(this, 'footer');
}
render() {
return html`
<div
part="base"
class=${classMap({
dialog: true,
'dialog--open': this.open,
'dialog--has-footer': this.hasFooter
})}
2021-03-06 17:01:39 +00:00
@keydown=${this.handleKeyDown}
2021-02-26 14:09:13 +00:00
>
2021-03-06 17:01:39 +00:00
<div part="overlay" class="dialog__overlay" @click=${this.handleOverlayClick} tabindex="-1"></div>
2021-02-26 14:09:13 +00:00
<div
part="panel"
class="dialog__panel"
role="dialog"
aria-modal="true"
aria-hidden=${this.open ? 'false' : 'true'}
2021-03-15 11:56:15 +00:00
aria-label=${ifDefined(this.noHeader ? this.label : undefined)}
aria-labelledby=${ifDefined(!this.noHeader ? `${this.componentId}-title` : undefined)}
2021-02-26 14:09:13 +00:00
tabindex="0"
>
${!this.noHeader
? html`
<header part="header" class="dialog__header">
<span part="title" class="dialog__title" id=${`${this.componentId}-title`}>
<slot name="label"> ${this.label || String.fromCharCode(65279)} </slot>
</span>
<sl-icon-button
exportparts="base:close-button"
class="dialog__close"
name="x"
library="system"
2021-03-06 17:01:39 +00:00
@click="${this.handleCloseClick}"
></sl-icon-button>
2021-02-26 14:09:13 +00:00
</header>
`
: ''}
<div part="body" class="dialog__body">
2021-03-06 17:01:39 +00:00
<slot></slot>
2021-02-26 14:09:13 +00:00
</div>
<footer part="footer" class="dialog__footer">
2021-03-06 17:01:39 +00:00
<slot name="footer" @slotchange=${this.handleSlotChange}></slot>
2021-02-26 14:09:13 +00:00
</footer>
</div>
</div>
`;
}
}
setDefaultAnimation('dialog.show', {
keyframes: [
{ opacity: 0, transform: 'scale(0.8)' },
{ opacity: 1, transform: 'scale(1)' }
],
options: { duration: 150 }
});
setDefaultAnimation('dialog.hide', {
keyframes: [
{ opacity: 1, transform: 'scale(1)' },
{ opacity: 0, transform: 'scale(0.8)' }
],
options: { duration: 150 }
});
setDefaultAnimation('dialog.overlay.show', {
keyframes: [{ opacity: 0 }, { opacity: 1 }],
options: { duration: 150 }
});
setDefaultAnimation('dialog.overlay.hide', {
keyframes: [{ opacity: 1 }, { opacity: 0 }],
options: { duration: 150 }
});
2021-03-12 14:09:08 +00:00
declare global {
interface HTMLElementTagNameMap {
'sl-dialog': SlDialog;
}
}