Skip to content

Commit

Permalink
add support for formdata event to state-editor web component
Browse files Browse the repository at this point in the history
  • Loading branch information
lexoyo committed Apr 26, 2024
1 parent 3e1c6de commit fb4ce15
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 4 deletions.
22 changes: 22 additions & 0 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,28 @@ export declare class StateEditor extends LitElement {
*/
get value(): string;
set value(newValue: string);
/**
* Form id
* This is the same API as input elements
*/
for: string;
/**
* FormData listener
*/
private onFormdata_;
connectedCallback(): void;
disconnectedCallback(): void;
/**
* Handle formdata event to add the current value to the form
*/
private onFormdata;
/**
* Form setter
* Handle formdata event to add the current value to the form
*/
protected _form: HTMLFormElement | null;
set form(newForm: HTMLFormElement | null);
get form(): HTMLFormElement | null;
/**
* Structured data
*/
Expand Down
6 changes: 3 additions & 3 deletions dist/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

56 changes: 56 additions & 0 deletions src/view/state-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,62 @@ export class StateEditor extends LitElement {
}
}

/**
* Form id
* This is the same API as input elements
*/
@property({type: String, attribute: 'for'})
for = ''

/**
* FormData listener
*/
private onFormdata_ = this.onFormdata.bind(this)

override connectedCallback() {
super.connectedCallback()
// Use the form to add formdata
if(this.for) {
const form = document.querySelector<HTMLFormElement>(`form#${this.for}`)
if(form) {
this.form = form
}
} else {
this.form = this.closest('form')
}
}

override disconnectedCallback() {
this.form = null
super.disconnectedCallback()
}

/**
* Handle formdata event to add the current value to the form
*/
private onFormdata(event: FormDataEvent) {
event.preventDefault()
const formData = event.formData
formData.set(this.name, this.value)
}

/**
* Form setter
* Handle formdata event to add the current value to the form
*/
protected _form: HTMLFormElement | null = null
set form(newForm: HTMLFormElement | null) {
if(this._form) {
this._form.removeEventListener('formdata', this.onFormdata_)
}
if(newForm) {
newForm.addEventListener('formdata', this.onFormdata_)
}
}
get form() {
return this._form
}

/**
* Structured data
*/
Expand Down

0 comments on commit fb4ce15

Please sign in to comment.