shoelace/src/components/menu/menu.ts

224 wiersze
6.6 KiB
TypeScript
Czysty Zwykły widok Historia

import { html, LitElement } from 'lit';
2021-05-27 21:00:43 +00:00
import { customElement, query } from 'lit/decorators.js';
2022-03-24 11:48:03 +00:00
import type SlMenuItem from '~/components/menu-item/menu-item';
import { emit } from '~/internal/event';
import { hasFocusVisible } from '~/internal/focus-visible';
import { getTextContent } from '~/internal/slot';
2021-07-10 00:45:44 +00:00
import styles from './menu.styles';
export interface MenuSelectEventDetail {
item: SlMenuItem;
}
2020-07-15 21:30:37 +00:00
/**
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.
*
2022-03-09 20:54:18 +00:00
* @csspart base - The component's internal wrapper.
2020-07-15 21:30:37 +00:00
*/
2021-03-18 13:04:23 +00:00
@customElement('sl-menu')
2021-03-09 00:14:32 +00:00
export default class SlMenu extends LitElement {
2021-07-10 00:45:44 +00:00
static styles = styles;
2021-03-06 17:01:39 +00:00
@query('.menu') menu: HTMLElement;
@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;
2021-11-12 14:50:50 +00:00
firstUpdated() {
this.setAttribute('role', 'menu');
}
2021-07-08 21:23:47 +00:00
getAllItems(options: { includeDisabled: boolean } = { includeDisabled: true }) {
return [...this.defaultSlot.assignedElements({ flatten: true })].filter((el: HTMLElement) => {
if (el.getAttribute('role') !== 'menuitem') {
return false;
}
if (!options.includeDisabled && (el as SlMenuItem).disabled) {
2021-07-08 21:23:47 +00:00
return false;
}
return true;
}) 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() {
return this.getAllItems({ includeDisabled: false }).find(i => i.getAttribute('tabindex') === '0');
}
/**
* @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) {
const items = this.getAllItems({ includeDisabled: false });
const activeItem = item.disabled ? items[0] : item;
2021-07-08 21:23:47 +00:00
// Update tab indexes
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) {
2021-07-08 21:23:47 +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
2021-08-26 12:35:36 +00:00
// Restore focus in browsers that don't support :focus-visible when using the keyboard
if (!hasFocusVisible) {
items.forEach(item => item.classList.remove('sl-focus-invisible'));
2021-08-26 12:35:36 +00:00
}
2021-08-20 13:55:32 +00:00
2021-07-08 21:23:47 +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) {
emit(this, 'sl-select', { detail: { item } });
2020-07-15 21:30:37 +00:00
}
}
2021-08-26 12:35:36 +00:00
handleKeyUp() {
// Restore focus in browsers that don't support :focus-visible when using the keyboard
if (!hasFocusVisible) {
const items = this.getAllItems();
items.forEach(item => {
item.classList.remove('sl-focus-invisible');
});
2021-08-26 12:35:36 +00:00
}
}
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)) {
2021-07-08 21:23:47 +00:00
const items = this.getAllItems({ includeDisabled: false });
const activeItem = this.getCurrentItem();
2022-01-19 14:37:07 +00:00
let index = activeItem ? items.indexOf(activeItem) : 0;
2020-07-15 21:30:37 +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') {
2021-07-08 21:23:47 +00:00
index = items.length - 1;
2020-07-15 21:30:37 +00:00
}
if (index < 0) {
index = 0;
}
if (index > items.length - 1) {
index = items.length - 1;
}
2020-07-15 21:30:37 +00:00
2021-07-08 21:23:47 +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);
2021-08-26 12:35:36 +00:00
// Hide focus in browsers that don't support :focus-visible when using the mouse
if (!hasFocusVisible) {
target.classList.add('sl-focus-invisible');
}
2021-07-08 21:23:47 +00:00
}
}
handleSlotChange() {
2021-07-08 21:23:47 +00:00
const items = this.getAllItems({ includeDisabled: false });
// Reset the roving tab index when the slotted items change
if (items.length > 0) {
2021-07-08 21:23:47 +00:00
this.setCurrentItem(items[0]);
}
}
2020-07-15 21:30:37 +00:00
render() {
2021-02-26 14:09:13 +00:00
return html`
2021-07-08 21:23:47 +00:00
<div
part="base"
class="menu"
@click=${this.handleClick}
@keydown=${this.handleKeyDown}
2021-08-26 12:35:36 +00:00
@keyup=${this.handleKeyUp}
2021-07-08 21:23:47 +00:00
@mousedown=${this.handleMouseDown}
>
<slot @slotchange=${this.handleSlotChange}></slot>
2020-07-15 21:30:37 +00:00
</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-menu': SlMenu;
}
}