From 9fc2a8ef4229a0b789389285d42bfa837807ee02 Mon Sep 17 00:00:00 2001 From: yonatankra Date: Wed, 20 Oct 2021 14:41:55 +0300 Subject: [PATCH] fix(button): prevent double click inside a form --- components/button/src/vwc-button.ts | 8 +++++-- components/button/test/button.test.js | 31 +++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/components/button/src/vwc-button.ts b/components/button/src/vwc-button.ts index f9230e61d8..e443fa80a8 100644 --- a/components/button/src/vwc-button.ts +++ b/components/button/src/vwc-button.ts @@ -134,7 +134,7 @@ export class VWCButton extends MWCButton { // return nothing } - protected _handleClick(): void { + protected _handleClick(event: MouseEvent): void { if (this.form) { switch (this.getAttribute('type')) { case 'reset': @@ -143,7 +143,11 @@ export class VWCButton extends MWCButton { case 'button': break; default: - this.#_hiddenButton.click(); + if (event.target === this) { + this.#_hiddenButton.click(); + } else { + event.stopImmediatePropagation(); + } break; } } diff --git a/components/button/test/button.test.js b/components/button/test/button.test.js index 823c02db17..f48d21ef09 100644 --- a/components/button/test/button.test.js +++ b/components/button/test/button.test.js @@ -75,6 +75,37 @@ describe('button', () => { expect(submitted).to.equal(true); }); + it('should emit a click event only once when inside a form', async function () { + let clicked = 0; + const addedElements = addElement( + textToDomToParent( + `
<${COMPONENT_NAME} type="submit">Button Text
` + ) + ); + await waitNextTask(); + const formElement = addedElements[0]; + const actualElement = formElement.firstChild; + actualElement.addEventListener('click', () => (clicked++)); + + actualElement.click(); + expect(clicked).to.equal(1); + }); + + it('should emit a click event only once when outside a form', async function () { + let clicked = 0; + const [actualElement] = addElement( + textToDomToParent( + `<${COMPONENT_NAME} type="submit">Button Text` + ) + ); + await waitNextTask(); + actualElement.addEventListener('click', () => (clicked++)); + + actualElement.click(); + await waitInterval(100); + expect(clicked).to.equal(1); + }); + it('should reset form when of type reset', async function () { let submitted = false; let reset = false;