diff --git a/src/declaform/declaform.ts b/src/declaform/declaform.ts index 6629342..f8f57f9 100644 --- a/src/declaform/declaform.ts +++ b/src/declaform/declaform.ts @@ -121,6 +121,10 @@ export class Declaform extends HTMLElement { for (const [name, inputs] of inputGroups.entries()) { this._fields.push(new Field(name, inputs)) } + const src = this.getAttribute('src'); + if (src) { + this.hydrateForm(src); + } } get form() { @@ -151,6 +155,24 @@ export class Declaform extends HTMLElement { } return obj; } + + private async hydrateForm(endpoint: string) { + const response = await fetch(endpoint); + const obj = await response.json(); + const populateFields = (current: Record, path: string) => { + for (const key of Object.keys(current)) { + const value = current[key]; + const propPath = (path.length) ? `${path}.${key}` : key; + if (typeof value !== 'object') { + const fields = this.fields.filter(x => x.name === propPath); + fields.forEach(x => x.value = value); + } else { + populateFields(current[key], propPath); + } + } + }; + populateFields(obj, ''); + } } customElements.define('decla-form', Declaform);