Skip to content

Commit

Permalink
fix(iconbutton): allow prevent default click for toggles
Browse files Browse the repository at this point in the history
Fixes #4857

PiperOrigin-RevId: 563154643
  • Loading branch information
asyncLiz authored and copybara-github committed Sep 6, 2023
1 parent 6988a49 commit de860f2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
18 changes: 16 additions & 2 deletions iconbutton/icon-button_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ describe('icon button tests', () => {
});

it('button with toggled aria label toggles aria label', async () => {
const {element} = await setUpTest('toggle');
const {element, harness} = await setUpTest('toggle');
element.ariaLabelSelected = 'aria label on';
element.ariaLabel = 'aria label off';
await element.updateComplete;
Expand All @@ -160,7 +160,7 @@ describe('icon button tests', () => {
expect(button.getAttribute('aria-label')).toEqual('aria label off');

// Toggle
button.click();
await harness.clickWithMouse();
await element.updateComplete;
expect(element.selected).toBeTrue();
expect(button.getAttribute('aria-label')).toEqual('aria label on');
Expand Down Expand Up @@ -193,6 +193,20 @@ describe('icon button tests', () => {
expect((element as unknown as IconButtonInternals).flipIcon)
.toBeFalse();
});

it('should allow preventing toggle click event', async () => {
const {element, harness} = await setUpTest('toggle');

element.addEventListener('click', event => {
event.preventDefault();
});

expect(element.selected).withContext('selected before click').toBeFalse();
await harness.clickWithMouse();
expect(element.selected)
.withContext('selected after prevent default click')
.toBeFalse();
});
});

async function setUpTest(type: string) {
Expand Down
6 changes: 4 additions & 2 deletions iconbutton/internal/icon-button.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,10 @@ export class IconButton extends LitElement implements FormSubmitter {
super.connectedCallback();
}

private handleClick() {
if (!this.toggle || this.disabled) {
private async handleClick(event: Event) {
// Allow the event to propagate
await 0;
if (!this.toggle || this.disabled || event.defaultPrevented) {
return;
}

Expand Down

0 comments on commit de860f2

Please sign in to comment.