Page Menu
Home
Sealhub
Search
Configure Global Search
Log In
Files
F22422110
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Flag For Later
Award Token
Authored By
Unknown
Size
38 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/src/forms/controls/checkboxed-list-input.ts b/src/forms/controls/checkboxed-list-input.ts
index 34f09c6..77db135 100644
--- a/src/forms/controls/checkboxed-list-input.ts
+++ b/src/forms/controls/checkboxed-list-input.ts
@@ -1,39 +1,39 @@
import { is, predicates } from "@sealcode/ts-predicates";
import { BaseContext } from "koa";
import { tempstream } from "tempstream";
-import { ChekboxedListField } from "../field";
+import { ChekboxedListField } from "../fields/field";
import { FormDataValue } from "../form";
import { FormFieldControl } from "./controls";
export class CheckboxedListInput extends FormFieldControl {
constructor(
public field: ChekboxedListField,
public options: { label: string } = { label: field.name }
) {
super([field]);
}
async render(ctx: BaseContext, data: Record<string, FormDataValue>) {
const { parsed: pickedValues } = await this.field.getValue(ctx, data);
if (!is(pickedValues, predicates.array(predicates.string))) {
throw new Error("picked values is not an array of strings");
}
const [options, isVisible] = await Promise.all([
this.field.generateOptions(ctx),
this.field.isVisible(ctx),
]);
return tempstream/* HTML */ `${isVisible
? Object.entries(options).map(
([value, text]) => /* HTML */ `<div>
<input
type="checkbox"
id="${this.field.name}.${value}"
name="${this.field.name}.${value}"
${pickedValues.includes(value) ? "checked" : ""}
/>
<label for="${this.field.name}.${value}">${text}</label>
</div>`
)
: ""}`;
}
}
diff --git a/src/forms/controls/dropdown.ts b/src/forms/controls/dropdown.ts
index 85979c1..75ff48d 100644
--- a/src/forms/controls/dropdown.ts
+++ b/src/forms/controls/dropdown.ts
@@ -1,52 +1,52 @@
import { BaseContext } from "koa";
import { tempstream } from "tempstream";
-import { FormField, PickFromListField } from "../field";
+import { FormField, PickFromListField } from "../fields/field";
import { FormDataValue } from "../form";
import { FormFieldControl } from "./controls";
export class Dropdown extends FormFieldControl {
constructor(
public field: PickFromListField,
public options: {
label: string;
autosubmit?: boolean;
autocomplete?: boolean;
} = {
label: field.name,
autosubmit: false,
autocomplete: true,
}
) {
super([field]);
}
async render<Fields extends Record<string, FormField>>(
ctx: BaseContext,
data: Record<string, FormDataValue>
) {
const { parsed: picked_value } = await this.field.getValue(ctx, data);
const id = this.field.name;
return tempstream/* HTML */ `<label for="${id}"
>${this.options.label}</label
><select
name="${this.field.name}"
id="${id}"
${this.options.autosubmit
? `onchange='this.form.submit()'`
: ""}
${!this.options.autocomplete ? `autocomplete="off"` : ""}
>
${Promise.resolve(this.field.generateOptions(ctx)).then(
(options) =>
Object.entries(options).map(
([value, text]) =>
`<option value="${value}" ${
(value || "") == picked_value
? "selected"
: ""
}>${text}</option>`
)
)}
</select>`;
}
}
diff --git a/src/forms/controls/editable-collection-subset.ts b/src/forms/controls/editable-collection-subset.ts
index cc16d6a..466260f 100644
--- a/src/forms/controls/editable-collection-subset.ts
+++ b/src/forms/controls/editable-collection-subset.ts
@@ -1,87 +1,87 @@
import { BaseContext } from "koa";
import { FlatTemplatable, tempstream } from "tempstream";
-import { PickFromListField } from "../field";
+import { PickFromListField } from "../fields/field";
import { FormDataValue } from "../form";
import { FormFieldControl } from "./controls";
/**
* This control has own forms in it so if you want to use it you
* probably shouldn't use `await super.render(ctx, data, path)` in
* render method of you from implementation and you should write
* your own implementation of this method. See forms that uses
* this control for reference.
*/
export class EditableCollectionSubset extends FormFieldControl {
constructor(
public field: PickFromListField,
public actionname: string,
public listLabel?: string,
public selectLabel?: string
) {
super([field]);
}
async render(
ctx: BaseContext,
data: Record<string, FormDataValue>
): Promise<FlatTemplatable> {
const { parsed: values } = await this.field.getValue(ctx, data);
return tempstream/* HTML */ `<div>
<ul>
${Promise.resolve(this.field.generateOptions(ctx)).then(
(options) =>
Object.entries(options)
.filter(([value]) => values.includes(value))
.map(
([value, text]) => /* HTML */ `
<li>
<form
method="POST"
action="${ctx.path}"
>
<span>${text}</span>
<input
type="hidden"
name="${this.field.name}"
value="${value}"
/>
<input
type="hidden"
name="${this.actionname}"
value="list"
/>
<input
type="submit"
${this.listLabel
? `value="${this.listLabel}"`
: ""}
/>
</form>
</li>
`
)
)}
</ul>
<form method="POST" action="${ctx.path}">
<select name="${this.field.name}">
${Promise.resolve(this.field.generateOptions(ctx)).then(
(options) =>
Object.entries(options)
.filter(([value]) => !values.includes(value))
.map(
([value, text]) =>
`<option value="${value}">${text}</option>`
)
)}
</select>
<input type="hidden" name="${this.actionname}" value="select" />
<input
type="submit"
${this.selectLabel ? `value="${this.selectLabel}"` : ""}
/>
</form>
</div>`;
}
role = <const>"input";
}
diff --git a/src/forms/controls/form-field-control.ts b/src/forms/controls/form-field-control.ts
index 11447bd..1d056dc 100644
--- a/src/forms/controls/form-field-control.ts
+++ b/src/forms/controls/form-field-control.ts
@@ -1,23 +1,23 @@
import { BaseContext } from "koa";
import { FlatTemplatable } from "tempstream";
-import { FormField } from "../field";
-import { FieldValueType, FormData, FormDataValue } from "../form";
+import { FormField } from "../fields/field";
+import { FieldValueType, FormDataValue } from "../form";
import { FormControl } from "./form-control";
export type FormFieldsToTypes<FormFields extends readonly FormField[]> = {
[Index in keyof FormFields]: FormFields[Index] extends FormField
? FieldValueType<FormFields[Index]>
: never;
};
export abstract class FormFieldControl extends FormControl {
role = <const>"input";
constructor(public fields: FormField[]) {
super();
}
abstract render(
ctx: BaseContext,
data: Record<string, FormDataValue>
): FlatTemplatable | Promise<FlatTemplatable>;
}
diff --git a/src/forms/controls/simple-input.ts b/src/forms/controls/simple-input.ts
index 3a30a42..6e719c9 100644
--- a/src/forms/controls/simple-input.ts
+++ b/src/forms/controls/simple-input.ts
@@ -1,73 +1,75 @@
import { BaseContext } from "koa";
-import { FormField, NumberField, SimpleFormField } from "../field";
+import { FormField } from "../fields/field";
+import { NumberField } from "../fields/number";
+import { SimpleFormField } from "../fields/simple-form-field";
import { FormDataValue } from "../form";
import { FormFieldControl } from "./controls";
export class SimpleInput extends FormFieldControl {
constructor(
public field: SimpleFormField | NumberField<number | null>,
public options: {
id?: string;
label?: string;
autocomplete?: boolean;
type?:
| "color"
| "date"
| "email"
| "file"
| "month"
| "number"
| "password"
| "search"
| "tel"
| "text"
| "time"
| "url"
| "week";
value?: string;
placeholder?: string;
readonly?: boolean;
step?: number;
} = {}
) {
super([field]);
}
async render<Fields extends Record<string, FormField>>(
ctx: BaseContext,
data: Record<string, FormDataValue>
) {
const id = this.options.id || this.field.name;
const label = this.options.label || this.field.name;
const type = this.options.type || "text";
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const { parsed, raw, valid, message } = await this.field.getValue(
ctx,
data
);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const placeholder = this.options.placeholder || type;
const readonly = this.options.readonly || false;
const required = this.field.required;
return /* HTML */ `<div class="input">
<label for="${id}">${label}</label>
<input
id="${id}"
type="${type}"
name="${this.field.name}"
value="${!valid && raw
? raw.toString()
: parsed !== undefined && parsed !== null
? parsed.toString()
: ""}"
placeholder="${placeholder}"
${readonly ? "readonly" : ""}
${required ? "required" : ""}
${!this.options.autocomplete ? `autocomplete="off"` : ""}
${this.options.step ? `step="${this.options.step}"` : ""}
/>
${~valid ? `<div class="input__error">${message}</div>` : ""}
</div>`;
}
}
diff --git a/src/forms/field.ts b/src/forms/field.ts
deleted file mode 100644
index d99e1b8..0000000
--- a/src/forms/field.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-import { is, predicates } from "@sealcode/ts-predicates";
-import { BaseContext } from "koa";
-import { FormDataValue } from "..";
-
-export type FormFieldValidationResponse = { valid: boolean; message: string };
-
-export type FormFieldValidationFn<ValueType> = (
- ctx: BaseContext,
- value: ValueType,
- field: FormField<ValueType>
-) => Promise<FormFieldValidationResponse>;
-
-export type FieldParsedValue<T> = T extends FormField<infer R> ? R : never;
-
-export type FieldParseResult<T> =
- | {
- parsable: false;
- error: string;
- parsed_value: null;
- }
- | { parsable: true; error: null; parsed_value: T };
-
-export abstract class FormField<ParsedValue extends unknown = unknown> {
- name: string;
- constructor(public required: boolean = false) {}
-
- init(fieldname: string): void {
- this.name = fieldname;
- }
-
- public async _validate(
- ctx: BaseContext,
- value: ParsedValue
- ): Promise<FormFieldValidationResponse> {
- if (
- this.required &&
- (value === "" || value === null || value === undefined)
- ) {
- return { valid: false, message: "This field is required" };
- }
- return this.isValueValid(ctx, value);
- }
-
- public abstract getEmptyValue(): ParsedValue;
-
- public async isValueValid(
- ctx: BaseContext,
- value: ParsedValue
- ): Promise<FormFieldValidationResponse> {
- return { valid: true, message: "" };
- }
-
- abstract parse(
- raw_value: FormDataValue
- ): Promise<FieldParseResult<ParsedValue>>;
-
- async getValue(
- ctx: BaseContext,
- all_form_values: Record<string, FormDataValue>
- ): Promise<{
- valid: boolean;
- message: string;
- parsed: ParsedValue;
- raw: FormDataValue;
- }> {
- if (Object.keys(all_form_values).length === 0) {
- // don't validate on virgin form
- return {
- parsed: this.getEmptyValue(),
- valid: true,
- message: "",
- raw: "",
- };
- }
- const raw = all_form_values[this.name];
- const {
- parsable,
- parsed_value,
- error: parse_error,
- } = await this.parse(raw);
- if (!parsable) {
- return {
- valid: false,
- parsed: this.getEmptyValue(),
- raw,
- message: parse_error || "Error",
- };
- }
- const { valid, message } = await this._validate(
- ctx,
- parsed_value as ParsedValue
- );
- return {
- parsed: parsed_value as ParsedValue,
- valid,
- message,
- raw: all_form_values[this.name],
- };
- }
-}
-
-export class SimpleFormField extends FormField<string> {
- async parse(raw_value: FormDataValue): Promise<FieldParseResult<string>> {
- return {
- parsed_value: (raw_value || "").toString(),
- parsable: true,
- error: null,
- };
- }
-
- public getEmptyValue(): string {
- return "";
- }
-}
-
-export class PickFromListField extends SimpleFormField {
- constructor(
- public required: boolean = false,
- public generateOptions: (
- ctx: BaseContext
- ) => Promise<Record<string, string> | { [i: string]: string }>,
- public customValidation: (
- ctx: BaseContext,
- value: unknown,
- instance: PickFromListField
- ) => Promise<FormFieldValidationResponse> = (ctx, value, instance) =>
- instance.valueInList(ctx, value)
- ) {
- super(required);
- }
-
- public isValueValid(
- ctx: BaseContext,
- value: string
- ): Promise<FormFieldValidationResponse> {
- return this.customValidation(ctx, value, this);
- }
-
- async valueInList(
- ctx: BaseContext,
- value: unknown
- ): Promise<FormFieldValidationResponse> {
- const options = await this.generateOptions(ctx);
- if (!is(value, predicates.string)) {
- return { valid: false, message: "not a string" };
- }
- if (!Object.keys(options).includes(value)) {
- return {
- valid: false,
- message: `"${value}" is not one of the options`,
- };
- }
- return { valid: true, message: "" };
- }
-
- public getEmptyValue(): string {
- return "";
- }
-}
-
-export class ChekboxedListField extends FormField<Record<string, "on">> {
- constructor(
- public required: boolean = false,
- public generateOptions: (
- ctx: BaseContext
- ) => Promise<Record<string, string> | { [i: string]: string }>,
- public isVisible: (ctx: BaseContext) => Promise<boolean> = () =>
- Promise.resolve(true)
- ) {
- super(required);
- }
-
- public async isValueValid(
- _: BaseContext,
- value: unknown
- ): Promise<FormFieldValidationResponse> {
- if (is(value, predicates.string)) {
- return { valid: false, message: "you need an array" };
- }
- if (is(value, predicates.null)) {
- return { valid: false, message: "you need an array" };
- }
- return { valid: true, message: "" };
- }
-
- async parse(
- raw_value: FormDataValue
- ): Promise<FieldParseResult<Record<string, "on">>> {
- if (is(raw_value, predicates.object)) {
- return {
- parsable: true,
- parsed_value: Object.fromEntries(
- Object.entries(raw_value).filter(
- ([, value]) => value === "on"
- )
- ) as Record<string, "on">,
- error: null,
- };
- } else {
- return {
- parsed_value: null,
- parsable: false,
- error: "Expected an object",
- };
- }
- }
-
- public getEmptyValue(): Record<string, "on"> {
- return {};
- }
-}
-
-export class NumberField<
- DefaultValue extends number | null = null
-> extends FormField<number | DefaultValue> {
- constructor(required = false, public default_value: DefaultValue) {
- super(required);
- }
-
- public async isValueValid(_: BaseContext, value: unknown) {
- if (
- (is(value, predicates.string) &&
- !isNaN(parseFloat(value)) &&
- parseFloat(value).toString() == value.trim()) ||
- is(value, predicates.number) ||
- ((is(value, predicates.undefined) || value == "") && !this.required)
- ) {
- return { valid: true, message: "" };
- }
- return { valid: false, message: "Proszę wprowadzić liczbę" };
- }
-
- async parse(value: FormDataValue): Promise<FieldParseResult<number>> {
- if (
- (is(value, predicates.string) &&
- !isNaN(parseFloat(value)) &&
- parseFloat(value).toString() == value.trim()) ||
- is(value, predicates.number)
- ) {
- return {
- parsable: true,
- parsed_value: parseFloat(value.toString()),
- error: null,
- };
- } else {
- return {
- parsable: false,
- parsed_value: null,
- error: "Please enter a number",
- };
- }
- }
-
- public getEmptyValue(): DefaultValue {
- return this.default_value;
- }
-}
diff --git a/src/forms/fields/checkboxed-list.ts b/src/forms/fields/checkboxed-list.ts
new file mode 100644
index 0000000..92e4516
--- /dev/null
+++ b/src/forms/fields/checkboxed-list.ts
@@ -0,0 +1,60 @@
+import { is, predicates } from "@sealcode/ts-predicates";
+import { BaseContext } from "koa";
+import { FormDataValue } from "../form";
+import {
+ FieldParseResult,
+ FormField,
+ FormFieldValidationResponse,
+} from "./field";
+
+export class ChekboxedListField extends FormField<Record<string, "on">> {
+ constructor(
+ public required: boolean = false,
+ public generateOptions: (
+ ctx: BaseContext
+ ) => Promise<Record<string, string> | { [i: string]: string }>,
+ public isVisible: (ctx: BaseContext) => Promise<boolean> = () =>
+ Promise.resolve(true)
+ ) {
+ super(required);
+ }
+
+ public async isValueValid(
+ _: BaseContext,
+ value: unknown
+ ): Promise<FormFieldValidationResponse> {
+ if (is(value, predicates.string)) {
+ return { valid: false, message: "you need an array" };
+ }
+ if (is(value, predicates.null)) {
+ return { valid: false, message: "you need an array" };
+ }
+ return { valid: true, message: "" };
+ }
+
+ async parse(
+ raw_value: FormDataValue
+ ): Promise<FieldParseResult<Record<string, "on">>> {
+ if (is(raw_value, predicates.object)) {
+ return {
+ parsable: true,
+ parsed_value: Object.fromEntries(
+ Object.entries(raw_value).filter(
+ ([, value]) => value === "on"
+ )
+ ) as Record<string, "on">,
+ error: null,
+ };
+ } else {
+ return {
+ parsed_value: null,
+ parsable: false,
+ error: "Expected an object",
+ };
+ }
+ }
+
+ public getEmptyValue(): Record<string, "on"> {
+ return {};
+ }
+}
diff --git a/src/forms/fields/field.ts b/src/forms/fields/field.ts
new file mode 100644
index 0000000..1524b83
--- /dev/null
+++ b/src/forms/fields/field.ts
@@ -0,0 +1,104 @@
+import { BaseContext } from "koa";
+import { FormDataValue } from "../form";
+
+export type FormFieldValidationResponse = { valid: boolean; message: string };
+
+export type FormFieldValidationFn<ValueType> = (
+ ctx: BaseContext,
+ value: ValueType,
+ field: FormField<ValueType>
+) => Promise<FormFieldValidationResponse>;
+
+export type FieldParsedValue<T> = T extends FormField<infer R> ? R : never;
+
+export type FieldParseResult<T> =
+ | {
+ parsable: false;
+ error: string;
+ parsed_value: null;
+ }
+ | { parsable: true; error: null; parsed_value: T };
+
+export abstract class FormField<ParsedValue extends unknown = unknown> {
+ name: string;
+ constructor(public required: boolean = false) {}
+
+ init(fieldname: string): void {
+ this.name = fieldname;
+ }
+
+ public async _validate(
+ ctx: BaseContext,
+ value: ParsedValue
+ ): Promise<FormFieldValidationResponse> {
+ if (
+ this.required &&
+ (value === "" || value === null || value === undefined)
+ ) {
+ return { valid: false, message: "This field is required" };
+ }
+ return this.isValueValid(ctx, value);
+ }
+
+ public abstract getEmptyValue(): ParsedValue;
+
+ public async isValueValid(
+ ctx: BaseContext,
+ value: ParsedValue
+ ): Promise<FormFieldValidationResponse> {
+ return { valid: true, message: "" };
+ }
+
+ abstract parse(
+ raw_value: FormDataValue
+ ): Promise<FieldParseResult<ParsedValue>>;
+
+ async getValue(
+ ctx: BaseContext,
+ all_form_values: Record<string, FormDataValue>
+ ): Promise<{
+ valid: boolean;
+ message: string;
+ parsed: ParsedValue;
+ raw: FormDataValue;
+ }> {
+ if (Object.keys(all_form_values).length === 0) {
+ // don't validate on virgin form
+ return {
+ parsed: this.getEmptyValue(),
+ valid: true,
+ message: "",
+ raw: "",
+ };
+ }
+ const raw = all_form_values[this.name];
+ const {
+ parsable,
+ parsed_value,
+ error: parse_error,
+ } = await this.parse(raw);
+ if (!parsable) {
+ return {
+ valid: false,
+ parsed: this.getEmptyValue(),
+ raw,
+ message: parse_error || "Error",
+ };
+ }
+ const { valid, message } = await this._validate(
+ ctx,
+ parsed_value as ParsedValue
+ );
+ return {
+ parsed: parsed_value as ParsedValue,
+ valid,
+ message,
+ raw: all_form_values[this.name],
+ };
+ }
+}
+
+export * from "./simple-form-field";
+export * from "./checkboxed-list";
+export * from "./number";
+export * from "./pick-from-list";
diff --git a/src/forms/fields/number.ts b/src/forms/fields/number.ts
new file mode 100644
index 0000000..442de6a
--- /dev/null
+++ b/src/forms/fields/number.ts
@@ -0,0 +1,50 @@
+import { is, predicates } from "@sealcode/ts-predicates";
+import { BaseContext } from "koa";
+import { FormDataValue } from "../form";
+import { FieldParseResult, FormField } from "./field";
+
+export class NumberField<
+ DefaultValue extends number | null = null
+> extends FormField<number | DefaultValue> {
+ constructor(required = false, public default_value: DefaultValue) {
+ super(required);
+ }
+
+ public async isValueValid(_: BaseContext, value: unknown) {
+ if (
+ (is(value, predicates.string) &&
+ !isNaN(parseFloat(value)) &&
+ parseFloat(value).toString() == value.trim()) ||
+ is(value, predicates.number) ||
+ ((is(value, predicates.undefined) || value == "") && !this.required)
+ ) {
+ return { valid: true, message: "" };
+ }
+ return { valid: false, message: "Proszę wprowadzić liczbę" };
+ }
+
+ async parse(value: FormDataValue): Promise<FieldParseResult<number>> {
+ if (
+ (is(value, predicates.string) &&
+ !isNaN(parseFloat(value)) &&
+ parseFloat(value).toString() == value.trim()) ||
+ is(value, predicates.number)
+ ) {
+ return {
+ parsable: true,
+ parsed_value: parseFloat(value.toString()),
+ error: null,
+ };
+ } else {
+ return {
+ parsable: false,
+ parsed_value: null,
+ error: "Please enter a number",
+ };
+ }
+ }
+
+ public getEmptyValue(): DefaultValue {
+ return this.default_value;
+ }
+}
diff --git a/src/forms/fields/pick-from-list.ts b/src/forms/fields/pick-from-list.ts
new file mode 100644
index 0000000..0380a9e
--- /dev/null
+++ b/src/forms/fields/pick-from-list.ts
@@ -0,0 +1,49 @@
+import { is, predicates } from "@sealcode/ts-predicates";
+import { BaseContext } from "koa";
+import { FormFieldValidationResponse } from "./field";
+import { SimpleFormField } from "./simple-form-field";
+
+export class PickFromListField extends SimpleFormField {
+ constructor(
+ public required: boolean = false,
+ public generateOptions: (
+ ctx: BaseContext
+ ) => Promise<Record<string, string> | { [i: string]: string }>,
+ public customValidation: (
+ ctx: BaseContext,
+ value: unknown,
+ instance: PickFromListField
+ ) => Promise<FormFieldValidationResponse> = (ctx, value, instance) =>
+ instance.valueInList(ctx, value)
+ ) {
+ super(required);
+ }
+
+ public isValueValid(
+ ctx: BaseContext,
+ value: string
+ ): Promise<FormFieldValidationResponse> {
+ return this.customValidation(ctx, value, this);
+ }
+
+ async valueInList(
+ ctx: BaseContext,
+ value: unknown
+ ): Promise<FormFieldValidationResponse> {
+ const options = await this.generateOptions(ctx);
+ if (!is(value, predicates.string)) {
+ return { valid: false, message: "not a string" };
+ }
+ if (!Object.keys(options).includes(value)) {
+ return {
+ valid: false,
+ message: `"${value}" is not one of the options`,
+ };
+ }
+ return { valid: true, message: "" };
+ }
+
+ public getEmptyValue(): string {
+ return "";
+ }
+}
diff --git a/src/forms/fields/simple-form-field.ts b/src/forms/fields/simple-form-field.ts
new file mode 100644
index 0000000..69457bd
--- /dev/null
+++ b/src/forms/fields/simple-form-field.ts
@@ -0,0 +1,16 @@
+import { FieldParseResult, FormField } from "./field";
+import { FormDataValue } from "../form";
+
+export class SimpleFormField extends FormField<string> {
+ async parse(raw_value: FormDataValue): Promise<FieldParseResult<string>> {
+ return {
+ parsed_value: (raw_value || "").toString(),
+ parsable: true,
+ error: null,
+ };
+ }
+
+ public getEmptyValue(): string {
+ return "";
+ }
+}
diff --git a/src/forms/form-fields-list.ts b/src/forms/form-fields-list.ts
deleted file mode 100644
index 4cb1298..0000000
--- a/src/forms/form-fields-list.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { FormField } from "./field";
-
-export class FormFieldsList {
- static getField(fields: FormField[], name: string) {
- return fields.find((f) => f.name == name);
- }
-}
diff --git a/src/forms/form.ts b/src/forms/form.ts
index 5703b59..84007af 100644
--- a/src/forms/form.ts
+++ b/src/forms/form.ts
@@ -1,174 +1,174 @@
import { BaseContext } from "koa";
import Router from "@koa/router";
import { FlatTemplatable, Templatable, tempstream } from "tempstream";
import {
hasFieldOfType,
hasShape,
is,
predicates,
} from "@sealcode/ts-predicates";
-import { FormField } from "./field";
+import { FormField } from "./fields/field";
import { Fields, Mountable, PageErrorMessage } from "../page/mountable";
export type FormDataPrimitive = string | string[] | undefined;
export type FormDataValue =
| FormDataPrimitive
| Record<string, FormDataPrimitive>;
export type FieldValueType<F extends FormField> = F extends FormField<infer R>
? R
: never;
export type FormFieldsToValues<F extends Record<string, FormField<keyof F>>> = {
[Property in keyof F]: FieldValueType<F[Property]>;
};
export type FormMessage = { type: "info" | "success" | "error"; text: string };
export type FormData<Fieldnames extends string = string> = {
raw_values: Record<Fieldnames, FormDataValue>;
messages: FormMessage[];
};
export abstract class Form<F extends Fields> extends Mountable<F> {
defaultSuccessMessage = "Done";
submitButtonText = "Wyślij";
async canAccess(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_: BaseContext
): Promise<{ canAccess: boolean; message: string }> {
return { canAccess: true, message: "" };
}
async renderError(
_: BaseContext,
error: PageErrorMessage
): Promise<Templatable> {
return tempstream/* HTML */ `<div>${error.message}</div>`;
}
async render(ctx: BaseContext, data: FormData): Promise<Templatable> {
return tempstream/* HTML */ `${this.makeFormTag()} ${
!this.controls.some((control) => control.role == "messages")
? this.renderMessages(ctx, data)
: ""
} ${this.renderControls(ctx, data)}<input type="submit" value="${
this.submitButtonText
}"/></form>`;
}
public makeFormTag(): FlatTemplatable {
return `<form method="POST" action="./">`;
}
public async onValuesInvalid(
ctx: BaseContext,
form_messages: FormMessage[]
): Promise<void> {
ctx.status = 422;
ctx.body = await this.render(ctx, {
raw_values: ctx.$body,
messages: form_messages.length
? form_messages
: [{ type: "error", text: "Some fields are invalid" }],
});
}
public async onError(
ctx: BaseContext,
data: FormData,
error: unknown
): Promise<void> {
ctx.status = 422;
let error_message = "Unknown error has occured";
if (
is(error, predicates.object) &&
hasShape({ message: predicates.string }, error)
) {
error_message = error.message;
}
ctx.body = await this.render(ctx, {
raw_values: data.raw_values,
messages: [{ type: "error", text: error_message }],
});
}
public abstract onSubmit(
ctx: BaseContext,
data: FormData
): void | Promise<void>;
public async onSuccess(ctx: BaseContext): Promise<void> {
ctx.body = await this.render(ctx, {
raw_values: ctx.$body,
messages: [{ type: "success", text: this.defaultSuccessMessage }],
});
ctx.status = 422;
}
public mount(router: Router, path: string): void {
router.use(path, async (ctx, next) => {
const result = await this.canAccess(ctx);
if (!result.canAccess) {
ctx.body = this.renderError(ctx, {
type: "access",
message: result.message,
});
ctx.status = 403;
return;
}
await next();
});
router.get(path, async (ctx) => {
ctx.type = "html";
ctx.body = await this.render(ctx, { raw_values: {}, messages: [] });
});
router.post(path, async (ctx) => {
const { valid, form_messages } = await this.validate(
ctx,
ctx.$body
);
if (!valid) {
await this.onValuesInvalid(ctx, form_messages);
return;
}
try {
await this.onSubmit(ctx, {
raw_values: ctx.$body,
messages: [],
});
await this.onSuccess(ctx);
} catch (e: unknown) {
// eslint-disable-next-line no-console
console.dir(e, { depth: 5 });
const message =
is(e, predicates.object) &&
hasFieldOfType(e, "message", predicates.string)
? e?.message
: is(e, predicates.string)
? e
: "Wystąpił błąd";
await this.onError(
ctx,
{
raw_values: ctx.$body,
messages: [
{
type: "error",
text: message,
},
],
},
e
);
}
});
}
extractRawValues(ctx: BaseContext): Record<string, FormDataValue> {
return ctx.$body;
}
}
diff --git a/src/forms/validator.ts b/src/forms/validator.ts
deleted file mode 100644
index b177eb5..0000000
--- a/src/forms/validator.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { BaseContext } from "koa";
-import { Field } from "sealious";
-import { FieldParsedValue } from "..";
-import { FormFieldValidationFn } from "./field";
-
-export function collectionFieldValidator<F extends Field>(
- field: F
-): FormFieldValidationFn<FieldParsedValue<F>> {
- return async (ctx: BaseContext, value) => {
- const { valid, reason } = await field.checkValue(
- ctx.$context,
- value,
- undefined
- );
- return { valid, message: reason || (valid ? "Wrong value" : "") };
- };
-}
diff --git a/src/index.ts b/src/index.ts
index 006a399..c677a58 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,19 +1,18 @@
import Sealious from "sealious";
import { FormDataValue } from "./forms/form";
declare module "koa" {
interface BaseContext {
$context: Sealious.Context;
$body: Record<string, FormDataValue>;
}
}
export * from "./forms/controls/controls";
-export * from "./forms/field";
+export * from "./forms/fields/field";
export * from "./page/mountable";
export * from "./page/page";
export * from "./forms/form";
export * from "./page/props-parser";
export * from "./utils/utils";
-export * from "./forms/validator";
export * from "./page/list";
diff --git a/src/page/list.ts b/src/page/list.ts
index 3bf51e6..4c152a4 100644
--- a/src/page/list.ts
+++ b/src/page/list.ts
@@ -1,172 +1,172 @@
import { BaseContext } from "koa";
import { Collection, CollectionItem } from "sealious";
import { Templatable, tempstream, FlatTemplatable } from "tempstream";
import { peopleWhoCan } from "./access-control";
import { Page } from "./page";
import { ShapeToType } from "@sealcode/ts-predicates";
import { FormFieldControl } from "../forms/controls/controls";
-import { FormField, NumberField } from "../forms/field";
+import { FormField, NumberField } from "../forms/fields/field";
import { naturalNumbers, UrlWithNewParams } from "../utils/utils";
import { FormDataValue } from "..";
import { makeHiddenInputs } from "../make-hidden-inputs";
export const BasePagePropsShape = <const>{};
export type BasePageProps = ShapeToType<typeof BasePagePropsShape>;
export const BaseListPageFields = <const>{
page: new NumberField(false, 1),
itemsPerPage: new NumberField(false, 12),
};
export abstract class ListPage<
ItemType,
F extends typeof BaseListPageFields
> extends Page<F> {
abstract getItems(
ctx: BaseContext,
page: number,
itemsPerPage: number,
values: Record<string, FormDataValue>
): Promise<ItemType[]>;
abstract getTotalPages(
ctx: BaseContext,
itemsPerPage: number,
values: Record<string, FormDataValue>
): Promise<number>;
abstract renderItem(
ctx: BaseContext,
item: ItemType
): Promise<FlatTemplatable>;
filterFields: Record<string, FormField<keyof Record<string, unknown>>>;
filterControls: FormFieldControl[] = [];
renderListContainer(_: BaseContext, content: Templatable): FlatTemplatable {
return tempstream`<div>${content}</div>`;
}
async render(ctx: BaseContext): Promise<FlatTemplatable> {
const values = this.extractRawValues(ctx);
const { parsed: page } = await this.fields.page.getValue(ctx, values);
const { parsed: itemsPerPage } =
await this.fields.itemsPerPage.getValue(ctx, values);
return tempstream`${this.renderPagination(ctx, values)}
${this.renderFilters(ctx, values)}
${this.getItems(ctx, page, itemsPerPage, values).then((items) =>
this.renderListContainer(
ctx,
items.map((item) => this.renderItem(ctx, item))
)
)}`;
}
async renderPagination(
ctx: BaseContext,
values: Record<string, FormDataValue>
): Promise<FlatTemplatable> {
const { parsed: page } = await this.fields.page.getValue(ctx, values);
const { parsed: itemsPerPage } =
await this.fields.itemsPerPage.getValue(ctx, values);
const totalIems = await this.getTotalPages(ctx, itemsPerPage, values);
return tempstream/* HTML */ `<center>
${page > 1 ? this.renderPageButton(ctx, 1, "Pierwsza strona") : ""}
${page > 1
? this.renderPageButton(ctx, page - 1, "Poprzednia strona")
: ""}
<select onchange="if (this.value) Turbo.visit(this.value)">
${Array.from(naturalNumbers(1, totalIems)).map(
(n) => /* HTML */ `<option
value="${UrlWithNewParams(
ctx,
//eslint-disable-next-line @typescript-eslint/consistent-type-assertions
this.propsParser.overwriteProp(ctx, {
page: n,
} as Partial<Record<string, unknown>>)
)}"
${page === n ? "selected" : ""}
>
${n}
</option>`
)}
</select>
${page < totalIems
? this.renderPageButton(ctx, page + 1, "Następna strona")
: ""}
${page < totalIems
? this.renderPageButton(ctx, totalIems, "Ostatnia strona")
: ""}
</center>`;
}
private renderPageButton(ctx: BaseContext, page: number, text: string) {
return /* HTML */ `<a
href="${UrlWithNewParams(
ctx,
//eslint-disable-next-line @typescript-eslint/consistent-type-assertions
this.propsParser.overwriteProp(ctx, {
page,
} as Partial<Record<string, unknown>>)
)}"
>${text}</a
>`;
}
renderFilters(
ctx: BaseContext,
values: Record<string, FormDataValue>
): FlatTemplatable {
return tempstream/* HTML */ `<form method="GET">
${makeHiddenInputs(ctx, this.fields, values, [
"page",
...Object.values(this.filterFields).map((f) => f.name),
])}
${this.filterControls.map((control) =>
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
control.render(ctx, values)
)}
</form>`;
}
}
export abstract class SealiousItemListPage<
C extends Collection,
F extends typeof BaseListPageFields
> extends ListPage<CollectionItem<C>, F> {
constructor(public collection: C) {
super();
}
async getTotalPages(
ctx: BaseContext,
itemsPerPage: number
): Promise<number> {
const { items } = await this.collection.list(ctx.$context).fetch();
return Math.ceil(items.length / itemsPerPage);
}
async getItems(
ctx: BaseContext,
page: number,
itemsPerPage: number
): Promise<CollectionItem<C>[]> {
const { items } = await this.collection
.list(ctx.$context)
.paginate({ items: itemsPerPage, page })
.fetch();
return items;
}
async renderItem(
_: BaseContext,
item: CollectionItem<C>
): Promise<FlatTemplatable> {
return `<div>${item.id}</div>`;
}
canAccess = peopleWhoCan("list", this.collection);
}
diff --git a/src/page/mountable.ts b/src/page/mountable.ts
index be0c7b3..ca3b709 100644
--- a/src/page/mountable.ts
+++ b/src/page/mountable.ts
@@ -1,105 +1,105 @@
import Router from "@koa/router";
-import { FormData, FormDataValue, FormMessage } from "..";
import { FormControl } from "../forms/controls/form-control";
-import { FormField } from "../forms/field";
import { BaseContext } from "koa";
import { FlatTemplatable, Templatable, tempstream } from "tempstream";
+import { FormField } from "../forms/fields/field";
+import { FormData, FormDataValue, FormMessage } from "../forms/form";
export type PageErrorMessage = { type: "access" | "internal"; message: string };
export type Fields = Record<string, FormField<unknown>>;
export abstract class Mountable<F extends Fields = Fields> {
fields: F;
constructor() {
if (!this.fields) this.fields = {} as F;
}
abstract controls: FormControl[];
abstract mount(router: Router, path: string): void;
abstract canAccess(
ctx: BaseContext
): Promise<{ canAccess: boolean; message: string }>;
abstract renderError(
ctx: BaseContext,
error: PageErrorMessage
): Promise<Templatable>;
abstract extractRawValues(ctx: BaseContext): Record<string, FormDataValue>;
// this one is meant to be overwritten
async validateValues(
ctx: BaseContext,
data: Record<string, FormDataValue>
): Promise<{ valid: boolean; error: string }> {
return {
valid: true,
error: "",
};
}
protected async validate(
ctx: BaseContext,
values: Record<string, FormDataValue>
): Promise<{
valid: boolean;
field_errors: Partial<Record<keyof Fields, string>>;
form_messages: FormMessage[];
}> {
const field_errors = {} as Record<keyof Fields, string>;
let valid = true;
const form_messages = [] as FormMessage[];
await Promise.all(
Object.entries(values)
.filter(([fieldname]) => fieldname in this.fields)
.map(async ([key]: [keyof F, FormDataValue]) => {
const field = this.fields[key];
const { valid: fieldvalid, message: fieldmessage } =
await field.getValue(ctx, values);
if (!fieldvalid) {
valid = false;
field_errors[field.name] = fieldmessage;
}
})
);
const formValidationResult = await this.validateValues(ctx, values);
if (!formValidationResult.valid) {
form_messages.push({
type: "error",
text: formValidationResult.error,
});
valid = false;
}
return { valid, field_errors, form_messages };
}
init(): void {
for (const [name, field] of Object.entries(this.fields)) {
field.init(name);
}
}
public renderControls(
ctx: BaseContext,
data: FormData<keyof Fields>
): FlatTemplatable {
return tempstream/* HTML */ `${this.controls.map((control) =>
control.render(ctx, data.raw_values, data.messages)
)}`;
}
public renderMessages(
_: BaseContext,
data: FormData<keyof Fields>
): Templatable {
return tempstream/* HTML */ `<div class="form-messages">
${data.messages.map(
(message) =>
`<div class="form-message form-message--${message.type}">${message.text}</div>`
)}
</div>`;
}
}
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Sat, Nov 28, 03:16 (1 d, 7 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1225892
Default Alt Text
(38 KB)
Attached To
Mode
rSGEN sealgen
Attached
Detach File
Event Timeline