From de860f2c6f062fb1c17f629c3ed91b4f7e2301ae Mon Sep 17 00:00:00 2001 From: Elizabeth Mitchell Date: Wed, 6 Sep 2023 10:59:41 -0700 Subject: [PATCH] fix(iconbutton): allow prevent default click for toggles Fixes #4857 PiperOrigin-RevId: 563154643 --- iconbutton/icon-button_test.ts | 18 ++++++++++++++++-- iconbutton/internal/icon-button.ts | 6 ++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/iconbutton/icon-button_test.ts b/iconbutton/icon-button_test.ts index 01c10105a95..ef517e9f781 100644 --- a/iconbutton/icon-button_test.ts +++ b/iconbutton/icon-button_test.ts @@ -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; @@ -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'); @@ -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) { diff --git a/iconbutton/internal/icon-button.ts b/iconbutton/internal/icon-button.ts index 6c1cc6f9fe5..03d01d73e11 100644 --- a/iconbutton/internal/icon-button.ts +++ b/iconbutton/internal/icon-button.ts @@ -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; }