diff --git a/src/index.ts b/src/index.ts index b103f28..c45b99f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,6 +7,8 @@ type Disableable = HTMLButtonElement | HTMLInputElement | HTMLTextAreaElement | type Focusable = HTMLElement +type SubmitEvent = Event & { submitter: Element } + function autofocus(el: DetailsDialogElement): void { let autofocusElement = Array.from(el.querySelectorAll('[autofocus]')).filter(focusable)[0] if (!autofocusElement) { @@ -197,6 +199,21 @@ class DetailsDialogElement extends HTMLElement { toggleDetails(details, false) } }) + this.addEventListener('submit', function(event: Event) { + if (!(event.target instanceof HTMLFormElement)) return + + const {target} = event + const submitEvent = 'submitter' in event ? event as SubmitEvent : null + const method = submitEvent?.submitter.getAttribute('formmethod') || target.getAttribute('method') + + if (method == 'dialog') { + event.preventDefault() + const details = target.closest('details') + if (details) { + toggleDetails(details, false) + } + } + }) } get src(): string | null { diff --git a/test/test.js b/test/test.js index 4039485..8f322a5 100644 --- a/test/test.js +++ b/test/test.js @@ -31,6 +31,8 @@ describe('details-dialog-element', function() {
+
+
@@ -96,6 +98,10 @@ describe('details-dialog-element', function() { triggerKeydownEvent(details, 'Tab') assert.equal(document.activeElement, document.querySelector(`[data-button]`)) triggerKeydownEvent(details, 'Tab') + assert.equal(document.activeElement, document.querySelector(`form[method="dialog"] button`)) + triggerKeydownEvent(details, 'Tab') + assert.equal(document.activeElement, document.querySelector(`[formmethod="dialog"]`)) + triggerKeydownEvent(details, 'Tab') assert.equal(document.activeElement, document.querySelector(`[${CLOSE_ATTR}]`)) }) @@ -199,6 +205,14 @@ describe('details-dialog-element', function() { assert(details.open) close.click() assert(!details.open) + dialog.toggle(true) + assert(details.open) + dialog.querySelector('#method-dialog').click() + assert(!details.open) + dialog.toggle(true) + assert(details.open) + dialog.querySelector('#formmethod-dialog').click() + assert(!details.open) }) it('closes when escape key is pressed', async function() {