Skip to content

Commit

Permalink
fix: stop propagation of sp-radio "change" events at sp-radio-group b…
Browse files Browse the repository at this point in the history
…oundary
  • Loading branch information
Westbrook Johnson authored and Westbrook committed Apr 7, 2022
1 parent 8350cf4 commit f618460
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
3 changes: 3 additions & 0 deletions packages/radio/src/Radio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ export class Radio extends FocusVisiblePolyfillMixin(SpectrumElement) {
}

protected activate(): void {
if (this.checked) {
return;
}
this.checked = true;
this.dispatchEvent(
new Event('change', {
Expand Down
5 changes: 1 addition & 4 deletions packages/radio/src/RadioGroup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,7 @@ export class RadioGroup extends FocusVisiblePolyfillMixin(FieldGroup) {
}
}

this.addEventListener('change', (event: Event) => {
if (event.target === this) {
return;
}
this.shadowRoot.addEventListener('change', (event: Event) => {
event.stopPropagation();
const target = event.target as Radio;
this._setSelected(target.value);
Expand Down
23 changes: 23 additions & 0 deletions packages/radio/test/radio-group.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
sendKeys,
} from '@web/test-runner-commands';
import { sendMouse } from '../../../test/plugins/browser.js';
import { spy } from 'sinon';

describe('Radio Group - focus control', () => {
it('does not accept focus when empty', async () => {
Expand Down Expand Up @@ -606,4 +607,26 @@ describe('Radio Group', () => {
) as RadioGroup;
expect(radioGroup.selected).to.equal('5');
});

it('prevents `change` events from radio buttons', async () => {
const changeSpy = spy();
const onChange = (event: Event & { target: RadioGroup }): void => {
changeSpy(event.target.selected);
};
const el = await fixture(html`
<sp-radio-group @change=${onChange}>
<sp-radio value="bulbasaur">Bulbasaur</sp-radio>
<sp-radio value="squirtle">Squirtle</sp-radio>
<sp-radio value="charmander">Charmander</sp-radio>
</sp-radio-group>
`);

const bulbasaur = el.querySelector('[value="bulbasaur"]') as Radio;
const charmander = el.querySelector('[value="charmander"]') as Radio;
bulbasaur.click();
bulbasaur.click();
charmander.click();

expect(changeSpy.calledWith(undefined)).to.be.false;
});
});

0 comments on commit f618460

Please sign in to comment.