Add toJSON implementation.
This commit is contained in:
@@ -1,3 +1,21 @@
|
||||
interface FieldElement {
|
||||
name: string;
|
||||
type: string;
|
||||
value: any;
|
||||
}
|
||||
|
||||
function isFieldElement(x: unknown): x is FieldElement {
|
||||
if (typeof x !== 'object' || !x) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!('name' in x) || !('type' in x) || !('value' in x)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the object that ties a group of inputs to a name.
|
||||
* It assumes that every input in the group is of the same type.
|
||||
@@ -6,13 +24,17 @@ class Field {
|
||||
|
||||
private _type: string;
|
||||
|
||||
constructor(private name: string, private _inputs: FieldElement[]) {
|
||||
constructor(private _name: string, private _inputs: FieldElement[]) {
|
||||
if (this._inputs.length === 0) {
|
||||
throw new Error("[Declaform] Error: cannot construct Field with empty inputs array.")
|
||||
}
|
||||
this._type = this._inputs[0]!.type;
|
||||
}
|
||||
|
||||
get name() {
|
||||
return this._name;
|
||||
}
|
||||
|
||||
get value() {
|
||||
switch(this._type) {
|
||||
case 'checkbox':
|
||||
@@ -109,25 +131,26 @@ export class Declaform extends HTMLElement {
|
||||
return this._fields;
|
||||
}
|
||||
|
||||
toJSON() {}
|
||||
toJSON() {
|
||||
const setProperty = (obj: Record<string, any>, name: string, value: any) => {
|
||||
const [current, children] = name.split('.');
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
if (!children) {
|
||||
obj[current] = value;
|
||||
return;
|
||||
}
|
||||
const iter_obj = obj[current] ?? {};
|
||||
setProperty(iter_obj, children, value);
|
||||
obj[current] = iter_obj;
|
||||
};
|
||||
let obj = {};
|
||||
for (const field of this._fields) {
|
||||
setProperty(obj, field.name, field.value)
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('decla-form', Declaform);
|
||||
|
||||
interface FieldElement {
|
||||
name: string;
|
||||
type: string;
|
||||
value: any;
|
||||
}
|
||||
|
||||
function isFieldElement(x: unknown): x is FieldElement {
|
||||
if (typeof x !== 'object' || !x) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!('name' in x) || !('type' in x) || !('value' in x)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
Reference in New Issue
Block a user