Skip to content

Commit

Permalink
fix(button): prevent double click inside a form
Browse files Browse the repository at this point in the history
  • Loading branch information
YonatanKra committed Oct 20, 2021
1 parent 3331109 commit 9fc2a8e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
8 changes: 6 additions & 2 deletions components/button/src/vwc-button.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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':
Expand All @@ -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;
}
}
Expand Down
31 changes: 31 additions & 0 deletions components/button/test/button.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
`<form onsubmit="return false" name="testForm" id="testForm"><${COMPONENT_NAME} type="submit">Button Text</${COMPONENT_NAME}></form>`
)
);
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</${COMPONENT_NAME}>`
)
);
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;
Expand Down

0 comments on commit 9fc2a8e

Please sign in to comment.