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

366 wiersze
12 KiB
TypeScript
Czysty Zwykły widok Historia

2023-01-13 20:43:55 +00:00
import '../button-group/button-group';
2021-09-29 12:40:26 +00:00
import { classMap } from 'lit/directives/class-map.js';
2023-01-13 20:43:55 +00:00
import { customElement, property, query, state } from 'lit/decorators.js';
import {
customErrorValidityState,
FormControlController,
validValidityState,
valueMissingValidityState
} from '../../internal/form';
2022-11-09 20:27:51 +00:00
import { HasSlotController } from '../../internal/slot';
2023-01-13 20:43:55 +00:00
import { html } from 'lit';
2022-08-30 14:17:46 +00:00
import { watch } from '../../internal/watch';
2023-01-13 20:43:55 +00:00
import ShoelaceElement from '../../internal/shoelace-element';
2021-07-10 00:45:44 +00:00
import styles from './radio-group.styles';
2023-01-13 20:43:55 +00:00
import type { CSSResultGroup } from 'lit';
import type { ShoelaceFormControl } from '../../internal/shoelace-element';
2022-08-08 14:15:41 +00:00
import type SlRadio from '../radio/radio';
2023-01-13 20:43:55 +00:00
import type SlRadioButton from '../radio-button/radio-button';
2021-04-09 12:15:33 +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 Radio groups are used to group multiple [radios](/components/radio) or [radio buttons](/components/radio-button) so they function as a single form control.
2023-01-12 15:26:25 +00:00
* @documentation https://shoelace.style/components/radio-group
2021-04-09 12:15:33 +00:00
* @status stable
2023-01-12 15:26:25 +00:00
* @since 2.0
2021-04-09 12:15:33 +00:00
*
2022-03-15 21:42:59 +00:00
* @dependency sl-button-group
*
2022-12-06 16:18:14 +00:00
* @slot - The default slot where `<sl-radio>` or `<sl-radio-button>` elements are placed.
* @slot label - The radio group's 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-12-07 22:40:46 +00:00
* @event sl-input - Emitted when the radio group receives user input.
* @event sl-invalid - Emitted when the form control has been checked for validity and its constraints aren't satisfied.
*
2022-12-06 16:18:14 +00:00
* @csspart form-control - The form control that wraps the label, input, and help text.
2022-11-09 20:27:51 +00:00
* @csspart form-control-label - The label's wrapper.
* @csspart form-control-input - The input's wrapper.
* @csspart form-control-help-text - The help text's wrapper.
2022-03-15 21:42:59 +00:00
* @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 ShoelaceElement implements ShoelaceFormControl {
static styles: CSSResultGroup = styles;
2021-04-09 12:15:33 +00:00
2023-02-07 20:57:50 +00:00
protected readonly formControlController = new FormControlController(this);
2022-11-09 20:27:51 +00:00
private readonly hasSlotController = new HasSlotController(this, 'help-text', 'label');
2023-01-10 20:05:07 +00:00
private customValidityMessage = '';
private validationTimeout: number;
2021-07-12 14:48:38 +00:00
@query('slot:not([name])') defaultSlot: HTMLSlotElement;
2023-01-10 20:05:07 +00:00
@query('.radio-group__validation-input') validationInput: HTMLInputElement;
2021-07-12 14:48:38 +00:00
@state() private hasButtonGroup = false;
@state() private errorMessage = '';
@state() defaultValue = '';
2022-03-15 21:42:59 +00:00
2022-08-03 15:06:52 +00:00
/**
2022-12-06 16:18:14 +00:00
* The radio group's label. Required for proper accessibility. If you need to display HTML, use the `label` slot
2022-08-03 15:06:52 +00:00
* instead.
*/
2021-07-01 00:04:46 +00:00
@property() label = '';
2021-04-09 12:15:33 +00:00
2022-12-06 16:18:14 +00:00
/** The radio groups's help text. If you need to display HTML, use the `help-text` slot instead. */
2022-11-09 20:27:51 +00:00
@property({ attribute: 'help-text' }) helpText = '';
2022-12-06 16:18:14 +00:00
/** The name of the radio group, submitted as a name/value pair with form data. */
@property() name = 'option';
2022-12-06 16:18:14 +00:00
/** The current value of the radio group, submitted as a name/value pair with form data. */
@property({ reflect: true }) value = '';
2023-01-13 17:34:33 +00:00
/**
* By default, form controls are associated with the nearest containing `<form>` element. This attribute allows you
* to place the form control outside of a form and associate it with the form that has this `id`. The form must be in
* the same document or shadow root for this to work.
*/
@property({ reflect: true }) form = '';
2022-06-21 13:21:33 +00:00
/** 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
/** Gets the validity state object */
get validity() {
const isRequiredAndEmpty = this.required && !this.value;
const hasCustomValidityMessage = this.customValidityMessage !== '';
if (hasCustomValidityMessage) {
return customErrorValidityState;
} else if (isRequiredAndEmpty) {
return valueMissingValidityState;
}
return validValidityState;
}
/** Gets the validation message */
get validationMessage() {
const isRequiredAndEmpty = this.required && !this.value;
const hasCustomValidityMessage = this.customValidityMessage !== '';
if (hasCustomValidityMessage) {
return this.customValidityMessage;
} else if (isRequiredAndEmpty) {
return this.validationInput.validationMessage;
}
return '';
}
2022-03-14 21:47:02 +00:00
connectedCallback() {
super.connectedCallback();
this.defaultValue = this.value;
}
2022-11-09 21:07:34 +00:00
firstUpdated() {
this.formControlController.updateValidity();
2022-11-09 21:07:34 +00:00
}
2023-01-03 20:04:07 +00:00
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
}
2023-01-03 20:04:07 +00:00
private handleRadioClick(event: MouseEvent) {
2023-01-17 15:45:19 +00:00
const target = (event.target as HTMLElement).closest<SlRadio | SlRadioButton>('sl-radio, sl-radio-button')!;
2022-12-07 22:40:46 +00:00
const radios = this.getAllRadios();
const oldValue = this.value;
2022-03-14 21:47:02 +00:00
if (target.disabled) {
return;
2022-03-14 21:47:02 +00:00
}
this.value = target.value;
radios.forEach(radio => (radio.checked = radio === target));
2022-12-07 22:40:46 +00:00
if (this.value !== oldValue) {
this.emit('sl-change');
this.emit('sl-input');
}
2022-03-14 21:47:02 +00:00
}
2023-01-03 20:04:07 +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;
2022-12-07 22:40:46 +00:00
const oldValue = this.value;
let index = radios.indexOf(checkedRadio) + incr;
2022-12-07 22:40:46 +00:00
if (index < 0) {
index = radios.length - 1;
}
2022-12-07 22:40:46 +00:00
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
}
2022-12-07 22:40:46 +00:00
if (this.value !== oldValue) {
this.emit('sl-change');
this.emit('sl-input');
}
event.preventDefault();
2022-03-14 21:47:02 +00:00
}
2023-01-03 20:04:07 +00:00
private handleLabelClick() {
2022-11-09 20:27:51 +00:00
const radios = this.getAllRadios();
const checked = radios.find(radio => radio.checked);
const radioToFocus = checked || radios[0];
// Move focus to the checked radio (or the first one if none are checked) when clicking the label
if (radioToFocus) {
radioToFocus.focus();
}
}
2023-01-03 20:04:07 +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;
}
}
}
private handleInvalid(event: Event) {
this.formControlController.setValidity(false);
2023-02-14 20:12:21 +00:00
this.formControlController.emitInvalidEvent(event);
}
2023-01-03 20:04:07 +00:00
private updateCheckedRadio() {
const radios = this.getAllRadios();
radios.forEach(radio => (radio.checked = radio.value === this.value));
this.formControlController.setValidity(this.validity.valid);
2021-07-12 14:48:38 +00:00
}
2023-01-03 20:04:07 +00:00
@watch('value')
handleValueChange() {
if (this.hasUpdated) {
this.updateCheckedRadio();
}
}
/** Checks for validity but does not show a validation message. Returns `true` when valid and `false` when invalid. */
2023-01-03 20:04:07 +00:00
checkValidity() {
2023-01-10 20:05:07 +00:00
const isRequiredAndEmpty = this.required && !this.value;
const hasCustomValidityMessage = this.customValidityMessage !== '';
2023-01-03 20:04:07 +00:00
2023-01-10 20:05:07 +00:00
if (isRequiredAndEmpty || hasCustomValidityMessage) {
2023-02-14 20:12:21 +00:00
this.formControlController.emitInvalidEvent();
2023-01-10 20:05:07 +00:00
return false;
2023-01-03 20:04:07 +00:00
}
2023-01-10 20:05:07 +00:00
return true;
2023-01-03 20:04:07 +00:00
}
2023-01-10 20:05:07 +00:00
/** Sets a custom validation message. Pass an empty string to restore validity. */
setCustomValidity(message = '') {
this.customValidityMessage = message;
this.errorMessage = message;
this.validationInput.setCustomValidity(message);
this.formControlController.updateValidity();
2023-01-03 20:04:07 +00:00
}
/** Checks for validity and shows the browser's validation message if the control is invalid. */
2023-01-03 20:04:07 +00:00
reportValidity(): boolean {
const isValid = this.validity.valid;
2023-01-10 20:05:07 +00:00
this.errorMessage = this.customValidityMessage || isValid ? '' : this.validationInput.validationMessage;
this.formControlController.setValidity(isValid);
this.validationInput.hidden = true;
clearTimeout(this.validationTimeout);
if (!isValid) {
// Show the browser's constraint validation message
this.validationInput.hidden = false;
this.validationInput.reportValidity();
this.validationTimeout = setTimeout(() => (this.validationInput.hidden = true), 10000) as unknown as number;
2023-01-03 20:04:07 +00:00
}
2023-01-10 20:05:07 +00:00
return isValid;
2023-01-03 20:04:07 +00:00
}
2021-04-09 12:15:33 +00:00
render() {
2022-11-09 20:27:51 +00:00
const hasLabelSlot = this.hasSlotController.test('label');
const hasHelpTextSlot = this.hasSlotController.test('help-text');
const hasLabel = this.label ? true : !!hasLabelSlot;
const hasHelpText = this.helpText ? true : !!hasHelpTextSlot;
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
2022-11-09 20:27:51 +00:00
part="form-control"
2021-04-09 12:15:33 +00:00
class=${classMap({
2022-11-09 20:27:51 +00:00
'form-control': true,
'form-control--medium': true,
'form-control--radio-group': true,
'form-control--has-label': hasLabel,
'form-control--has-help-text': hasHelpText
2021-04-09 12:15:33 +00:00
})}
2022-11-09 20:27:51 +00:00
role="radiogroup"
aria-labelledby="label"
aria-describedby="help-text"
aria-errormessage="error-message"
2021-04-09 12:15:33 +00:00
>
2022-11-09 20:27:51 +00:00
<label
part="form-control-label"
id="label"
class="form-control__label"
aria-hidden=${hasLabel ? 'false' : 'true'}
@click=${this.handleLabelClick}
>
2021-04-09 12:15:33 +00:00
<slot name="label">${this.label}</slot>
2022-11-09 20:27:51 +00:00
</label>
<div part="form-control-input" class="form-control-input">
<div class="visually-hidden">
<div id="error-message" aria-live="assertive">${this.errorMessage}</div>
<label class="radio-group__validation">
<input
type="text"
class="radio-group__validation-input"
?required=${this.required}
tabindex="-1"
hidden
@invalid=${this.handleInvalid}
2022-11-09 20:27:51 +00:00
/>
</label>
</div>
${this.hasButtonGroup
? html`
<sl-button-group part="button-group" exportparts="base:button-group__base">
${defaultSlot}
</sl-button-group>
`
: defaultSlot}
</div>
2022-12-02 22:03:59 +00:00
<slot
name="help-text"
2022-11-09 20:27:51 +00:00
part="form-control-help-text"
id="help-text"
class="form-control__help-text"
aria-hidden=${hasHelpText ? 'false' : 'true'}
>
2022-12-02 22:03:59 +00:00
${this.helpText}
</slot>
2021-04-09 12:15:33 +00:00
</fieldset>
`;
2022-11-09 20:27:51 +00:00
/* eslint-enable lit-a11y/click-events-have-key-events */
2021-04-09 12:15:33 +00:00
}
}
declare global {
interface HTMLElementTagNameMap {
'sl-radio-group': SlRadioGroup;
}
}