import { classMap } from 'lit/directives/class-map.js'; import { customElement, property, query, state } from 'lit/decorators.js'; import { HasSlotController } from '../internal/slot'; import { html } from 'lit'; import { watch } from '../internal/watch'; import NileElement from '../internal/nile-element'; import styles from './nile-radio-group.css'; import type { CSSResultGroup, PropertyValues } from 'lit'; import type NileRadio from '../nile-radio/nile-radio'; import { Nile_Events } from '../internal/enum'; /** * @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. * * @dependency nile-button-group * * @slot - The default slot where `` or `` elements are placed. * @slot label - The radio group's label. Required for proper accessibility. Alternatively, you can use the `label` * attribute. * * @event change - Emitted when the radio group's selected value changes. * @event input - Emitted when the radio group receives user input. * @event invalid - Emitted when the form control has been checked for validity and its constraints aren't satisfied. * @csspart button-group - The button group that wraps radio buttons. * @csspart button-group__base - The button group's `base` part. */ @customElement('nile-radio-group') export class NileRadioGroup extends NileElement { static styles: CSSResultGroup = styles; private readonly hasSlotController = new HasSlotController(this, 'help-text', 'label'); private customValidityMessage = ''; @query('slot:not([name])') defaultSlot: HTMLSlotElement; @state() private hasButtonGroup = false; @state() defaultValue = ''; /** * The radio group's label. Required for proper accessibility. If you need to display HTML, use the `label` slot * instead. */ @property() label = ''; /** The name of the radio group, submitted as a name/value pair with form data. */ @property() name = 'option'; /** The current value of the radio group, submitted as a name/value pair with form data. */ @property({ reflect: true }) value = ''; /** * By default, form controls are associated with the nearest containing `
` 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 = ''; /** Ensures a child radio is checked before allowing the containing form to submit. */ @property({ type: Boolean, reflect: true }) required = false; /** Used to show radio in inline or not */ @property({ type: Boolean, reflect: true }) labelInline = false; /** Used to disabled or not */ @property({ type: Boolean, reflect: true }) disabled = false; @property({ attribute: 'help-text', reflect: true }) helpText = ''; @property({ attribute: 'error-message', reflect: true }) errorMessage = ''; /** The radio's labelborder for whole gp. */ @property({ type: Boolean, reflect: true }) islabelborder = false; /** Allow the radio to be unchecked. */ @property({ type: Boolean, reflect: true, attribute: true }) allowUncheckGroup = false; connectedCallback() { super.connectedCallback(); this.defaultValue = this.value; this.handleInitialDisabledState(); this.emit('nile-init'); } disconnectedCallback() { super.disconnectedCallback(); this.emit('nile-destroy'); } private getAllRadios() { return [...this.querySelectorAll('nile-radio')]; } private handleRadioClick(event: MouseEvent) { const target = (event.target as HTMLElement).closest('nile-radio')!; const radios = this.getAllRadios(); const oldValue = this.value; if (target.disabled || this.disabled) { return; } this.value = target.value; if (!this.allowUncheckGroup) { radios.forEach(radio => { radio.checked = radio === target; }); } if (!this.allowUncheckGroup && this.value !== oldValue) { this.emit('change', { value: this.value}); this.emit('input'); this.emit(Nile_Events.NILE_CHANGE, { value: this.value}); this.emit(Nile_Events.NILE_INPUT, { value: this.value}); } else if (this.allowUncheckGroup) { this.emit('change', { value: this.value , checked: target.checked}); this.emit('input'); this.emit(Nile_Events.NILE_CHANGE, { value: this.value , checked: target.checked}); this.emit(Nile_Events.NILE_INPUT, { value: this.value , checked: target.checked}); } } protected updated(changedProperties: PropertyValues): void { super.updated(changedProperties); if (changedProperties.has('allowUncheckGroup')) { if (this.allowUncheckGroup) { this.getAllRadios().forEach(radio => { radio.allowUncheck = true; }); } } } @watch('disabled', { waitUntilFirstUpdate: true }) handleDisabledChange() { this.getAllRadios().forEach(radio => { radio.disabled = this.disabled; }); } private handleInitialDisabledState() { this.getAllRadios().forEach(radio => { radio.disabled = radio.hasAttribute('disabled') ? radio.disabled : this.disabled; }); } private handleKeyDown(event: KeyboardEvent) { if (this.disabled) return; 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; const oldValue = this.value; 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; } }); 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(); } if (this.value !== oldValue) { this.emit('change'); this.emit('input'); this.emit(Nile_Events.NILE_CHANGE, { value: this.value}); this.emit(Nile_Events.NILE_INPUT, { value: this.value}); } event.preventDefault(); } private handleLabelClick() { if (this.disabled) return; 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(); } } private handleSlotChange() { const radios = this.getAllRadios(); radios.forEach(radio => { radio.checked = radio.value === this.value; if (this.islabelborder) { radio.islabelborder=true; } }); if (this.disabled) { radios.forEach(r => (r.tabIndex = -1)); return; } const nile_radio_check='nile-radio-button'; this.hasButtonGroup = radios.some(radio => radio.tagName.toLowerCase() === nile_radio_check); if (radios.length > 0 && !radios.some(radio => radio.checked)) { if (this.hasButtonGroup) { const buttonRadio = radios[0].shadowRoot!.querySelector('button')!; buttonRadio.tabIndex = 0; } else { radios[0].tabIndex = 0; } } if (this.hasButtonGroup) { const buttonGroup = this.shadowRoot?.querySelector('nile-button-group'); } } private updateCheckedRadio() { const radios = this.getAllRadios(); radios.forEach(radio => (radio.checked = radio.value === this.value)); } @watch('value') handleValueChange() { if (this.hasUpdated) { this.updateCheckedRadio(); } } render() { const hasLabelSlot = this.hasSlotController.test('label'); const hasHelpTextSlot = this.hasSlotController.test('help-text'); const hasLabelSuffixSlot = this.hasSlotController.test('label-suffix'); const hasLabel = this.label ? true : !!hasLabelSlot; const hasHelpText = this.helpText ? true : false; const hasErrorMessage = this.errorMessage ? true : false; const defaultSlot = html` `; return html`
${hasLabelSuffixSlot ? html` ` : ``}
${this.hasButtonGroup ? html` ${defaultSlot} ` : html`
${defaultSlot}
`}
${ hasHelpText ? html` ${this.helpText} ` : `` } ${ hasErrorMessage ? html` ${this.errorMessage} ` : `` }
`; } } export default NileRadioGroup; declare global { interface HTMLElementTagNameMap { 'nile-radio-group': NileRadioGroup; } }