Skip to content

Commit 5dc870b

Browse files
asynclizcopybara-github
authored andcommitted
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
1 parent 035d155 commit 5dc870b

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

chips/internal/filter-chip.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,11 +108,17 @@ export class FilterChip extends MultiActionChip {
108108
return;
109109
}
110110

111+
// Store prevValue to revert in case `chip.selected` is changed during an
112+
// event listener.
113+
const prevValue = this.selected;
111114
this.selected = !this.selected;
112115

113116
const preventDefault = !redispatchEvent(this, event);
114117
if (preventDefault) {
115-
this.selected = !this.selected;
118+
// We should not do `this.selected = !this.selected`, since a client
119+
// click listener could change its value. Instead, always revert to the
120+
// original value.
121+
this.selected = prevValue;
116122
return;
117123
}
118124
}

chips/internal/filter-chip_test.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,5 +66,38 @@ describe('Filter chip', () => {
6666
await harness.clickWithMouse();
6767
expect(handler).toHaveBeenCalledTimes(0);
6868
});
69+
70+
it('always reverts value on preventDefault() even if selected is changed in listener', async () => {
71+
const {chip, harness} = await setupTest();
72+
73+
chip.addEventListener(
74+
'click',
75+
(event) => {
76+
event.preventDefault();
77+
chip.selected = false;
78+
},
79+
{once: true},
80+
);
81+
82+
await harness.clickWithMouse();
83+
expect(chip.selected)
84+
.withContext('chip.selected reverts to false')
85+
.toBeFalse();
86+
87+
chip.selected = true;
88+
chip.addEventListener(
89+
'click',
90+
(event) => {
91+
event.preventDefault();
92+
chip.selected = false;
93+
},
94+
{once: true},
95+
);
96+
97+
await harness.clickWithMouse();
98+
expect(chip.selected)
99+
.withContext('chip.selected reverts to true')
100+
.toBeTrue();
101+
});
69102
});
70103
});

0 commit comments

Comments
 (0)