shoelace/src/components/menu/menu.ts

200 wiersze
5.9 KiB
TypeScript
Czysty Zwykły widok Historia

2022-08-17 15:37:37 +00:00
import { html } from 'lit';
2021-05-27 21:00:43 +00:00
import { customElement, query } from 'lit/decorators.js';
2022-08-17 15:37:37 +00:00
import ShoelaceElement from '../../internal/shoelace-element';
2022-03-24 12:01:09 +00:00
import { getTextContent } from '../../internal/slot';
2021-07-10 00:45:44 +00:00
import styles from './menu.styles';
2022-08-08 14:15:41 +00:00
import type SlMenuItem from '../menu-item/menu-item';
import type { CSSResultGroup } from 'lit';
export interface MenuSelectEventDetail {
item: SlMenuItem;
}
2020-07-15 21:30:37 +00:00
/**
Enrich components `@summary` with description from docs (#962) * keep header styles with repositioned description text * `animated-image` move description to component * code style * `avatar` add summary from docs * `badge` add summary from docs * `breadcrumb` add summary from docs * `button` add summary from docs * lead sentence is now part of the header * `button-group` add summary from docs * `card` add summary from docs * `checkbox` add summary from docs * `color-picker` add summary from docs * `details` add summary from docs * `dialog` add summary from docs * `divider` add summary from docs * `drawer` add summary from docs * `dropdown` add summary from docs * `format-bytes` add summary from docs * `format-date` add summary from docs * `format-number` add summary from docs * `icon` add summary from docs * `icon-button` add summary from docs * `image-comparer` add summary from docs * `include` add summary from docs * `input` add summary from docs * `menu` add summary from docs * `menu-item` add summary from docs * `menu-label` add summary from docs * `popup` add summary from docs * `progressbar` add summary from docs * `progress-ring` add summary from docs * `radio` add summary from docs * `radio-button` add summary from docs * `range` add summary from docs * `rating` add summary from docs * `relative-time` add summary from docs * `select` add summary from docs * `skeleton` add summary from docs * `spinner` add summary from docs * `split-panel` add summary from docs * `switch` add summary from docs * `tab-group` add summary from docs * `tag` add summary from docs * `textarea` add summary from docs * `tooltip` add summary from docs * `visually-hidden` add summary from docs * `animation` add summary from docs * `breadcrumb-item` add summary from docs * `mutation-observer` add summary from docs * `radio-group` add summary from docs * `resize-observer` add summary from docs * `tab` add summary from docs * `tab-panel` add summary from docs * `tree` add summary from docs * `tree-item` add summary from docs * remove `title` for further usage of `Sl` classnames in docs * revert: use markdown parser for component summary
2022-10-21 13:56:35 +00:00
* @summary Menus provide a list of options for the user to choose from.
*
2020-07-17 10:09:10 +00:00
* @since 2.0
2020-07-15 21:30:37 +00:00
* @status stable
*
2021-09-29 12:03:03 +00:00
* @slot - The menu's content, including menu items, menu labels, and dividers.
2020-07-15 21:30:37 +00:00
*
2021-06-25 20:25:46 +00:00
* @event {{ item: SlMenuItem }} sl-select - Emitted when a menu item is selected.
2020-07-15 21:30:37 +00:00
*/
2021-03-18 13:04:23 +00:00
@customElement('sl-menu')
2022-08-17 15:37:37 +00:00
export default class SlMenu extends ShoelaceElement {
static styles: CSSResultGroup = styles;
2021-03-06 17:01:39 +00:00
@query('slot') defaultSlot: HTMLSlotElement;
2020-07-15 21:30:37 +00:00
2021-02-26 14:09:13 +00:00
private typeToSelectString = '';
private typeToSelectTimeout: number;
2022-07-20 20:53:59 +00:00
connectedCallback() {
super.connectedCallback();
2021-11-12 14:50:50 +00:00
this.setAttribute('role', 'menu');
}
2022-08-02 12:26:03 +00:00
getAllItems(options: { includeDisabled: boolean } = { includeDisabled: true }) {
2021-07-08 21:23:47 +00:00
return [...this.defaultSlot.assignedElements({ flatten: true })].filter((el: HTMLElement) => {
2022-08-02 12:26:03 +00:00
if (el.getAttribute('role') !== 'menuitem') {
return false;
}
if (!options.includeDisabled && (el as SlMenuItem).disabled) {
return false;
}
return true;
2021-07-08 21:23:47 +00:00
}) as SlMenuItem[];
}
/**
* @internal Gets the current menu item, which is the menu item that has `tabindex="0"` within the roving tab index.
* The menu item may or may not have focus, but for keyboard interaction purposes it's considered the "active" item.
*/
getCurrentItem() {
2022-08-02 12:26:03 +00:00
return this.getAllItems({ includeDisabled: false }).find(i => i.getAttribute('tabindex') === '0');
2021-07-08 21:23:47 +00:00
}
/**
* @internal Sets the current menu item to the specified element. This sets `tabindex="0"` on the target element and
* `tabindex="-1"` to all other items. This method must be called prior to setting focus on a menu item.
*/
setCurrentItem(item: SlMenuItem) {
2022-08-02 12:26:03 +00:00
const items = this.getAllItems({ includeDisabled: false });
const activeItem = item.disabled ? items[0] : item;
2021-07-08 21:23:47 +00:00
// Update tab indexes
2022-05-31 12:31:41 +00:00
items.forEach(i => {
i.setAttribute('tabindex', i === activeItem ? '0' : '-1');
});
2021-07-08 21:23:47 +00:00
}
/**
* Initiates type-to-select logic, which automatically selects an option based on what the user is currently typing.
2022-03-04 15:12:05 +00:00
* The event passed will be used to append the appropriate characters to the internal query and the selection will be
* updated. After a brief period, the internal query is cleared automatically. This is useful for enabling
* type-to-select behavior when the menu doesn't have focus.
*/
2022-03-04 15:12:05 +00:00
typeToSelect(event: KeyboardEvent) {
2022-08-02 12:26:03 +00:00
const items = this.getAllItems({ includeDisabled: false });
clearTimeout(this.typeToSelectTimeout);
2022-03-03 20:48:20 +00:00
this.typeToSelectTimeout = window.setTimeout(() => (this.typeToSelectString = ''), 1000);
2022-03-04 15:12:05 +00:00
if (event.key === 'Backspace') {
if (event.metaKey || event.ctrlKey) {
this.typeToSelectString = '';
} else {
this.typeToSelectString = this.typeToSelectString.slice(0, -1);
}
2022-03-03 20:48:20 +00:00
} else {
2022-03-04 15:12:05 +00:00
this.typeToSelectString += event.key.toLowerCase();
2022-03-03 20:48:20 +00:00
}
2021-08-20 13:55:32 +00:00
2022-05-31 12:31:41 +00:00
for (const item of items) {
const slot = item.shadowRoot?.querySelector<HTMLSlotElement>('slot:not([name])');
const label = getTextContent(slot).toLowerCase().trim();
if (label.startsWith(this.typeToSelectString)) {
2021-07-26 12:23:46 +00:00
this.setCurrentItem(item);
2021-08-26 12:35:36 +00:00
// Set focus here to force the browser to show :focus-visible styles
item.focus();
break;
}
}
}
2020-07-15 21:30:37 +00:00
handleClick(event: MouseEvent) {
const target = event.target as HTMLElement;
const item = target.closest('sl-menu-item');
2020-07-15 21:30:37 +00:00
if (item?.disabled === false) {
2022-09-16 20:21:40 +00:00
this.emit('sl-select', { detail: { item } });
2020-07-15 21:30:37 +00:00
}
}
handleKeyDown(event: KeyboardEvent) {
// Make a selection when pressing enter
if (event.key === 'Enter') {
2021-07-08 21:23:47 +00:00
const item = this.getCurrentItem();
2020-07-15 21:30:37 +00:00
event.preventDefault();
// Simulate a click to support @click handlers on menu items that also work with the keyboard
item?.click();
2020-07-15 21:30:37 +00:00
}
// Prevent scrolling when space is pressed
if (event.key === ' ') {
event.preventDefault();
}
// Move the selection when pressing down or up
if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
2022-08-02 12:26:03 +00:00
const items = this.getAllItems({ includeDisabled: false });
2021-07-08 21:23:47 +00:00
const activeItem = this.getCurrentItem();
2022-05-31 12:31:41 +00:00
let index = activeItem ? items.indexOf(activeItem) : 0;
2020-07-15 21:30:37 +00:00
2022-05-31 12:31:41 +00:00
if (items.length > 0) {
2020-07-15 21:30:37 +00:00
event.preventDefault();
if (event.key === 'ArrowDown') {
index++;
} else if (event.key === 'ArrowUp') {
index--;
} else if (event.key === 'Home') {
index = 0;
} else if (event.key === 'End') {
2022-05-31 12:31:41 +00:00
index = items.length - 1;
2020-07-15 21:30:37 +00:00
}
if (index < 0) {
2022-05-31 12:31:41 +00:00
index = items.length - 1;
}
2022-05-31 12:31:41 +00:00
if (index > items.length - 1) {
2022-03-24 12:50:44 +00:00
index = 0;
}
2020-07-15 21:30:37 +00:00
2022-05-31 12:31:41 +00:00
this.setCurrentItem(items[index]);
items[index].focus();
2020-07-15 21:30:37 +00:00
return;
}
}
2022-03-04 15:12:05 +00:00
this.typeToSelect(event);
}
2020-07-15 21:30:37 +00:00
2021-07-08 21:23:47 +00:00
handleMouseDown(event: MouseEvent) {
const target = event.target as HTMLElement;
if (target.getAttribute('role') === 'menuitem') {
this.setCurrentItem(target as SlMenuItem);
}
}
handleSlotChange() {
2022-08-02 12:26:03 +00:00
const items = this.getAllItems({ includeDisabled: false });
2021-07-08 21:23:47 +00:00
// Reset the roving tab index when the slotted items change
2022-05-31 12:31:41 +00:00
if (items.length > 0) {
this.setCurrentItem(items[0]);
2021-07-08 21:23:47 +00:00
}
}
2020-07-15 21:30:37 +00:00
render() {
2021-02-26 14:09:13 +00:00
return html`
2022-08-10 15:01:13 +00:00
<slot
@slotchange=${this.handleSlotChange}
2021-07-08 21:23:47 +00:00
@click=${this.handleClick}
@keydown=${this.handleKeyDown}
@mousedown=${this.handleMouseDown}
2022-08-10 15:01:13 +00:00
></slot>
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-menu': SlMenu;
}
}