import { html, unsafeCSS } from 'lit';
import { PieElement } from '@justeattakeaway/pie-webc-core/src/internals/PieElement';
import {
property, query, state,
} from 'lit/decorators.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { live } from 'lit/directives/live.js';
import { classMap } from 'lit/directives/class-map.js';
import { consume } from '@lit/context';
import {
FormControlMixin,
RtlMixin,
wrapNativeEvent,
validPropertyValues,
safeCustomElement,
ariaContext,
type ContextualAria,
} from '@justeattakeaway/pie-webc-core';
import { type RadioProps, defaultProps, statusTypes } from './defs';
import styles from './radio.scss?inline';
// Valid values available to consumers
export * from './defs';
const componentSelector = 'pie-radio';
/**
* @tagname pie-radio
* @event {InputEvent} input - Should fire whenever a user toggles the radio.
* @event {CustomEvent} change - Fires when the radio is checked (but not when unchecked).
*/
@safeCustomElement('pie-radio')
export class PieRadio extends FormControlMixin(RtlMixin(PieElement)) implements RadioProps {
@state()
private _disabledByParent = false;
@state()
private _isAnimationAllowed = false;
// Optional ARIA supplied by an ancestor (for example a `pie-list-item`). A radio's host carries
// `role="radio"`, so it is the element assistive tech announces and where the name/description
// belong. Undefined when standalone, so a consumer's own aria-* is left untouched.
@consume({ context: ariaContext, subscribe: true })
@state()
private _contextAria?: ContextualAria;
@property({ type: Boolean, reflect: true })
public checked = defaultProps.checked;
@property({ type: Boolean, reflect: true })
public defaultChecked = defaultProps.defaultChecked;
@property({ type: Boolean, reflect: true })
public disabled = defaultProps.disabled;
@property({ type: String, reflect: true })
public name: RadioProps['name'];
@property({ type: Boolean, reflect: true })
public required = defaultProps.required;
@property({ type: String })
public value!: RadioProps['value'];
@property({ type: String })
@validPropertyValues(componentSelector, statusTypes, defaultProps.status)
public status = defaultProps.status;
@query('input[type="radio"]')
private _radio!: HTMLInputElement;
private _abortController!: AbortController;
connectedCallback () : void {
super.connectedCallback();
this._abortController = new AbortController();
const { signal } = this._abortController;
this.setAttribute('role', 'radio');
this.addEventListener('pie-radio-group-disabled', (e: CustomEventInit) => { this._disabledByParent = e.detail.disabled; }, { signal });
// This is required to ensure that programmatic clicks correctly select the radio input in the template. This is primarily
// how screen readers such as Apple VoiceOver interact with the component.
// Without this, double tapping the radio input would not select it when using VoiceOver.
this.addEventListener('click', this._handleClick, { signal });
}
disconnectedCallback () : void {
super.disconnectedCallback();
this._abortController.abort();
}
/**
* Ensures that the form value is in sync with the component.
*/
private _handleFormAssociation () {
if (this.form && this.name) {
this._internals.setFormValue(this.checked ? this.value : null);
}
}
/**
* Captures the native change event and wraps it in a custom event.
* @param {Event} event - This should be the change event that was listened for on an input element with `type="radio"`.
*/
private _handleChange (event: Event) {
const { checked } = event?.currentTarget as HTMLInputElement;
this.checked = checked;
// This is because some events set `composed` to `false`.
// Reference: https://javascript.info/shadow-dom-events#event-composed
const customChangeEvent = wrapNativeEvent(event);
if (!this._isAnimationAllowed) {
this._isAnimationAllowed = true;
}
this.dispatchEvent(customChangeEvent);
this._handleFormAssociation();
}
/**
* (Read-only) returns a ValidityState with the validity states that this element is in.
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/validity
*/
public get validity () : ValidityState {
return this._radio.validity;
}
/**
* Called when the form that contains this component is reset.
* If the current checked state is different to the default checked state,
* the checked state is reset to the default checked state and a `change` event is emitted.
*/
public formResetCallback () {
if (this.checked === this.defaultChecked) {
return;
}
this.checked = this.defaultChecked;
const changeEvent = new Event('change', { bubbles: true, composed: true });
this.dispatchEvent(changeEvent);
this._handleFormAssociation();
}
// Triggers a programmatic click on the underlying radio input.
// This is primarily used to ensure that the radio input is selected when using screenreaders like Apple VoiceOver.
private _handleClick (event: MouseEvent): void {
// This guard prevents an infinite loop by ignoring the programmatic click
// that this handler generates as it bubbles back up from the internal input.
if (event.composedPath()[0] === this._radio) {
return;
}
if (this.disabled || this._disabledByParent) {
return;
}
this._radio.click();
}
updated () {
// Ensure aria-checked reflects the checked state
this.setAttribute('aria-checked', String(this.checked));
this._handleFormAssociation();
this._applyContextAria();
}
/**
* When an ancestor provides ARIA (for example a `pie-list-item`), applies the name and
* description to the host, which carries `role="radio"` and so is the element assistive tech
* announces. Guarded to only run when a provider exists (in a list), so a standalone radio's
* consumer-set `aria-*` is never removed.
*/
private _applyContextAria (): void {
const aria = this._contextAria;
if (!aria) return;
if (aria.label) {
this.setAttribute('aria-label', aria.label);
} else {
this.removeAttribute('aria-label');
}
if (aria.description) {
this.setAttribute('aria-description', aria.description);
} else {
this.removeAttribute('aria-description');
}
}
render () {
const {
checked,
disabled,
_disabledByParent,
_isAnimationAllowed,
name,
required,
value,
status,
} = this;
const componentDisabled = disabled || _disabledByParent;
const classes = {
'c-radio': true,
'is-disabled': componentDisabled,
[`has-${status}`]: !componentDisabled,
'is-animated': _isAnimationAllowed,
};
// NOTE: The label element here does not require a `for` attribute. This is because the click logic is handled by the component itself.
// Adding a `for` attribute would cause multiple click events to be fired which could lead to unexpected behaviour that might impact accessibility, performance and analytics.
// We still use a label element for good semantics.
return html`
`;
}
// Renders a `CSSResult` generated from SCSS by Vite
static styles = unsafeCSS(styles);
}
declare global {
interface HTMLElementTagNameMap {
[componentSelector]: PieRadio;
}
}