shoelace/src/components/select/select.ts

512 wiersze
16 KiB
TypeScript
Czysty Zwykły widok Historia

import { LitElement, TemplateResult, html, unsafeCSS } from 'lit';
2021-05-27 21:00:43 +00:00
import { customElement, property, query, state } from 'lit/decorators.js';
2021-03-06 17:01:39 +00:00
import { classMap } from 'lit-html/directives/class-map';
import { ifDefined } from 'lit-html/directives/if-defined';
import { emit } from '../../internal/event';
import { watch } from '../../internal/watch';
import { getLabelledBy, renderFormControl } from '../../internal/form-control';
2021-02-26 14:09:13 +00:00
import { getTextContent } from '../../internal/slot';
import { hasSlot } from '../../internal/slot';
2021-05-27 20:29:10 +00:00
import type SlDropdown from '../dropdown/dropdown';
import type SlIconButton from '../icon-button/icon-button';
import type SlMenu from '../menu/menu';
import type SlMenuItem from '../menu-item/menu-item';
2021-05-03 19:08:17 +00:00
import styles from 'sass:./select.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
*
2021-02-26 14:09:13 +00:00
* @dependency sl-dropdown
* @dependency sl-icon
* @dependency sl-icon-button
* @dependency sl-menu
* @dependency sl-tag
*
2021-06-25 20:25:46 +00:00
* @slot - The select's options in the form of menu items.
* @slot label - The select's label. Alternatively, you can use the label prop.
* @slot help-text - Help text that describes how to use the select.
2020-07-15 21:30:37 +00:00
*
2021-06-25 20:25:46 +00:00
* @event sl-clear - Emitted when the clear button is activated.
* @event sl-change - Emitted when the control's value changes.
* @event sl-focus - Emitted when the control gains focus.
2021-07-08 21:23:47 +00:00
* @event sl-blur - Emitted when the control loses focus.
*
2021-06-25 20:25:46 +00:00
* @csspart base - The component's base wrapper.
* @csspart clear-button - The input's clear button, exported from <sl-input>.
* @csspart form-control - The form control that wraps the label, input, and help text.
* @csspart help-text - The select's help text.
* @csspart icon - The select's icon.
* @csspart label - The select's label.
* @csspart menu - The select menu, a <sl-menu> element.
* @csspart tag - The multiselect option, a <sl-tag> element.
* @csspart tags - The container in which multiselect options are rendered.
*
2021-06-25 20:25:46 +00:00
* @cssproperty --focus-ring - The focus ring style to use when the control receives focus, a `box-shadow` property.
2020-07-15 21:30:37 +00:00
*/
2021-03-18 13:04:23 +00:00
@customElement('sl-select')
2021-03-09 00:14:32 +00:00
export default class SlSelect extends LitElement {
2021-03-06 17:01:39 +00:00
static styles = unsafeCSS(styles);
@query('.select') dropdown: SlDropdown;
2021-06-05 16:29:57 +00:00
@query('.select__box') box: SlDropdown;
2021-03-06 17:01:39 +00:00
@query('.select__hidden-select') input: HTMLInputElement;
@query('.select__menu') menu: SlMenu;
2021-02-26 14:09:13 +00:00
private inputId = `select-${++id}`;
private helpTextId = `select-help-text-${id}`;
2021-02-26 14:09:13 +00:00
private labelId = `select-label-${id}`;
private resizeObserver: ResizeObserver;
@state() private hasFocus = false;
@state() private hasHelpTextSlot = false;
@state() private hasLabelSlot = false;
@state() private isOpen = false;
@state() private displayLabel = '';
@state() private displayTags: TemplateResult[] = [];
2021-03-06 17:01:39 +00:00
2021-02-26 14:09:13 +00:00
/** Enables multiselect. With this enabled, value will be an array. */
2021-07-01 00:04:46 +00:00
@property({ type: Boolean, reflect: true }) multiple = false;
2020-07-15 21:30:37 +00:00
/**
* The maximum number of tags to show when `multiple` is true. After the maximum, "+n" will be shown to indicate the
* number of additional items that are selected. Set to -1 to remove the limit.
*/
2021-07-01 00:04:46 +00:00
@property({ attribute: 'max-tags-visible', type: Number }) maxTagsVisible = 3;
2020-07-15 21:30:37 +00:00
2021-02-26 14:09:13 +00:00
/** Disables the select control. */
2021-07-01 00:04:46 +00:00
@property({ type: Boolean, reflect: true }) disabled = false;
2020-07-15 21:30:37 +00:00
/** The select's name. */
2021-07-01 00:04:46 +00:00
@property() name = '';
2020-07-15 21:30:37 +00:00
/** The select's placeholder text. */
2021-07-01 00:04:46 +00:00
@property() placeholder = '';
2020-07-15 21:30:37 +00:00
/** The select's size. */
2021-03-06 17:01:39 +00:00
@property() size: 'small' | 'medium' | 'large' = 'medium';
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-07-01 00:04:46 +00:00
@property({ type: Boolean }) hoist = false;
2020-08-25 21:07:28 +00:00
2020-07-15 21:30:37 +00:00
/** The value of the control. This will be a string or an array depending on `multiple`. */
2021-03-06 17:01:39 +00:00
@property() value: string | Array<string> = '';
2021-03-06 20:18:54 +00:00
2021-02-26 14:09:13 +00:00
/** Draws a pill-style select with rounded edges. */
2021-07-01 00:04:46 +00:00
@property({ type: Boolean, reflect: true }) pill = false;
2020-07-15 21:30:37 +00:00
2020-12-23 20:47:13 +00:00
/** The select's label. Alternatively, you can use the label slot. */
2021-04-02 11:47:25 +00:00
@property() label: string;
2021-03-06 20:18:54 +00:00
2020-12-23 20:47:13 +00:00
/** The select's help text. Alternatively, you can use the help-text slot. */
2021-03-06 17:01:39 +00:00
@property({ attribute: 'help-text' }) helpText: string;
2021-03-06 20:18:54 +00:00
2020-08-25 13:30:28 +00:00
/** The select's required attribute. */
2021-07-01 00:04:46 +00:00
@property({ type: Boolean, reflect: true }) required = false;
2020-08-25 13:30:28 +00:00
2021-02-26 14:09:13 +00:00
/** Adds a clear button when the select is populated. */
2021-07-01 00:04:46 +00:00
@property({ type: Boolean }) clearable = false;
/** This will be true when the control is in an invalid state. Validity is determined by the `required` prop. */
2021-07-01 00:04:46 +00:00
@property({ type: Boolean, reflect: true }) invalid = false;
2021-03-06 17:01:39 +00:00
connectedCallback() {
super.connectedCallback();
this.handleSlotChange = this.handleSlotChange.bind(this);
2020-07-15 21:30:37 +00:00
this.resizeObserver = new ResizeObserver(() => this.resizeMenu());
2021-06-02 12:47:55 +00:00
this.updateComplete.then(() => {
this.resizeObserver.observe(this);
this.shadowRoot!.addEventListener('slotchange', this.handleSlotChange);
this.syncItemsFromValue();
});
2020-07-15 21:30:37 +00:00
}
2021-06-16 12:42:02 +00:00
firstUpdated() {
this.invalid = !this.input.checkValidity();
}
2021-03-06 17:01:39 +00:00
disconnectedCallback() {
super.disconnectedCallback();
2021-06-02 12:47:55 +00:00
this.resizeObserver.unobserve(this);
2021-02-26 14:09:13 +00:00
this.shadowRoot!.removeEventListener('slotchange', this.handleSlotChange);
2020-12-23 20:47:13 +00:00
}
/** Checks for validity and shows the browser's validation message if the control is invalid. */
2021-02-26 14:09:13 +00:00
reportValidity() {
return this.input.reportValidity();
}
/** Sets a custom validation message. If `message` is not empty, the field will be considered invalid. */
2021-02-26 14:09:13 +00:00
setCustomValidity(message: string) {
this.input.setCustomValidity(message);
this.invalid = !this.input.checkValidity();
}
2021-02-26 14:09:13 +00:00
getItemLabel(item: SlMenuItem) {
const slot = item.shadowRoot!.querySelector('slot:not([name])') as HTMLSlotElement;
2020-07-15 21:30:37 +00:00
return getTextContent(slot);
}
getItems() {
2021-02-26 14:09:13 +00:00
return [...this.querySelectorAll('sl-menu-item')] as SlMenuItem[];
2020-07-15 21:30:37 +00:00
}
getValueAsArray() {
2021-06-04 12:56:35 +00:00
// Single selects use '' as an empty selection value, so convert this to [] for an empty multi select
if (this.multiple && this.value === '') {
return [];
}
2020-07-15 21:30:37 +00:00
return Array.isArray(this.value) ? this.value : [this.value];
}
2020-12-11 22:09:10 +00:00
handleBlur() {
2021-06-05 16:29:57 +00:00
// Don't blur if the control is open. We'll move focus back once it closes.
if (!this.isOpen) {
this.hasFocus = false;
emit(this, 'sl-blur');
2021-06-05 16:29:57 +00:00
}
2020-07-15 21:30:37 +00:00
}
2020-12-11 22:09:10 +00:00
handleClearClick(event: MouseEvent) {
event.stopPropagation();
this.value = this.multiple ? [] : '';
emit(this, 'sl-clear');
this.syncItemsFromValue();
}
@watch('disabled')
2021-03-06 19:39:48 +00:00
handleDisabledChange() {
if (this.disabled && this.isOpen) {
this.dropdown.hide();
}
2021-06-25 23:22:05 +00:00
// Disabled form controls are always valid, so we need to recheck validity when the state changes
if (this.input) {
this.input.disabled = this.disabled;
this.invalid = !this.input.checkValidity();
}
2021-03-06 19:39:48 +00:00
}
handleFocus() {
2021-06-05 16:29:57 +00:00
if (!this.hasFocus) {
this.hasFocus = true;
emit(this, 'sl-focus');
2021-06-05 16:29:57 +00:00
}
2021-03-06 19:39:48 +00:00
}
2020-10-22 17:42:37 +00:00
handleKeyDown(event: KeyboardEvent) {
2020-12-11 22:09:10 +00:00
const target = event.target as HTMLElement;
2020-10-22 17:42:37 +00:00
const items = this.getItems();
const firstItem = items[0];
const lastItem = items[items.length - 1];
2020-12-11 22:09:10 +00:00
// Ignore key presses on tags
if (target.tagName.toLowerCase() === 'sl-tag') {
return;
}
// Tabbing out of the control closes it
if (event.key === 'Tab') {
if (this.isOpen) {
this.dropdown.hide();
}
return;
}
2020-10-22 17:42:37 +00:00
2020-12-11 22:09:10 +00:00
// Up/down opens the menu
2020-10-22 17:42:37 +00:00
if (['ArrowDown', 'ArrowUp'].includes(event.key)) {
event.preventDefault();
// Show the menu if it's not already open
if (!this.isOpen) {
this.dropdown.show();
}
// Focus on a menu item
if (event.key === 'ArrowDown' && firstItem) {
2021-07-08 21:23:47 +00:00
this.menu.setCurrentItem(firstItem);
firstItem.focus();
2020-10-22 17:42:37 +00:00
return;
}
if (event.key === 'ArrowUp' && lastItem) {
2021-07-08 21:23:47 +00:00
this.menu.setCurrentItem(lastItem);
lastItem.focus();
2020-10-22 17:42:37 +00:00
return;
}
}
2020-08-29 15:26:14 +00:00
2021-06-10 13:33:02 +00:00
// All other "printable" keys open the menu and initiate type to select
if (!this.isOpen && event.key.length === 1) {
2020-12-11 22:09:10 +00:00
event.stopPropagation();
event.preventDefault();
this.dropdown.show();
this.menu.typeToSelect(event.key);
}
2020-07-15 21:30:37 +00:00
}
handleLabelClick() {
2021-02-26 14:09:13 +00:00
const box = this.shadowRoot?.querySelector('.select__box') as HTMLElement;
box.focus();
2020-07-15 21:30:37 +00:00
}
handleMenuSelect(event: CustomEvent) {
const item = event.detail.item;
if (this.multiple) {
this.value = this.value.includes(item.value)
? (this.value as []).filter(v => v !== item.value)
: [...this.value, item.value];
} else {
this.value = item.value;
}
this.syncItemsFromValue();
}
2021-05-27 20:29:10 +00:00
handleMenuShow() {
2020-07-15 21:30:37 +00:00
this.resizeMenu();
this.isOpen = true;
}
handleMenuHide() {
this.isOpen = false;
2021-06-05 16:29:57 +00:00
// Restore focus on the box after the menu is hidden
this.box.focus();
2020-07-15 21:30:37 +00:00
}
@watch('multiple')
2021-03-06 19:39:48 +00:00
handleMultipleChange() {
// Cast to array | string based on `this.multiple`
const value = this.getValueAsArray();
this.value = this.multiple ? value : value[0] || '';
this.syncItemsFromValue();
}
@watch('helpText')
@watch('label')
async handleSlotChange() {
2021-02-26 14:09:13 +00:00
this.hasHelpTextSlot = hasSlot(this, 'help-text');
this.hasLabelSlot = hasSlot(this, 'label');
// Wait for items to render before gathering labels otherwise the slot won't exist
const items = this.getItems();
await Promise.all(items.map(item => item.render)).then(() => this.syncItemsFromValue());
2020-07-15 21:30:37 +00:00
}
2020-12-11 22:09:10 +00:00
handleTagInteraction(event: KeyboardEvent | MouseEvent) {
2020-08-27 12:20:36 +00:00
// Don't toggle the menu when a tag's clear button is activated
const path = event.composedPath() as Array<EventTarget>;
2021-02-26 14:09:13 +00:00
const clearButton = path.find((el: SlIconButton) => {
2020-08-27 12:20:36 +00:00
if (el instanceof HTMLElement) {
const element = el as HTMLElement;
2021-01-20 17:09:48 +00:00
return element.classList.contains('tag__clear');
2020-08-27 12:20:36 +00:00
}
2021-02-26 14:09:13 +00:00
return false;
2020-08-27 12:20:36 +00:00
});
if (clearButton) {
event.stopPropagation();
}
}
2021-06-15 13:26:35 +00:00
@watch('value', { waitUntilFirstUpdate: true })
2021-06-16 12:42:02 +00:00
async handleValueChange() {
2021-03-06 19:39:48 +00:00
this.syncItemsFromValue();
2021-06-16 12:42:02 +00:00
await this.updateComplete;
this.invalid = !this.input.checkValidity();
emit(this, 'sl-change');
2021-03-06 19:39:48 +00:00
}
2020-07-15 21:30:37 +00:00
resizeMenu() {
2021-02-26 14:09:13 +00:00
const box = this.shadowRoot?.querySelector('.select__box') as HTMLElement;
this.menu.style.width = `${box.clientWidth}px`;
2021-03-06 17:01:39 +00:00
if (this.dropdown) {
this.dropdown.reposition();
}
2020-07-15 21:30:37 +00:00
}
syncItemsFromValue() {
const items = this.getItems();
const value = this.getValueAsArray();
// Sync checked states
items.map(item => (item.checked = value.includes(item.value)));
2021-03-22 17:14:32 +00:00
// Sync display label and tags
2020-07-15 21:30:37 +00:00
if (this.multiple) {
2021-03-22 17:14:32 +00:00
const checkedItems = items.filter(item => value.includes(item.value)) as SlMenuItem[];
2020-07-15 21:30:37 +00:00
2021-03-22 17:14:32 +00:00
this.displayLabel = checkedItems[0] ? this.getItemLabel(checkedItems[0]) : '';
2021-02-26 14:09:13 +00:00
this.displayTags = checkedItems.map((item: SlMenuItem) => {
return html`
2020-07-15 21:30:37 +00:00
<sl-tag
exportparts="base:tag"
2020-07-15 21:30:37 +00:00
type="info"
2021-02-26 14:09:13 +00:00
size=${this.size}
2021-03-15 12:03:32 +00:00
?pill=${this.pill}
2020-07-15 21:30:37 +00:00
clearable
2021-03-06 17:01:39 +00:00
@click=${this.handleTagInteraction}
@keydown=${this.handleTagInteraction}
@sl-clear=${(event: CustomEvent) => {
event.stopPropagation();
2020-12-11 22:09:10 +00:00
if (!this.disabled) {
item.checked = false;
this.syncValueFromItems();
}
2020-07-15 21:30:37 +00:00
}}
>
2021-02-26 14:09:13 +00:00
${this.getItemLabel(item)}
2020-07-15 21:30:37 +00:00
</sl-tag>
2021-02-26 14:09:13 +00:00
`;
2020-07-15 21:30:37 +00:00
});
if (this.maxTagsVisible > 0 && this.displayTags.length > this.maxTagsVisible) {
const total = this.displayTags.length;
2020-12-11 22:09:10 +00:00
this.displayLabel = '';
2020-07-15 21:30:37 +00:00
this.displayTags = this.displayTags.slice(0, this.maxTagsVisible);
2021-02-26 14:09:13 +00:00
this.displayTags.push(html`
<sl-tag exportparts="base:tag" type="info" size=${this.size}> +${total - this.maxTagsVisible} </sl-tag>
`);
2020-07-15 21:30:37 +00:00
}
} else {
const checkedItem = items.filter(item => item.value === value[0])[0];
2021-03-22 17:14:32 +00:00
2020-07-15 21:30:37 +00:00
this.displayLabel = checkedItem ? this.getItemLabel(checkedItem) : '';
this.displayTags = [];
}
}
syncValueFromItems() {
const items = this.getItems();
const checkedItems = items.filter(item => item.checked);
const checkedValues = checkedItems.map(item => item.value);
if (this.multiple) {
this.value = (this.value as []).filter(val => checkedValues.includes(val));
} else {
this.value = checkedValues.length > 0 ? checkedValues[0] : '';
}
}
render() {
2020-12-11 22:09:10 +00:00
const hasSelection = this.multiple ? this.value.length > 0 : this.value !== '';
2021-02-26 14:09:13 +00:00
return renderFormControl(
{
inputId: this.inputId,
label: this.label,
labelId: this.labelId,
hasLabelSlot: this.hasLabelSlot,
helpTextId: this.helpTextId,
helpText: this.helpText,
hasHelpTextSlot: this.hasHelpTextSlot,
size: this.size,
onLabelClick: () => this.handleLabelClick()
},
html`
2020-07-15 21:30:37 +00:00
<sl-dropdown
part="base"
2021-02-26 14:09:13 +00:00
.hoist=${this.hoist}
2021-07-01 21:23:16 +00:00
.stayOpenOnSelect=${this.multiple}
2021-02-26 14:09:13 +00:00
.containingElement=${this}
2021-05-27 20:29:10 +00:00
?disabled=${this.disabled}
2021-02-26 14:09:13 +00:00
class=${classMap({
2020-07-15 21:30:37 +00:00
select: true,
'select--open': this.isOpen,
2020-08-27 16:23:24 +00:00
'select--empty': this.value?.length === 0,
2020-07-15 21:30:37 +00:00
'select--focused': this.hasFocus,
2020-12-11 22:09:10 +00:00
'select--clearable': this.clearable,
2020-07-15 21:30:37 +00:00
'select--disabled': this.disabled,
'select--multiple': this.multiple,
2021-03-06 17:01:39 +00:00
'select--has-tags': this.multiple && this.displayTags.length > 0,
2020-12-11 22:09:10 +00:00
'select--placeholder-visible': this.displayLabel === '',
2020-07-15 21:30:37 +00:00
'select--small': this.size === 'small',
'select--medium': this.size === 'medium',
'select--large': this.size === 'large',
2020-12-11 22:09:10 +00:00
'select--pill': this.pill,
'select--invalid': this.invalid
2021-02-26 14:09:13 +00:00
})}
2021-03-06 17:01:39 +00:00
@sl-show=${this.handleMenuShow}
@sl-hide=${this.handleMenuHide}
2020-07-15 21:30:37 +00:00
>
2020-12-11 22:09:10 +00:00
<div
2020-07-15 21:30:37 +00:00
slot="trigger"
2021-02-26 14:09:13 +00:00
id=${this.inputId}
2020-12-11 22:09:10 +00:00
class="select__box"
role="combobox"
aria-labelledby=${ifDefined(
getLabelledBy({
label: this.label,
labelId: this.labelId,
hasLabelSlot: this.hasLabelSlot,
helpText: this.helpText,
helpTextId: this.helpTextId,
hasHelpTextSlot: this.hasHelpTextSlot
})
)}
2020-12-11 22:09:10 +00:00
aria-haspopup="true"
2021-02-26 14:09:13 +00:00
aria-expanded=${this.isOpen ? 'true' : 'false'}
tabindex=${this.disabled ? '-1' : '0'}
2021-03-06 17:01:39 +00:00
@blur=${this.handleBlur}
@focus=${this.handleFocus}
@keydown=${this.handleKeyDown}
2020-07-15 21:30:37 +00:00
>
2020-12-11 22:09:10 +00:00
<div class="select__label">
2021-02-26 14:09:13 +00:00
${this.displayTags.length
? html` <span part="tags" class="select__tags"> ${this.displayTags} </span> `
: this.displayLabel || this.placeholder}
2020-12-11 22:09:10 +00:00
</div>
2021-02-26 14:09:13 +00:00
${this.clearable && hasSelection
? html`
<sl-icon-button
exportparts="base:clear-button"
class="select__clear"
name="x-circle"
library="system"
2021-03-06 17:01:39 +00:00
@click=${this.handleClearClick}
2021-02-26 14:09:13 +00:00
tabindex="-1"
2021-03-06 17:01:39 +00:00
></sl-icon-button>
2021-02-26 14:09:13 +00:00
`
: ''}
2020-07-15 21:30:37 +00:00
2021-04-09 17:51:48 +00:00
<span part="icon" class="select__icon" aria-hidden="true">
<sl-icon name="chevron-down" library="system"></sl-icon>
2020-07-15 21:30:37 +00:00
</span>
2020-12-11 22:09:10 +00:00
2021-03-06 17:01:39 +00:00
<!-- The hidden input tricks the browser's built-in validation so it works as expected. We use an input
2021-02-26 14:09:13 +00:00
instead of a select because, otherwise, iOS will show a list of options during validation. -->
<input
2020-12-11 22:09:10 +00:00
class="select__hidden-select"
aria-hidden="true"
2021-03-06 20:22:59 +00:00
?required=${this.required}
2021-02-26 14:09:13 +00:00
.value=${hasSelection ? '1' : ''}
tabindex="-1"
/>
2020-12-11 22:09:10 +00:00
</div>
2020-07-15 21:30:37 +00:00
2021-03-06 17:01:39 +00:00
<sl-menu part="menu" class="select__menu" @sl-select=${this.handleMenuSelect}>
<slot @slotchange=${this.handleSlotChange}></slot>
2020-07-15 21:30:37 +00:00
</sl-menu>
</sl-dropdown>
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-select': SlSelect;
}
}