Page MenuHomeSealhub

dropdown.ts
No OneTemporary

dropdown.ts

import { Context } from "koa";
import { FlatTemplatable, tempstream } from "tempstream";
import { attribute } from "../../sanitize.js";
import { FormField } from "../fields/field.js";
import { PickFromListField } from "../fields/pick-from-list.js";
import { FormDataValue } from "../form-types.js";
import { FormControlContext } from "./form-control.js";
import { SimpleInput } from "./simple-input.js";
export type DropdownOptions = {
label: string;
autosubmit?: boolean;
autocomplete?: boolean;
};
export type DropdownOption = { value: string; label: string };
export class FreeformDropdown extends SimpleInput<string | null> {
constructor(
public field: FormField<boolean, string | null>,
public _generateOptions: (ctx: Context) => Promise<DropdownOption[]>,
public options: DropdownOptions = {
label: field.name,
autosubmit: false,
autocomplete: true,
}
) {
super(field, options);
}
async generateOptions(ctx: Context): Promise<DropdownOption[]> {
return this._generateOptions(ctx);
}
async getInputAttributes(
fctx: FormControlContext
): Promise<Record<string, string | boolean>> {
const original = await super.getInputAttributes(fctx);
return {
...original,
...Object.fromEntries([
...(this.options.autosubmit
? [
[
"onchange",
((original.onchange as string | undefined) ||
"") + ";this.form.submit();",
],
]
: []),
]),
} as Record<string, string>;
}
async renderInput(
ctx: Context,
attributes_str: string,
data: Record<string, FormDataValue>
): Promise<FlatTemplatable> {
const { parsed: picked_value } = await this.field.getValue(ctx, data);
return /* HTML */ tempstream`<select ${attributes_str}>
${
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
Promise.resolve(this.generateOptions(ctx)).then((options) =>
options.map(
({ value, label }) =>
`<option value="${attribute(value)}" ${
(value || "") == picked_value ? "selected" : ""
}>${label}</option>`
)
)
}
</select>`;
}
}
export class Dropdown extends FreeformDropdown {
constructor(
public field: PickFromListField<boolean>,
public options: DropdownOptions = {
label: field.name,
autosubmit: false,
autocomplete: true,
}
) {
super(field, (ctx) => field.generateOptions(ctx), options);
}
}

File Metadata

Mime Type
text/x-java
Expires
Wed, May 7, 19:51 (17 h, 43 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
624931
Default Alt Text
dropdown.ts (2 KB)

Event Timeline