Skip to content

Commit

Permalink
fix: button type submit (#50)
Browse files Browse the repository at this point in the history
* fix: button type submit

* test: update
  • Loading branch information
phoebus-84 authored Feb 15, 2024
1 parent 4b2cd38 commit b0b8c81
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
46 changes: 43 additions & 3 deletions src/components/button/d-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,48 @@ export class DButton implements ComponentInterface {
@Event() dFocus!: EventEmitter<void>;
@Event() dBlur!: EventEmitter<void>;


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();
Expand All @@ -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);
}
};
Expand All @@ -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 (
<Host
onClick={this.handleClick}
Expand Down
2 changes: 1 addition & 1 deletion src/components/button/test/d-button.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ describe('d-button', () => {
html: `<d-button></d-button>`,
});
expect(page.root).toEqualHtml(`
<d-button class="button button-small primary" color="primary">
<d-button class="button button-default primary" color="primary">
<mock:shadow-root>
<button class="button-native primary" part="native" type="button">
<span class="button-inner">
Expand Down

0 comments on commit b0b8c81

Please sign in to comment.