restore desired commits

This commit is contained in:
Cory LaViska
2022-03-24 08:11:49 -04:00
parent cb460ee7ba
commit af4d25ee37
13 changed files with 585 additions and 170 deletions

View File

@@ -60,4 +60,64 @@ import { SlCheckbox } from '@shoelace-style/shoelace/dist/react';
const App = () => <SlCheckbox disabled>Disabled</SlCheckbox>;
```
### Custom Validity
Use the `setCustomValidity()` method to set a custom validation message. This will prevent the form from submitting and make the browser display the error message you provide. To clear the error, call this function with an empty string.
```html preview
<form class="custom-validity">
<sl-checkbox>Check me</sl-checkbox>
<br />
<sl-button type="submit" variant="primary" style="margin-top: 1rem;">Submit</sl-button>
</form>
<script>
const form = document.querySelector('.custom-validity');
const checkbox = form.querySelector('sl-checkbox');
const errorMessage = `Don't forget to check me!`;
// Set initial validity as soon as the element is defined
customElements.whenDefined('sl-checkbox').then(() => {
checkbox.setCustomValidity(errorMessage);
});
// Update validity on change
checkbox.addEventListener('sl-change', () => {
checkbox.setCustomValidity(checkbox.checked ? '' : errorMessage);
});
// Handle submit
form.addEventListener('submit', event => {
event.preventDefault();
alert('All fields are valid!');
});
</script>
```
```jsx react
import { useEffect, useRef } from 'react';
import { SlButton, SlCheckbox } from '@shoelace-style/shoelace/dist/react';
const App = () => {
const checkbox = useRef(null);
const errorMessage = `Don't forget to check me!`;
function handleChange() {
checkbox.current.setCustomValidity(checkbox.current.checked ? '' : errorMessage);
}
function handleSubmit(event) {
event.preventDefault();
alert('All fields are valid!');
}
useEffect(() => {
checkbox.current.setCustomValidity(errorMessage);
}, []);
return (
<form class="custom-validity" onSubmit={handleSubmit}>
<SlCheckbox ref={checkbox} onSlChange={handleChange}>
Check me
</SlCheckbox>
<br />
<SlButton type="submit" variant="primary" style={{ marginTop: '1rem' }}>
Submit
</SlButton>
</form>
);
};
```
[component-metadata:sl-checkbox]

View File

@@ -414,4 +414,77 @@ const App = () => (
);
```
### Custom Validity
Use the `setCustomValidity()` method to set a custom validation message. This will prevent the form from submitting and make the browser display the error message you provide. To clear the error, call this function with an empty string.
```html preview
<form class="custom-validity">
<sl-radio-group label="Select an option">
<sl-radio-button name="a" value="1" checked>Not me</sl-radio-button>
<sl-radio-button name="a" value="2">Me neither</sl-radio-button>
<sl-radio-button name="a" value="3">Choose me</sl-radio-button>
</sl-radio-group>
<br />
<sl-button type="submit" variant="primary">Submit</sl-button>
</form>
<script>
const form = document.querySelector('.custom-validity');
const radioButton = form.querySelectorAll('sl-radio-button')[2];
const errorMessage = 'You must choose this option';
// Set initial validity as soon as the element is defined
customElements.whenDefined('sl-radio-button').then(() => {
radioButton.setCustomValidity(errorMessage);
});
// Update validity when a selection is made
form.addEventListener('sl-change', () => {
const isValid = radioButton.checked;
radioButton.setCustomValidity(isValid ? '' : errorMessage);
});
// Handle form submit
form.addEventListener('submit', event => {
event.preventDefault();
alert('All fields are valid!');
});
</script>
```
```jsx react
import { useEffect, useRef } from 'react';
import { SlButton, SlIcon, SlRadioButton, SlRadioGroup } from '@shoelace-style/shoelace/dist/react';
const App = () => {
const radio = useRef(null);
const errorMessage = 'You must choose this option';
function handleChange(event) {
radio.current.setCustomValidity(radio.current.checked ? '' : errorMessage);
}
function handleSubmit(event) {
event.preventDefault();
alert('All fields are valid!');
}
useEffect(() => {
radio.current.setCustomValidity(errorMessage);
}, []);
return (
<form class="custom-validity" onSubmit={handleSubmit}>
<SlRadioGroup label="Select an option">
<SlRadioButton name="a" value="1" checked onSlChange={handleChange}>
Not me
</SlRadioButton>
<SlRadioButton name="a" value="2" onSlChange={handleChange}>
Me neither
</SlRadioButton>
<SlRadioButton ref={radio} name="a" value="3" onSlChange={handleChange}>
Choose me
</SlRadioButton>
</SlRadioGroup>
<br />
<SlButton type="submit" variant="primary">
Submit
</SlButton>
</form>
);
};
```
[component-metadata:sl-radio-button]

