Skip to content

Commit

Permalink
fix(chips): filter's click.preventDefault() not working when also u…
Browse files Browse the repository at this point in the history
…pdating `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
  • Loading branch information
asyncLiz authored and copybara-github committed Jan 2, 2024
1 parent 035d155 commit 5dc870b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
8 changes: 7 additions & 1 deletion chips/internal/filter-chip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down
33 changes: 33 additions & 0 deletions chips/internal/filter-chip_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
});

0 comments on commit 5dc870b

Please sign in to comment.