import { Context } from "koa"; import { FlatTemplatable, tempstream } from "tempstream"; import { File } from "./file.js"; import { FormField } from "../fields/field.js"; import { SimpleInputOptions } from "./simple-input.js"; import { FormControlContext } from "./form-control.js"; import { FileContainer } from "../fields/file.js"; import { FilePointer } from "@sealcode/file-manager"; export class Image extends File { constructor( public field: FormField, options?: SimpleInputOptions ) { super(field, options); } async getImgStyle() { return "width: 100px; height: 100px; object-fit: contain"; } async renderFilePreview( ctx: Context, file: FilePointer | null ): Promise { const class_name = "file_preview"; const empty_container = `
`; if (!file) { return empty_container; } return tempstream /* HTML */ `
${ctx.$app.imageRouter.image(await file.getPath(), { resolutions: [100, 200], sizesAttr: "100px", crop: { width: 100, height: 100 }, container: { width: 100, height: 100 }, imgStyle: await this.getImgStyle(), alt: "Image preview", })}
`; } getWrapperModifiers(): string[] { return [ ...super.getWrapperModifiers(), "control-type__image", "control-type__photo", ]; } async getInputAttributes(fctx: FormControlContext) { const original = await super.getInputAttributes(fctx); const onchange = ((original.onchange as string) || "") + ";" + ` const file = this.files[0]; const preview_container = this.parentElement.querySelector(".file_preview"); const target = this; if (file) { const fileReader = new FileReader(); fileReader.readAsDataURL(file); fileReader.addEventListener("load", function () { preview_container.innerHTML = \`\`; }); }` .replaceAll("\n", " ") .replaceAll(`"`, "'"); return { ...original, accept: "image/*", onchange, }; } }