From b0b8c813dbccbe37ff4c08395372fbf84fa30186 Mon Sep 17 00:00:00 2001 From: phoebus-84 <83974413+phoebus-84@users.noreply.github.com> Date: Thu, 15 Feb 2024 18:29:59 +0100 Subject: [PATCH] fix: button type submit (#50) * fix: button type submit * test: update --- src/components/button/d-button.tsx | 46 ++++++++++++++++++-- src/components/button/test/d-button.spec.tsx | 2 +- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/src/components/button/d-button.tsx b/src/components/button/d-button.tsx index 1023367..2f600ce 100644 --- a/src/components/button/d-button.tsx +++ b/src/components/button/d-button.tsx @@ -34,11 +34,48 @@ export class DButton implements ComponentInterface { @Event() dFocus!: EventEmitter; @Event() dBlur!: EventEmitter; - private get hasIconOnly() { return !!this.el.querySelector('[slot="icon-only"]'); } + private findForm(): HTMLFormElement | null { + const { form } = this; + if (form instanceof HTMLFormElement) { + return form; + } + if (typeof form === 'string') { + const el: HTMLElement | null = document.getElementById(form); + if (el) { + if (el instanceof HTMLFormElement) { + return el; + } else { + return null; + } + } else { + return null; + } + } + if (form !== undefined) { + return null; + } + return this.el.closest('form'); + } + + private renderHiddenButton() { + const formEl = (this.formEl = this.findForm()); + if (formEl) { + const { formButtonEl } = this; + if (formButtonEl !== null && formEl.contains(formButtonEl)) { + return; + } + const newFormButtonEl = (this.formButtonEl = document.createElement('button')); + newFormButtonEl.type = this.type; + newFormButtonEl.style.display = 'none'; + newFormButtonEl.disabled = this.disabled; + formEl.appendChild(newFormButtonEl); + } + } + private submitForm(ev: Event) { if (this.formEl && this.formButtonEl) { ev.preventDefault(); @@ -48,7 +85,7 @@ export class DButton implements ComponentInterface { private handleClick = (ev: Event) => { const { el } = this; - if (hasShadowDom(el)) { + if (hasShadowDom(el)) { this.submitForm(ev); } }; @@ -63,10 +100,13 @@ export class DButton implements ComponentInterface { render() { const { buttonType, type, disabled, size, href, color, expand, hasIconOnly } = this; - const finalSize = size === undefined ? 'small' : size; + const finalSize = size === undefined ? 'default' : size; const TagType = href === undefined ? 'button' : ('a' as any); const attrs = TagType === 'button' ? { type } : { href }; + { + type !== 'button' && this.renderHiddenButton(); + } return ( { html: ``, }); expect(page.root).toEqualHtml(` - +