Page MenuHomeSealhub

simple-form-field.ts
No OneTemporary

Authored By
Unknown
Size
2 KB
Referenced Files
None
Subscribers
None

simple-form-field.ts

import { FormDataValue } from "../form-types.js";
import { Context } from "koa";
import { predicates } from "@sealcode/ts-predicates";
import { FieldParseResult, FormField } from "./field.js";
import { SimpleInput } from "../controls/simple-input.js";
import { FormControl } from "../controls/controls.js";
import { CollectionItem } from "sealious";
import { FormControlContext } from "../controls/form-control.js";
export abstract class SimpleFormField<
Required extends boolean,
DefaultControl extends FormControl = SimpleInput,
Parsed = string
> extends FormField<Required, Parsed, DefaultControl> {
predicate = predicates.string;
constructor(required: Required, public type: string = "text") {
super(required);
}
async sealiousValueToForm(
ctx: Context,
value: unknown
): Promise<FormDataValue> {
if (value === null) {
return "";
}
return String(value) as FormDataValue;
}
}
export class TextBasedSimpleField<
Required extends boolean,
DefaultControl extends FormControl = SimpleInput
> extends SimpleFormField<Required, DefaultControl, string | null> {
async parse(
_: Context,
raw_value: FormDataValue
): Promise<FieldParseResult<string>> {
return {
parsed_value: (raw_value || "").toString(),
parsable: true,
error: null,
};
}
async getSealiousCreateValue(
fctx: FormControlContext
): Promise<string | null> {
const { parsed } = await this.getParsedValue(
fctx.ctx,
fctx.data.raw_values
);
return parsed || "";
}
async postSealiousCreate(
ctx: Context,
created_item: CollectionItem<any>
): Promise<void> {}
async postSealiousEdit(
ctx: Context,
edited_item: CollectionItem<any>
): Promise<void> {}
getControl(): DefaultControl {
return new SimpleInput(this, {
label: this.name,
type: this.type,
}) as unknown as DefaultControl;
}
public getEmptyValue(): string {
return "";
}
}
export class NumberBasedSimpleField<
Required extends boolean,
DefaultControl extends FormControl = SimpleInput
> extends SimpleFormField<Required, DefaultControl, number> {
async parse(
_: Context,
raw_value: FormDataValue
): Promise<FieldParseResult<number>> {
return {
parsed_value: parseFloat(raw_value as string) || 0,
parsable: true,
error: null,
};
}
async getSealiousCreateValue(
fctx: FormControlContext
): Promise<number | undefined> {
const { parsed } = await this.getParsedValue(
fctx.ctx,
fctx.data.raw_values
);
return parsed || 0;
}
async postSealiousCreate(): Promise<void> {}
async postSealiousEdit(): Promise<void> {}
getControl(): DefaultControl {
return new SimpleInput(this, {
label: this.name,
type: this.type,
}) as unknown as DefaultControl;
}
public getEmptyValue(): number {
return 0;
}
}

File Metadata

Mime Type
application/javascript
Expires
Fri, Nov 27, 16:09 (1 d, 16 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1213685
Default Alt Text
simple-form-field.ts (2 KB)

Event Timeline