Skip to content

Commit

Permalink
support non-string default field values (numbers, booleans, lists of …
Browse files Browse the repository at this point in the history
…them)
  • Loading branch information
konodyuk committed Dec 2, 2023
1 parent 0b760d9 commit 4cce0ac
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/typing/field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export class Field extends DataClass implements Bindable<FieldBindingContext, Fi
if (!this.type.context) {
this.type = this.type.bind({ field: this });
}
this.default = this.type.parseDefault(this.default);
}

bind(context: FieldBindingContext) {
Expand Down
4 changes: 4 additions & 0 deletions src/typing/field_type/base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ export abstract class FieldType<InstanceType extends FieldType = any>
return "";
}

parseDefault(value: any): string {
return `${value}`;
}

bind(context: FieldTypeBindingContext): InstanceType {
let instance = this.copy();
instance.context = context;
Expand Down
10 changes: 10 additions & 0 deletions src/typing/field_type/boolean.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ export class Boolean extends FieldType<Boolean> {
return `false`;
}

parseDefault(value: number | string | boolean): string {
if (typeof value == "boolean") {
return value ? "true" : "false";
}
if (typeof value == "number") {
return value > 0 ? "true" : "false";
}
return value;
}

static ParametersVisitor = () =>
Visitors.ParametersVisitorFactory({
kwargs: {
Expand Down
9 changes: 9 additions & 0 deletions src/typing/field_type/list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ export class List extends FieldType<List> {
return "";
}

parseDefault(value: string | any[]): string {
if (Array.isArray(value)) {
let result = value.map(this.type.parseDefault).join(", ");
if (value.length == 1) result += ",";
return result;
}
return value;
}

bind(context: FieldTypeBindingContext): List {
let result = super.bind(context);
// TODO: there may be some troubles with field name, as it will be the same as of outer type
Expand Down

0 comments on commit 4cce0ac

Please sign in to comment.