shoelace/src/components/dropdown/dropdown.ts

414 wiersze
13 KiB
TypeScript
Czysty Zwykły widok Historia

import { LitElement, html, unsafeCSS } from 'lit';
import { customElement, property, query } from 'lit/decorators';
2021-03-06 17:01:39 +00:00
import { classMap } from 'lit-html/directives/class-map';
2021-03-18 13:04:23 +00:00
import { event, EventEmitter, watch } from '../../internal/decorators';
2021-02-26 14:09:13 +00:00
import { scrollIntoView } from '../../internal/scroll';
import { getNearestTabbableElement } from '../../internal/tabbable';
import Popover from '../../internal/popover';
2021-05-03 19:08:17 +00:00
import SlMenu from '../menu/menu';
import SlMenuItem from '../menu-item/menu-item';
import styles from 'sass:./dropdown.scss';
2020-07-15 21:30:37 +00:00
let id = 0;
/**
2020-07-17 10:09:10 +00:00
* @since 2.0
2020-07-15 21:30:37 +00:00
* @status stable
*
* @slot trigger - The dropdown's trigger, usually a `<sl-button>` element.
* @slot - The dropdown's content.
*
* @part base - The component's base wrapper.
* @part trigger - The container that wraps the trigger.
* @part panel - The panel that gets shown when the dropdown is open.
*/
2021-03-18 13:04:23 +00:00
@customElement('sl-dropdown')
2021-03-09 00:14:32 +00:00
export default class SlDropdown extends LitElement {
2021-03-06 17:01:39 +00:00
static styles = unsafeCSS(styles);
@query('.dropdown__trigger') trigger: HTMLElement;
@query('.dropdown__panel') panel: HTMLElement;
@query('.dropdown__positioner') positioner: HTMLElement;
2021-02-26 14:09:13 +00:00
private componentId = `dropdown-${++id}`;
private isVisible = false;
private popover: Popover;
2020-07-15 21:30:37 +00:00
/** Indicates whether or not the dropdown is open. You can use this in lieu of the show/hide methods. */
2021-03-06 20:34:33 +00:00
@property({ type: Boolean, reflect: true }) open = false;
2020-07-15 21:30:37 +00:00
/**
* The preferred placement of the dropdown panel. Note that the actual placement may vary as needed to keep the panel
* inside of the viewport.
*/
2021-03-06 17:01:39 +00:00
@property() placement:
2020-07-15 21:30:37 +00:00
| 'top'
| 'top-start'
| 'top-end'
| 'bottom'
| 'bottom-start'
| 'bottom-end'
| 'right'
| 'right-start'
| 'right-end'
| 'left'
| 'left-start'
| 'left-end' = 'bottom-start';
/** Determines whether the dropdown should hide when a menu item is selected. */
2021-03-06 20:34:33 +00:00
@property({ attribute: 'close-on-select', type: Boolean, reflect: true }) closeOnSelect = true;
2020-07-15 21:30:37 +00:00
/** The dropdown will close when the user interacts outside of this element (e.g. clicking). */
2021-03-30 12:29:54 +00:00
@property({ attribute: false }) containingElement: HTMLElement;
2020-07-15 21:30:37 +00:00
/** The distance in pixels from which to offset the panel away from its trigger. */
2021-03-06 17:01:39 +00:00
@property({ type: Number }) distance = 2;
2020-07-15 21:30:37 +00:00
/** The distance in pixels from which to offset the panel along its trigger. */
2021-03-06 17:01:39 +00:00
@property({ type: Number }) skidding = 0;
2020-07-15 21:30:37 +00:00
2020-08-25 21:07:28 +00:00
/**
* Enable this option to prevent the panel from being clipped when the component is placed inside a container with
* `overflow: auto|scroll`.
*/
2021-03-06 17:01:39 +00:00
@property({ type: Boolean }) hoist = false;
/** Emitted when the dropdown opens. Calling `event.preventDefault()` will prevent it from being opened. */
@event('sl-show') slShow: EventEmitter<void>;
/** Emitted after the dropdown opens and all transitions are complete. */
@event('sl-after-show') slAfterShow: EventEmitter<void>;
/** Emitted when the dropdown closes. Calling `event.preventDefault()` will prevent it from being closed. */
@event('sl-hide') slHide: EventEmitter<void>;
/** Emitted after the dropdown closes and all transitions are complete. */
@event('sl-after-hide') slAfterHide: EventEmitter<void>;
2020-07-15 21:30:37 +00:00
2021-03-06 17:01:39 +00:00
connectedCallback() {
super.connectedCallback();
this.handleMenuItemActivate = this.handleMenuItemActivate.bind(this);
this.handlePanelSelect = this.handlePanelSelect.bind(this);
2021-02-26 14:09:13 +00:00
this.handleDocumentKeyDown = this.handleDocumentKeyDown.bind(this);
this.handleDocumentMouseDown = this.handleDocumentMouseDown.bind(this);
if (!this.containingElement) {
this.containingElement = this;
}
}
2021-03-06 17:01:39 +00:00
firstUpdated() {
2020-08-26 10:47:27 +00:00
this.popover = new Popover(this.trigger, this.positioner, {
2020-08-25 21:07:28 +00:00
strategy: this.hoist ? 'fixed' : 'absolute',
2020-07-15 21:30:37 +00:00
placement: this.placement,
distance: this.distance,
2020-08-25 21:07:28 +00:00
skidding: this.skidding,
2020-08-25 21:51:52 +00:00
transitionElement: this.panel,
2021-03-06 17:01:39 +00:00
onAfterHide: () => this.slAfterHide.emit(),
onAfterShow: () => this.slAfterShow.emit(),
2020-07-15 21:30:37 +00:00
onTransitionEnd: () => {
if (!this.open) {
this.panel.scrollTop = 0;
}
}
});
// Show on init if open
if (this.open) {
this.show();
}
}
2021-03-06 17:01:39 +00:00
disconnectedCallback() {
super.disconnectedCallback();
2020-07-15 21:30:37 +00:00
this.hide();
this.popover.destroy();
}
focusOnTrigger() {
2021-02-26 14:09:13 +00:00
const slot = this.trigger.querySelector('slot')!;
const trigger = slot.assignedElements({ flatten: true })[0] as any;
if (trigger && typeof trigger.focus === 'function') {
trigger.focus();
}
}
2020-07-15 21:30:37 +00:00
getMenu() {
2021-02-26 14:09:13 +00:00
const slot = this.panel.querySelector('slot')!;
return slot.assignedElements({ flatten: true }).filter(el => el.tagName.toLowerCase() === 'sl-menu')[0] as SlMenu;
2020-07-15 21:30:37 +00:00
}
handleDocumentKeyDown(event: KeyboardEvent) {
// Close when escape is pressed
if (event.key === 'Escape') {
this.hide();
this.focusOnTrigger();
2020-07-15 21:30:37 +00:00
return;
}
2020-09-03 21:44:52 +00:00
// Handle tabbing
2020-07-15 21:30:37 +00:00
if (event.key === 'Tab') {
2020-10-22 17:42:52 +00:00
// Tabbing within an open menu should close the dropdown and refocus the trigger
if (this.open && document.activeElement?.tagName.toLowerCase() === 'sl-menu-item') {
event.preventDefault();
this.hide();
this.focusOnTrigger();
return;
}
// Tabbing outside of the containing element closes the panel
//
// If the dropdown is used within a shadow DOM, we need to obtain the activeElement within that shadowRoot,
// otherwise `document.activeElement` will only return the name of the parent shadow DOM element.
2020-07-15 21:30:37 +00:00
setTimeout(() => {
const activeElement =
this.containingElement.getRootNode() instanceof ShadowRoot
2021-02-26 14:09:13 +00:00
? document.activeElement?.shadowRoot?.activeElement
: document.activeElement;
if (activeElement?.closest(this.containingElement.tagName.toLowerCase()) !== this.containingElement) {
2020-07-15 21:30:37 +00:00
this.hide();
return;
}
});
}
}
handleDocumentMouseDown(event: MouseEvent) {
2020-09-02 20:59:20 +00:00
// Close when clicking outside of the containing element
const path = event.composedPath() as Array<EventTarget>;
if (!path.includes(this.containingElement)) {
2020-07-15 21:30:37 +00:00
this.hide();
return;
}
}
handleMenuItemActivate(event: CustomEvent) {
2021-02-26 14:09:13 +00:00
const item = event.target as SlMenuItem;
scrollIntoView(item, this.panel);
}
2020-07-15 21:30:37 +00:00
handlePanelSelect(event: CustomEvent) {
const target = event.target as HTMLElement;
// Hide the dropdown when a menu item is selected
if (this.closeOnSelect && target.tagName.toLowerCase() === 'sl-menu') {
this.hide();
this.focusOnTrigger();
2020-07-15 21:30:37 +00:00
}
}
2021-03-06 20:09:12 +00:00
@watch('distance')
@watch('hoist')
@watch('placement')
@watch('skidding')
handlePopoverOptionsChange() {
if (this.popover) {
this.popover.setOptions({
strategy: this.hoist ? 'fixed' : 'absolute',
placement: this.placement,
distance: this.distance,
skidding: this.skidding
});
}
}
2020-09-03 21:44:52 +00:00
handleTriggerClick() {
this.open ? this.hide() : this.show();
}
2020-07-15 21:30:37 +00:00
handleTriggerKeyDown(event: KeyboardEvent) {
2020-09-03 21:44:52 +00:00
const menu = this.getMenu();
2021-02-26 14:09:13 +00:00
const menuItems = menu ? ([...menu.querySelectorAll('sl-menu-item')] as SlMenuItem[]) : [];
2020-10-22 17:42:52 +00:00
const firstMenuItem = menuItems[0];
const lastMenuItem = menuItems[menuItems.length - 1];
2020-09-03 21:44:52 +00:00
// Close when escape or tab is pressed
if (event.key === 'Escape') {
this.focusOnTrigger();
2020-10-22 17:42:52 +00:00
this.hide();
2020-09-03 21:44:52 +00:00
return;
}
// When spacebar/enter is pressed, show the panel but don't focus on the menu. This let's the user press the same
// key again to hide the menu in case they don't want to make a selection.
if ([' ', 'Enter'].includes(event.key)) {
2020-07-15 21:30:37 +00:00
event.preventDefault();
2020-09-03 21:44:52 +00:00
this.open ? this.hide() : this.show();
return;
2020-07-15 21:30:37 +00:00
}
2020-09-03 21:44:52 +00:00
// When up/down is pressed, we make the assumption that the user is familiar with the menu and plans to make a
// selection. Rather than toggle the panel, we focus on the menu (if one exists) and activate the first item for
// faster navigation.
if (['ArrowDown', 'ArrowUp'].includes(event.key)) {
event.preventDefault();
// Show the menu if it's not already open
if (!this.open) {
this.show();
}
2020-10-22 17:42:52 +00:00
// Focus on a menu item
if (event.key === 'ArrowDown' && firstMenuItem) {
firstMenuItem.focus();
2020-10-22 17:42:52 +00:00
return;
}
if (event.key === 'ArrowUp' && lastMenuItem) {
lastMenuItem.focus();
2020-09-03 21:44:52 +00:00
return;
}
}
// Other keys bring focus to the menu and initiate type-to-select behavior
const ignoredKeys = ['Tab', 'Shift', 'Meta', 'Ctrl', 'Alt'];
if (this.open && menu && !ignoredKeys.includes(event.key)) {
menu.typeToSelect(event.key);
return;
}
2020-07-15 21:30:37 +00:00
}
2020-09-11 14:55:24 +00:00
handleTriggerKeyUp(event: KeyboardEvent) {
// Prevent space from triggering a click event in Firefox
if (event.key === ' ') {
event.preventDefault();
}
}
2020-10-16 21:04:35 +00:00
handleTriggerSlotChange() {
this.updateAccessibleTrigger();
}
//
// Slotted triggers can be arbitrary content, but we need to link them to the dropdown panel with `aria-haspopup` and
// `aria-expanded`. These must be applied to the "accessible trigger" (the tabbable portion of the trigger element
// that gets slotted in) so screen readers will understand them. The accessible trigger could be the slotted element,
// a child of the slotted element, or an element in the slotted element's shadow root.
//
// For example, the accessible trigger of an <sl-button> is a <button> located inside its shadow root.
//
// To determine this, we assume the first tabbable element in the trigger slot is the "accessible trigger."
//
updateAccessibleTrigger() {
2021-03-06 20:09:12 +00:00
if (this.trigger) {
const slot = this.trigger.querySelector('slot') as HTMLSlotElement;
const assignedElements = slot.assignedElements({ flatten: true }) as HTMLElement[];
const accessibleTrigger = assignedElements.map(getNearestTabbableElement)[0];
if (accessibleTrigger) {
accessibleTrigger.setAttribute('aria-haspopup', 'true');
accessibleTrigger.setAttribute('aria-expanded', this.open ? 'true' : 'false');
}
2020-10-16 21:04:35 +00:00
}
}
2021-02-26 14:09:13 +00:00
/** Shows the dropdown panel */
show() {
// Prevent subsequent calls to the method, whether manually or triggered by the `open` watcher
if (this.isVisible) {
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.panel.addEventListener('sl-activate', this.handleMenuItemActivate);
this.panel.addEventListener('sl-select', this.handlePanelSelect);
document.addEventListener('keydown', this.handleDocumentKeyDown);
document.addEventListener('mousedown', this.handleDocumentMouseDown);
this.isVisible = true;
this.open = true;
this.popover.show();
}
/** Hides the dropdown panel */
hide() {
// Prevent subsequent calls to the method, whether manually or triggered by the `open` watcher
if (!this.isVisible) {
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.panel.removeEventListener('sl-activate', this.handleMenuItemActivate);
this.panel.removeEventListener('sl-select', this.handlePanelSelect);
document.addEventListener('keydown', this.handleDocumentKeyDown);
document.removeEventListener('mousedown', this.handleDocumentMouseDown);
this.isVisible = false;
this.open = false;
this.popover.hide();
}
/**
* Instructs the dropdown menu to reposition. Useful when the position or size of the trigger changes when the menu
* is activated.
*/
reposition() {
if (!this.open) {
return;
}
this.popover.reposition();
}
2021-03-06 20:09:12 +00:00
@watch('open')
handleOpenChange() {
2021-02-26 14:09:13 +00:00
this.open ? this.show() : this.hide();
2021-03-06 20:09:12 +00:00
this.updateAccessibleTrigger();
2021-02-26 14:09:13 +00:00
}
2020-07-15 21:30:37 +00:00
render() {
2021-02-26 14:09:13 +00:00
return html`
2020-07-15 21:30:37 +00:00
<div
part="base"
2021-02-26 14:09:13 +00:00
id=${this.componentId}
class=${classMap({
2020-07-15 21:30:37 +00:00
dropdown: true,
'dropdown--open': this.open
2021-02-26 14:09:13 +00:00
})}
2020-07-15 21:30:37 +00:00
>
<span
part="trigger"
class="dropdown__trigger"
2021-03-06 17:01:39 +00:00
@click=${this.handleTriggerClick}
@keydown=${this.handleTriggerKeyDown}
@keyup=${this.handleTriggerKeyUp}
2020-07-15 21:30:37 +00:00
>
2021-03-06 17:39:13 +00:00
<slot name="trigger" @slotchange=${this.handleTriggerSlotChange}></slot>
2020-07-15 21:30:37 +00:00
</span>
2021-02-26 14:09:13 +00:00
<!-- Position the panel with a wrapper since the popover makes use of translate. This let's us add transitions
on the panel without interfering with the position. -->
2021-03-06 17:01:39 +00:00
<div class="dropdown__positioner">
2020-08-25 21:51:52 +00:00
<div
part="panel"
class="dropdown__panel"
role="menu"
2021-02-26 14:09:13 +00:00
aria-hidden=${this.open ? 'false' : 'true'}
aria-labelledby=${this.componentId}
2020-08-25 21:51:52 +00:00
>
2021-03-06 17:39:13 +00:00
<slot></slot>
2020-08-25 21:51:52 +00:00
</div>
2020-07-15 21:30:37 +00:00
</div>
</div>
2021-02-26 14:09:13 +00:00
`;
2020-07-15 21:30:37 +00:00
}
}
2021-03-12 14:09:08 +00:00
declare global {
interface HTMLElementTagNameMap {
'sl-dropdown': SlDropdown;
}
}