fix(chips): filter's click.preventDefault() not working when also updating selected

Fixes #5199

This bug appeared when calling prevent default as well as changing the state of the chip in the same listener. Now calling preventDefault will always revert to the previous value.

PiperOrigin-RevId: 595199149
This commit is contained in:
Elizabeth Mitchell 2024-01-02 13:40:56 -08:00 committed by Copybara-Service
parent 035d155366
commit 5dc870bfe1
2 changed files with 40 additions and 1 deletions

View File

@ -108,11 +108,17 @@ export class FilterChip extends MultiActionChip {
return;
}
// Store prevValue to revert in case `chip.selected` is changed during an
// event listener.
const prevValue = this.selected;
this.selected = !this.selected;
const preventDefault = !redispatchEvent(this, event);
if (preventDefault) {
this.selected = !this.selected;
// We should not do `this.selected = !this.selected`, since a client
// click listener could change its value. Instead, always revert to the
// original value.
this.selected = prevValue;
return;
}
}

View File

@ -66,5 +66,38 @@ describe('Filter chip', () => {
await harness.clickWithMouse();
expect(handler).toHaveBeenCalledTimes(0);
});
it('always reverts value on preventDefault() even if selected is changed in listener', async () => {
const {chip, harness} = await setupTest();
chip.addEventListener(
'click',
(event) => {
event.preventDefault();
chip.selected = false;
},
{once: true},
);
await harness.clickWithMouse();
expect(chip.selected)
.withContext('chip.selected reverts to false')
.toBeFalse();
chip.selected = true;
chip.addEventListener(
'click',
(event) => {
event.preventDefault();
chip.selected = false;
},
{once: true},
);
await harness.clickWithMouse();
expect(chip.selected)
.withContext('chip.selected reverts to true')
.toBeTrue();
});
});
});