dees-catalog/ts_web/elements/dees-form.ts
2021-08-20 00:25:14 +02:00

85 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { customElement, html, TemplateResult, DeesElement } from '@designestate/dees-element';
import { DeesInputCheckbox } from './dees-input-checkbox';
import { DeesInputText } from './dees-input-text';
import { DeesInputQuantitySelector } from './dees-input-quantityselector';
import { DeesInputRadio } from './dees-input-radio';
import * as domtools from '@designestate/dees-domtools';
export type TFormElement = Array<DeesInputCheckbox | DeesInputText | DeesInputQuantitySelector | DeesInputRadio>;
declare global {
interface HTMLElementTagNameMap {
'dees-form': DeesForm;
}
}
@customElement('dees-form')
export class DeesForm extends DeesElement {
public static demo = () => html`
<dees-form style="display: block; margin:auto; max-width: 500px; padding: 20px">
<dees-input-text key="hello1" label="a text"></dees-input-text>
<dees-input-text key="hello2" label="also a text"></dees-input-text>
<dees-input-checkbox key="hello3" label="another text"></dees-input-checkbox>
<dees-form-submit>Submit</dees-form-submit>
</dees-form>
`;
public name: string = 'myform';
public changeSubject = new domtools.rxjs.Subject();
public render(): TemplateResult {
return html`
<style>
:host {
display: contents;
}
</style>
<slot></slot>
`;
}
public firstUpdated() {
const formChildren = this.getFormChildren();
for (const child of formChildren) {
child.changeSubject.subscribe(async (elementArg: TFormElement) => {
const valueObject = await this.gatherData();
this.changeSubject.next(valueObject);
console.log(valueObject);
})
}
}
public getFormChildren() {
const children: Array<DeesElement> = this.children as any;
const formChildren: TFormElement = [];
for (const child of children) {
if (child instanceof DeesInputCheckbox || child instanceof DeesInputText || child instanceof DeesInputQuantitySelector) {
formChildren.push(child);
}
}
return formChildren;
}
public async gatherData() {
const children = this.getFormChildren();
const valueObject: { [key: string]: string | number | boolean} = {};
for (const child of children) {
valueObject[child.key] = child.value;
}
return valueObject;
}
public async gatherAndDispatch() {
const valueObject = await this.gatherData();
const formDataEvent = new CustomEvent('formData', {
detail: {
data: valueObject
},
bubbles: true
});
this.dispatchEvent(formDataEvent);
}
}