shoelace/src/components/radio-group/radio-group.ts

261 wiersze
7.8 KiB
TypeScript
Czysty Zwykły widok Historia

import { html, LitElement } from 'lit';
2022-03-15 21:42:59 +00:00
import { customElement, property, query, state } from 'lit/decorators.js';
2021-09-29 12:40:26 +00:00
import { classMap } from 'lit/directives/class-map.js';
import { emit } from 'src/internal/event';
import { FormSubmitController } from 'src/internal/form';
import { watch } from 'src/internal/watch';
2022-03-24 12:01:09 +00:00
import '../../components/button-group/button-group';
2021-07-10 00:45:44 +00:00
import styles from './radio-group.styles';
2022-03-24 12:01:09 +00:00
import type SlRadio from '../../components/radio/radio';
import type SlRadioButton from '../radio-button/radio-button';
import type { CSSResultGroup } from 'lit';
2021-04-09 12:15:33 +00:00
/**
* @since 2.0
* @status stable
*
2022-03-15 21:42:59 +00:00
* @dependency sl-button-group
*
2021-06-25 20:25:46 +00:00
* @slot - The default slot where radio controls are placed.
2022-08-03 15:06:52 +00:00
* @slot label - The radio group label. Required for proper accessibility. Alternatively, you can use the `label` attribute.
2021-04-09 12:15:33 +00:00
*
* @event sl-change - Emitted when the radio group's selected value changes.
*
2022-03-09 20:54:18 +00:00
* @csspart base - The component's internal wrapper.
2022-03-15 21:42:59 +00:00
* @csspart label - The radio group's label.
* @csspart button-group - The button group that wraps radio buttons.
* @csspart button-group__base - The button group's `base` part.
2021-04-09 12:15:33 +00:00
*/
@customElement('sl-radio-group')
export default class SlRadioGroup extends LitElement {
static styles: CSSResultGroup = styles;
2021-04-09 12:15:33 +00:00
protected readonly formSubmitController = new FormSubmitController(this, {
defaultValue: (control: SlRadioGroup) => control.defaultValue
});
2021-07-12 14:48:38 +00:00
@query('slot:not([name])') defaultSlot: HTMLSlotElement;
@query('.radio-group__validation-input') input: HTMLInputElement;
2021-07-12 14:48:38 +00:00
@state() private hasButtonGroup = false;
@state() private errorMessage = '';
@state() private customErrorMessage = '';
@state() private defaultValue = '';
2022-03-15 21:42:59 +00:00
2022-08-03 15:06:52 +00:00
/**
* The radio group label. Required for proper accessibility. If you need to display HTML, you can use the `label` slot
* instead.
*/
2021-07-01 00:04:46 +00:00
@property() label = '';
2021-04-09 12:15:33 +00:00
/** The selected value of the control. */
@property({ reflect: true }) value = '';
/** The name assigned to the radio controls. */
@property() name = 'option';
2022-08-03 15:55:24 +00:00
/**
* This will be true when the control is in an invalid state. Validity is determined by props such as `type`,
* `required`, `minlength`, `maxlength`, and `pattern` using the browser's constraint validation API.
*/
@property({ type: Boolean, reflect: true }) invalid = false;
2021-08-27 13:00:01 +00:00
/** Shows the fieldset and legend that surrounds the radio group. */
2022-06-21 13:21:33 +00:00
@property({ type: Boolean, attribute: 'fieldset', reflect: true }) fieldset = false;
/** Ensures a child radio is checked before allowing the containing form to submit. */
@property({ type: Boolean, reflect: true }) required = false;
2021-04-09 12:15:33 +00:00
@watch('value')
handleValueChange() {
if (this.hasUpdated) {
emit(this, 'sl-change');
this.updateCheckedRadio();
}
}
2022-03-14 21:47:02 +00:00
connectedCallback() {
super.connectedCallback();
this.defaultValue = this.value;
}
2022-08-03 15:55:24 +00:00
/** Sets a custom validation message. If `message` is not empty, the field will be considered invalid. */
setCustomValidity(message = '') {
this.customErrorMessage = message;
this.errorMessage = message;
if (!message) {
2022-08-03 15:55:24 +00:00
this.invalid = false;
} else {
2022-08-03 15:55:24 +00:00
this.invalid = true;
this.input.setCustomValidity(message);
}
}
get validity(): ValidityState {
const hasMissingData = !((this.value && this.required) || !this.required);
const hasCustomError = this.customErrorMessage !== '';
return {
badInput: false,
customError: hasCustomError,
patternMismatch: false,
rangeOverflow: false,
rangeUnderflow: false,
stepMismatch: false,
tooLong: false,
tooShort: false,
typeMismatch: false,
valid: hasMissingData || hasCustomError ? false : true,
valueMissing: !hasMissingData
};
}
2022-08-03 15:55:24 +00:00
/** Checks for validity and shows the browser's validation message if the control is invalid. */
reportValidity(): boolean {
const validity = this.validity;
this.errorMessage = this.customErrorMessage || validity.valid ? '' : this.input.validationMessage;
2022-08-03 15:55:24 +00:00
this.invalid = !validity.valid;
if (!validity.valid) {
this.showNativeErrorMessage();
}
2022-08-03 15:55:24 +00:00
return !this.invalid;
}
private getAllRadios() {
2022-08-04 13:17:08 +00:00
return [...this.querySelectorAll<SlRadio | SlRadioButton>('sl-radio, sl-radio-button')];
2022-03-14 21:47:02 +00:00
}
private handleRadioClick(event: MouseEvent) {
const target = event.target as SlRadio | SlRadioButton;
2022-03-14 21:47:02 +00:00
if (target.disabled) {
return;
2022-03-14 21:47:02 +00:00
}
this.value = target.value;
const radios = this.getAllRadios();
radios.forEach(radio => (radio.checked = radio === target));
2022-03-14 21:47:02 +00:00
}
private handleKeyDown(event: KeyboardEvent) {
if (!['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' '].includes(event.key)) {
return;
}
const radios = this.getAllRadios().filter(radio => !radio.disabled);
const checkedRadio = radios.find(radio => radio.checked) ?? radios[0];
const incr = event.key === ' ' ? 0 : ['ArrowUp', 'ArrowLeft'].includes(event.key) ? -1 : 1;
let index = radios.indexOf(checkedRadio) + incr;
if (index < 0) {
index = radios.length - 1;
}
if (index > radios.length - 1) {
index = 0;
}
this.getAllRadios().forEach(radio => {
radio.checked = false;
if (!this.hasButtonGroup) {
radio.tabIndex = -1;
}
});
2022-03-14 21:47:02 +00:00
this.value = radios[index].value;
radios[index].checked = true;
if (!this.hasButtonGroup) {
radios[index].tabIndex = 0;
radios[index].focus();
} else {
radios[index].shadowRoot!.querySelector('button')!.focus();
2022-08-01 16:08:31 +00:00
}
event.preventDefault();
2022-03-14 21:47:02 +00:00
}
private handleSlotChange() {
2022-03-14 21:47:02 +00:00
const radios = this.getAllRadios();
2022-08-03 15:55:24 +00:00
radios.forEach(radio => (radio.checked = radio.value === this.value));
this.hasButtonGroup = radios.some(radio => radio.tagName.toLowerCase() === 'sl-radio-button');
if (!radios.some(radio => radio.checked)) {
if (this.hasButtonGroup) {
const buttonRadio = radios[0].shadowRoot!.querySelector('button')!;
buttonRadio.tabIndex = 0;
} else {
radios[0].tabIndex = 0;
}
2022-07-20 17:55:12 +00:00
}
if (this.hasButtonGroup) {
const buttonGroup = this.shadowRoot?.querySelector('sl-button-group');
if (buttonGroup) {
buttonGroup.disableRole = true;
}
}
}
2022-08-04 13:22:13 +00:00
private showNativeErrorMessage() {
this.input.hidden = false;
this.input.reportValidity();
setTimeout(() => (this.input.hidden = true), 10000);
}
private updateCheckedRadio() {
const radios = this.getAllRadios();
radios.forEach(radio => (radio.checked = radio.value === this.value));
2021-07-12 14:48:38 +00:00
}
2021-04-09 12:15:33 +00:00
render() {
2022-03-15 21:42:59 +00:00
const defaultSlot = html`
<slot
@click=${this.handleRadioClick}
@keydown=${this.handleKeyDown}
@slotchange=${this.handleSlotChange}
role="presentation"
></slot>
2022-03-15 21:42:59 +00:00
`;
2021-04-09 12:15:33 +00:00
return html`
<fieldset
part="base"
role="radiogroup"
aria-errormessage="radio-error-message"
2022-08-03 15:55:24 +00:00
aria-invalid="${this.invalid}"
2021-04-09 12:15:33 +00:00
class=${classMap({
'radio-group': true,
2022-06-21 13:21:33 +00:00
'radio-group--has-fieldset': this.fieldset,
'radio-group--required': this.required
2021-04-09 12:15:33 +00:00
})}
>
<legend part="label" class="radio-group__label">
<slot name="label">${this.label}</slot>
</legend>
<div class="visually-hidden">
<div id="radio-error-message" aria-live="assertive">${this.errorMessage}</div>
<label class="radio-group__validation visually-hidden">
<input type="text" class="radio-group__validation-input" ?required=${this.required} tabindex="-1" hidden />
</label>
</div>
2022-03-15 21:42:59 +00:00
${this.hasButtonGroup
? html`<sl-button-group part="button-group">${defaultSlot}</sl-button-group>`
: defaultSlot}
2021-04-09 12:15:33 +00:00
</fieldset>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'sl-radio-group': SlRadioGroup;
}
}