View File

@@ -96,4 +96,77 @@ const App = () => (
);
```
### Custom Validity
Use the `setCustomValidity()` method to set a custom validation message. This will prevent the form from submitting and make the browser display the error message you provide. To clear the error, call this function with an empty string.
```html preview
<form class="custom-validity">
<sl-radio-group label="Select an option">
<sl-radio name="a" value="1" checked>Not me</sl-radio>
<sl-radio name="a" value="2">Me neither</sl-radio>
<sl-radio name="a" value="3">Choose me</sl-radio>
</sl-radio-group>
<br />
<sl-button type="submit" variant="primary">Submit</sl-button>
</form>
<script>
const form = document.querySelector('.custom-validity');
const radio = form.querySelectorAll('sl-radio')[2];
const errorMessage = 'You must choose this option';
// Set initial validity as soon as the element is defined
customElements.whenDefined('sl-radio').then(() => {
radio.setCustomValidity(errorMessage);
});
// Update validity when a selection is made
form.addEventListener('sl-change', () => {
const isValid = radio.checked;
radio.setCustomValidity(isValid ? '' : errorMessage);
});
// Handle form submit
form.addEventListener('submit', event => {
event.preventDefault();
alert('All fields are valid!');
});
</script>
```
```jsx react
import { useEffect, useRef } from 'react';
import { SlButton, SlIcon, SlRadio, SlRadioGroup } from '@shoelace-style/shoelace/dist/react';
const App = () => {
const radio = useRef(null);
const errorMessage = 'You must choose this option';
function handleChange(event) {
radio.current.setCustomValidity(radio.current.checked ? '' : errorMessage);
}
function handleSubmit(event) {
event.preventDefault();
alert('All fields are valid!');
}
useEffect(() => {
radio.current.setCustomValidity(errorMessage);
}, []);
return (
<form class="custom-validity" onSubmit={handleSubmit}>
<SlRadioGroup label="Select an option">
<SlRadio name="a" value="1" checked onSlChange={handleChange}>
Not me
</SlRadio>
<SlRadio name="a" value="2" onSlChange={handleChange}>
Me neither
</SlRadio>
<SlRadio ref={radio} name="a" value="3" onSlChange={handleChange}>
Choose me
</SlRadio>
</SlRadioGroup>
<br />
<SlButton type="submit" variant="primary">
Submit
</SlButton>
</form>
);
};
```
[component-metadata:sl-radio]

View File

@@ -194,7 +194,7 @@ const App = () => {
### Custom Validation
To create a custom validation error, use the `setCustomValidity` method. The form will not be submitted when this method is called with anything other than an empty string, and its message will be shown by the browser as the validation error. To make the input valid again, call the method a second time with an empty string as the argument.
To create a custom validation error, pass a non-empty string to the `setCustomValidity()` method. This will override any existing validation constraints. The form will not be submitted when a custom validity is set and the browser will show a validation error when the containing form is submitted. To make the input valid again, call `setCustomValidity()` again with an empty string.
```html preview
<form class="input-validation-custom">
@@ -257,6 +257,8 @@ const App = () => {
};
```
?> Custom validation can be applied to any form control that supports the `setCustomValidity()` method. It is not limited to inputs and textareas.
### Custom Validation Styles
The `invalid` attribute reflects the form control's validity, so you can style invalid fields using the `[invalid]` selector. The example below demonstrates how you can give erroneous fields a different appearance. Type something other than "shoelace" to demonstrate this.

View File

@@ -6,6 +6,15 @@ Components with the <sl-badge variant="warning" pill>Experimental</sl-badge> bad
_During the beta period, these restrictions may be relaxed in the event of a mission-critical bug._ 🐛
## Next
- Added `button` part to `<sl-radio-button>`
- Added custom validity examples and tests to `<sl-checkbox>`, `<sl-radio>`, and `<sl-radio-button>`
- Fixed a bug that prevented `setCustomValidity()` from working with `<sl-radio-button>`
- Fixed a bug where the right border of a checked `<sl-radio-button>` was the wrong color
- Fixed a bug that prevented a number of properties, methods, etc. from being documented in `<sl-radio>` and `<sl-radio-button>`
- Once again removed path aliasing because it doesn't work with Web Test Runner's esbuild plugin
## 2.0.0-beta.72
- 🚨 BREAKING: refactored parts in `<sl-input>`, `<sl-range>`, `<sl-select>`, and `<sl-textarea>` to allow you to customize the label and help text position

View File

@@ -632,12 +632,13 @@ export default css`
mix-blend-mode: multiply;
}
/* Bump focused buttons up so their focus ring isn't clipped */
/* Bump hovered, focused, and checked buttons up so their focus ring isn't clipped */
:host(.sl-button-group__button--hover) {
z-index: 1;
}
:host(.sl-button-group__button--focus) {
:host(.sl-button-group__button--focus),
:host(.sl-button-group__button[checked]) {
z-index: 2;
}
`;

View File

@@ -1,5 +1,6 @@
import { expect, fixture, html, oneEvent } from '@open-wc/testing';
import { aTimeout, expect, fixture, html, oneEvent, waitUntil } from '@open-wc/testing';
import { sendKeys } from '@web/test-runner-commands';
import sinon from 'sinon';
import type SlCheckbox from './checkbox';
describe('<sl-checkbox>', () => {
@@ -42,4 +43,49 @@ describe('<sl-checkbox>', () => {
el.checked = false;
await el.updateComplete;
});
describe('when submitting a form', () => {
it('should submit the correct value', async () => {
const form = await fixture<HTMLFormElement>(html`
<form>
<sl-checkbox name="a" value="1" checked></sl-checkbox>
<sl-button type="submit">Submit</sl-button>
</form>
`);
const button = form.querySelector('sl-button')!;
const submitHandler = sinon.spy((event: SubmitEvent) => {
formData = new FormData(form);
event.preventDefault();
});
let formData: FormData;
form.addEventListener('submit', submitHandler);
button.click();
await waitUntil(() => submitHandler.calledOnce);
expect(formData!.get('a')).to.equal('1');
});
it('should show a constraint validation error when setCustomValidity() is called', async () => {
const form = await fixture<HTMLFormElement>(html`
<form>
<sl-checkbox name="a" value="1" checked></sl-checkbox>
<sl-button type="submit">Submit</sl-button>
</form>
`);
const button = form.querySelector('sl-button')!;
const checkbox = form.querySelector('sl-checkbox')!;
const submitHandler = sinon.spy((event: SubmitEvent) => event.preventDefault());
// Submitting the form after setting custom validity should not trigger the handler
checkbox.setCustomValidity('Invalid selection');
form.addEventListener('submit', submitHandler);
button.click();
await aTimeout(100);
expect(submitHandler).to.not.have.been.called;
});
});
});

View File

@@ -0,0 +1,23 @@
import { css } from 'lit';
import buttonStyles from '../button/button.styles';
export default css`
${buttonStyles}
label {
display: inline-block;
position: relative;
}
/* We use a hidden input so constraint validation errors work, since they don't appear to show when used with buttons.
We can't actually hide it, though, otherwise the messages will be suppressed by the browser. */
.hidden-input {
all: unset;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
outline: dotted 1px red;
opacity: 0;
z-index: -1;
}
`;

View File

@@ -1,4 +1,4 @@
import { expect, fixture, html, oneEvent, waitUntil } from '@open-wc/testing';
import { aTimeout, expect, fixture, html, oneEvent, waitUntil } from '@open-wc/testing';
import { sendKeys } from '@web/test-runner-commands';
import sinon from 'sinon';
import type SlRadioGroup from '../../components/radio-group/radio-group';
@@ -74,7 +74,7 @@ describe('<sl-radio-button>', () => {
<sl-radio-group>
<sl-radio-button id="radio-1" name="a" value="1" checked></sl-radio-button>
<sl-radio-button id="radio-2" name="a" value="2"></sl-radio-button>
<sl-radio-button id="radio-2" name="a" value="3"></sl-radio-button>
<sl-radio-button id="radio-3" name="a" value="3"></sl-radio-button>
</sl-radio-group>
<sl-button type="submit">Submit</sl-button>
</form>
@@ -96,4 +96,28 @@ describe('<sl-radio-button>', () => {
expect(formData!.get('a')).to.equal('2');
});
});
it('should show a constraint validation error when setCustomValidity() is called', async () => {
const form = await fixture<HTMLFormElement>(html`
<form>
<sl-radio-group>
<sl-radio-button id="radio-1" name="a" value="1" checked></sl-radio-button>
<sl-radio-button id="radio-2" name="a" value="2"></sl-radio-button>
</sl-radio-group>
<sl-button type="submit">Submit</sl-button>
</form>
`);
const button = form.querySelector('sl-button')!;
const radio = form.querySelectorAll('sl-radio-button')[1]!;
const submitHandler = sinon.spy((event: SubmitEvent) => event.preventDefault());
// Submitting the form after setting custom validity should not trigger the handler
radio.setCustomValidity('Invalid selection');
form.addEventListener('submit', submitHandler);
button.click();
await aTimeout(100);
expect(submitHandler).to.not.have.been.called;
});
});

View File

@@ -1,10 +1,13 @@
import { customElement, property } from 'lit/decorators.js';
import { LitElement } from 'lit';
import { customElement, property, query, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { html } from 'lit/static-html.js';
import styles from '../../components/button/button.styles';
import RadioBase from '../../internal/radio';
import { emit } from '../../internal/event';
import { FormSubmitController } from '../../internal/form';
import { HasSlotController } from '../../internal/slot';
import { watch } from '../../internal/watch';
import styles from './radio-button.styles';
/**
* @since 2.0
@@ -21,16 +24,109 @@ import { HasSlotController } from '../../internal/slot';
* @slot suffix - Used to append an icon or similar element to the button.
*
* @csspart base - The component's internal wrapper.
* @csspart button - The internal button element.
* @csspart prefix - The prefix slot's container.
* @csspart label - The button's label.
* @csspart suffix - The suffix slot's container.
*/
@customElement('sl-radio-button')
export default class SlRadioButton extends RadioBase {
export default class SlRadioButton extends LitElement {
static styles = styles;
@query('.button') input: HTMLInputElement;
@query('.hidden-input') hiddenInput: HTMLInputElement;
protected readonly formSubmitController = new FormSubmitController(this, {
value: (control: SlRadioButton) => (control.checked ? control.value : undefined)
});
private readonly hasSlotController = new HasSlotController(this, '[default]', 'prefix', 'suffix');
@state() protected hasFocus = false;
/** The radio's name attribute. */
@property() name: string;
/** The radio's value attribute. */
@property() value: string;
/** Disables the radio. */
@property({ type: Boolean, reflect: true }) disabled = false;
/** Draws the radio in a checked state. */
@property({ type: Boolean, reflect: true }) checked = false;
/**
* This will be true when the control is in an invalid state. Validity in radios is determined by the message provided
* by the `setCustomValidity` method.
*/
@property({ type: Boolean, reflect: true }) invalid = false;
connectedCallback(): void {
super.connectedCallback();
this.setAttribute('role', 'radio');
}
/** Simulates a click on the radio. */
click() {
this.input.click();
}
/** Sets focus on the radio. */
focus(options?: FocusOptions) {
this.input.focus(options);
}
/** Removes focus from the radio. */
blur() {
this.input.blur();
}
/** Checks for validity and shows the browser's validation message if the control is invalid. */
reportValidity() {
return this.hiddenInput.reportValidity();
}
/** Sets a custom validation message. If `message` is not empty, the field will be considered invalid. */
setCustomValidity(message: string) {
this.hiddenInput.setCustomValidity(message);
}
handleBlur() {
this.hasFocus = false;
emit(this, 'sl-blur');
}
handleClick() {
if (!this.disabled) {
this.checked = true;
}
}
handleFocus() {
this.hasFocus = true;
emit(this, 'sl-focus');
}
@watch('checked')
handleCheckedChange() {
this.setAttribute('aria-checked', this.checked ? 'true' : 'false');
if (this.hasUpdated) {
emit(this, 'sl-change');
}
}
@watch('disabled', { waitUntilFirstUpdate: true })
handleDisabledChange() {
this.setAttribute('aria-disabled', this.disabled ? 'true' : 'false');
// Disabled form controls are always valid, so we need to recheck validity when the state changes
if (this.hasUpdated) {
this.input.disabled = this.disabled;
this.invalid = !this.input.checkValidity();
}
}
/** The button's variant. */
@property({ reflect: true }) variant: 'default' | 'primary' | 'success' | 'neutral' | 'warning' | 'danger' =
'default';
@@ -38,57 +134,54 @@ export default class SlRadioButton extends RadioBase {
/** The button's size. */
@property({ reflect: true }) size: 'small' | 'medium' | 'large' = 'medium';
/**
* This will be true when the control is in an invalid state. Validity in radio buttons is determined by the message
* provided by the `setCustomValidity` method.
*/
@property({ type: Boolean, reflect: true }) invalid = false;
/** Draws a pill-style button with rounded edges. */
@property({ type: Boolean, reflect: true }) pill = false;
render() {
return html`
<button
part="base"
class=${classMap({
button: true,
'button--default': this.variant === 'default',
'button--primary': this.variant === 'primary',
'button--success': this.variant === 'success',
'button--neutral': this.variant === 'neutral',
'button--warning': this.variant === 'warning',
'button--danger': this.variant === 'danger',
'button--small': this.size === 'small',
'button--medium': this.size === 'medium',
'button--large': this.size === 'large',
'button--checked': this.checked,
'button--disabled': this.disabled,
'button--focused': this.hasFocus,
'button--outline': true,
'button--pill': this.pill,
'button--has-label': this.hasSlotController.test('[default]'),
'button--has-prefix': this.hasSlotController.test('prefix'),
'button--has-suffix': this.hasSlotController.test('suffix')
})}
?disabled=${this.disabled}
type="button"
name=${ifDefined(this.name)}
value=${ifDefined(this.value)}
@blur=${this.handleBlur}
@focus=${this.handleFocus}
@click=${this.handleClick}
>
<span part="prefix" class="button__prefix">
<slot name="prefix"></slot>
</span>
<span part="label" class="button__label">
<slot></slot>
</span>
<span part="suffix" class="button__suffix">
<slot name="suffix"></slot>
</span>
</button>
<div part="base">
<input class="hidden-input" type="radio" aria-hidden="true" tabindex="-1" />
<button
part="button"
class=${classMap({
button: true,
'button--default': this.variant === 'default',
'button--primary': this.variant === 'primary',
'button--success': this.variant === 'success',
'button--neutral': this.variant === 'neutral',
'button--warning': this.variant === 'warning',
'button--danger': this.variant === 'danger',
'button--small': this.size === 'small',
'button--medium': this.size === 'medium',
'button--large': this.size === 'large',
'button--checked': this.checked,
'button--disabled': this.disabled,
'button--focused': this.hasFocus,
'button--outline': true,
'button--pill': this.pill,
'button--has-label': this.hasSlotController.test('[default]'),
'button--has-prefix': this.hasSlotController.test('prefix'),
'button--has-suffix': this.hasSlotController.test('suffix')
})}
?disabled=${this.disabled}
type="button"
name=${ifDefined(this.name)}
value=${ifDefined(this.value)}
@blur=${this.handleBlur}
@focus=${this.handleFocus}
@click=${this.handleClick}
>
<span part="prefix" class="button__prefix">
<slot name="prefix"></slot>
</span>
<span part="label" class="button__label">
<slot></slot>
</span>
<span part="suffix" class="button__suffix">
<slot name="suffix"></slot>
</span>
</button>
</div>
`;
}
}

View File

@@ -1,4 +1,4 @@
import { expect, fixture, html, oneEvent, waitUntil } from '@open-wc/testing';
import { aTimeout, expect, fixture, html, oneEvent, waitUntil } from '@open-wc/testing';
import { sendKeys } from '@web/test-runner-commands';
import sinon from 'sinon';
import type SlRadioGroup from '../../components/radio-group/radio-group';
@@ -75,7 +75,7 @@ describe('<sl-radio>', () => {
<sl-radio-group>
<sl-radio id="radio-1" name="a" value="1" checked></sl-radio>
<sl-radio id="radio-2" name="a" value="2"></sl-radio>
<sl-radio id="radio-2" name="a" value="3"></sl-radio>
<sl-radio id="radio-3" name="a" value="3"></sl-radio>
</sl-radio-group>
<sl-button type="submit">Submit</sl-button>
</form>
@@ -97,4 +97,28 @@ describe('<sl-radio>', () => {
expect(formData!.get('a')).to.equal('2');
});
});
it('should show a constraint validation error when setCustomValidity() is called', async () => {
const form = await fixture<HTMLFormElement>(html`
<form>
<sl-radio-group>
<sl-radio id="radio-1" name="a" value="1" checked></sl-radio>
<sl-radio id="radio-2" name="a" value="2"></sl-radio>
</sl-radio-group>
<sl-button type="submit">Submit</sl-button>
</form>
`);
const button = form.querySelector('sl-button')!;
const radio = form.querySelectorAll('sl-radio')[1]!;
const submitHandler = sinon.spy((event: SubmitEvent) => event.preventDefault());
// Submitting the form after setting custom validity should not trigger the handler
radio.setCustomValidity('Invalid selection');
form.addEventListener('submit', submitHandler);
button.click();
await aTimeout(100);
expect(submitHandler).to.not.have.been.called;
});
});

View File

@@ -1,9 +1,11 @@
import { html } from 'lit';
import { customElement } from 'lit/decorators.js';
import { html, LitElement } from 'lit';
import { customElement, property, query, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { live } from 'lit/directives/live.js';
import RadioBase from '../../internal/radio';
import { emit } from '../../internal/event';
import { FormSubmitController } from '../../internal/form';
import { watch } from '../../internal/watch';
import styles from './radio.styles';
/**
@@ -22,9 +24,102 @@ import styles from './radio.styles';
* @csspart label - The radio label.
*/
@customElement('sl-radio')
export default class SlRadio extends RadioBase {
export default class SlRadio extends LitElement {
static styles = styles;
@query('.radio__input') input: HTMLInputElement;
protected readonly formSubmitController = new FormSubmitController(this, {
value: (control: HTMLInputElement) => (control.checked ? control.value : undefined)
});
@state() protected hasFocus = false;
/** The radio's name attribute. */
@property() name: string;
/** The radio's value attribute. */
@property() value: string;
/** Disables the radio. */
@property({ type: Boolean, reflect: true }) disabled = false;
/** Draws the radio in a checked state. */
@property({ type: Boolean, reflect: true }) checked = false;
/**
* This will be true when the control is in an invalid state. Validity in radios is determined by the message provided
* by the `setCustomValidity` method.
*/
@property({ type: Boolean, reflect: true }) invalid = false;
connectedCallback(): void {
super.connectedCallback();
this.setAttribute('role', 'radio');
}
/** Simulates a click on the radio. */
click() {
this.input.click();
}
/** Sets focus on the radio. */
focus(options?: FocusOptions) {
this.input.focus(options);
}
/** Removes focus from the radio. */
blur() {
this.input.blur();
}
/** Checks for validity and shows the browser's validation message if the control is invalid. */
reportValidity() {
return this.input.reportValidity();
}
/** Sets a custom validation message. If `message` is not empty, the field will be considered invalid. */
setCustomValidity(message: string) {
this.input.setCustomValidity(message);
this.invalid = !this.input.checkValidity();
}
handleBlur() {
this.hasFocus = false;
emit(this, 'sl-blur');
}
handleClick() {
if (!this.disabled) {
this.checked = true;
}
}
handleFocus() {
this.hasFocus = true;
emit(this, 'sl-focus');
}
@watch('checked')
handleCheckedChange() {
this.setAttribute('aria-checked', this.checked ? 'true' : 'false');
if (this.hasUpdated) {
emit(this, 'sl-change');
}
}
@watch('disabled', { waitUntilFirstUpdate: true })
handleDisabledChange() {
this.setAttribute('aria-disabled', this.disabled ? 'true' : 'false');
// Disabled form controls are always valid, so we need to recheck validity when the state changes
if (this.hasUpdated) {
this.input.disabled = this.disabled;
this.invalid = !this.input.checkValidity();
}
}
render() {
return html`
<label

View File

@@ -1,108 +0,0 @@
import { LitElement } from 'lit';
import { property, query, state } from 'lit/decorators.js';
import { emit } from '../internal/event';
import { FormSubmitController } from '../internal/form';
import { watch } from '../internal/watch';
/**
* The following events are emitted by the base class. When extending, these comments should be prepended to the
* component so they show up in its documentation.
*
* @event sl-blur - Emitted when the control loses focus.
* @event sl-change - Emitted when the control's checked state changes.
* @event sl-focus - Emitted when the control gains focus.
*/
export default abstract class RadioBase extends LitElement {
@query('input[type="radio"], button') input: HTMLInputElement;
protected readonly formSubmitController = new FormSubmitController(this, {
value: (control: RadioBase) => (control.checked ? control.value : undefined)
});
@state() protected hasFocus = false;
/** The radio's name attribute. */
@property() name: string;
/** The radio's value attribute. */
@property() value: string;
/** Disables the radio. */
@property({ type: Boolean, reflect: true }) disabled = false;
/** Draws the radio in a checked state. */
@property({ type: Boolean, reflect: true }) checked = false;
/**
* This will be true when the control is in an invalid state. Validity in radios is determined by the message provided
* by the `setCustomValidity` method.
*/
@property({ type: Boolean, reflect: true }) invalid = false;
connectedCallback(): void {
super.connectedCallback();
this.setAttribute('role', 'radio');
}
/** Simulates a click on the radio. */
click() {
this.input.click();
}
/** Sets focus on the radio. */
focus(options?: FocusOptions) {
this.input.focus(options);
}
/** Removes focus from the radio. */
blur() {
this.input.blur();
}
/** Checks for validity and shows the browser's validation message if the control is invalid. */
reportValidity() {
return this.input.reportValidity();
}
/** Sets a custom validation message. If `message` is not empty, the field will be considered invalid. */
setCustomValidity(message: string) {
this.input.setCustomValidity(message);
this.invalid = !this.input.checkValidity();
}
handleBlur() {
this.hasFocus = false;
emit(this, 'sl-blur');
}
handleClick() {
if (!this.disabled) {
this.checked = true;
}
}
handleFocus() {
this.hasFocus = true;
emit(this, 'sl-focus');
}
@watch('checked')
handleCheckedChange() {
this.setAttribute('aria-checked', this.checked ? 'true' : 'false');
if (this.hasUpdated) {
emit(this, 'sl-change');
}
}
@watch('disabled', { waitUntilFirstUpdate: true })
handleDisabledChange() {
this.setAttribute('aria-disabled', this.disabled ? 'true' : 'false');
// Disabled form controls are always valid, so we need to recheck validity when the state changes
if (this.hasUpdated) {
this.input.disabled = this.disabled;
this.invalid = !this.input.checkValidity();
}
}
}