Skip to content

Commit

Permalink
feat(checkbox): add "checked" state to <md-checkbox> via CustomStateSet
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 692246916
  • Loading branch information
material-web-copybara authored and copybara-github committed Nov 1, 2024
1 parent 1bdcbd3 commit 7b0f656
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 1 deletion.
11 changes: 10 additions & 1 deletion checkbox/internal/checkbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ import {
getValidityAnchor,
mixinConstraintValidation,
} from '../../labs/behaviors/constraint-validation.js';
import {mixinElementInternals} from '../../labs/behaviors/element-internals.js';
import {
internals,
mixinElementInternals,
} from '../../labs/behaviors/element-internals.js';
import {
getFormState,
getFormValue,
Expand Down Expand Up @@ -111,6 +114,12 @@ export class Checkbox extends checkboxBaseClass {
this.prevDisabled = changed.get('disabled') ?? this.disabled;
this.prevIndeterminate =
changed.get('indeterminate') ?? this.indeterminate;

if (this.checked) {
this[internals].states.add('checked');
} else {
this[internals].states.delete('checked');
}
}

super.update(changed);
Expand Down
2 changes: 2 additions & 0 deletions checkbox/internal/checkbox_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,15 @@ describe('checkbox', () => {
expect(harness.element.indeterminate).toEqual(false);
expect(harness.element.disabled).toEqual(false);
expect(harness.element.value).toEqual('on');
expect(harness.element.matches(':state(checked)')).toEqual(false);
});

it('user input updates checked state', async () => {
const {harness} = await setupTest();
await harness.clickWithMouse();
await env.waitForStability();
expect(harness.element.checked).toEqual(true);
expect(harness.element.matches(':state(checked)')).toEqual(true);
});

it('should trigger changed event when checkbox is selected', async () => {
Expand Down
6 changes: 6 additions & 0 deletions docs/components/checkbox.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,9 @@ Token | Default value
<!-- mdformat on(autogenerated might break rendering in catalog) -->

<!-- auto-generated API docs end -->

#### States

| State | Description |
| --- | --- |
| `checked` | Set if this checkbox is checked. |
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-terser": "^0.4.4",
"@types/jasmine": "^4.0.3",
"@types/web": "^0.0.175",
"@web/test-runner": "^0.18.2",
"@web/test-runner-playwright": "^0.9.0",
"jasmine": "^4.5.0",
Expand Down

0 comments on commit 7b0f656

Please sign in to comment.