/* eslint @typescript-eslint/no-unsafe-assignment: off, @typescript-eslint/no-unsafe-argument: off, @typescript-eslint/no-unsafe-member-access: off, @typescript-eslint/no-unsafe-call: off */ import { Context } from "koa"; import { FilePointer, PathFilePointer } from "@sealcode/file-manager"; import { FlatTemplatable, tempstream } from "tempstream"; import { FormDataValue } from "../form-types.js"; import { FormControlContext } from "./form-control.js"; import { SimpleInput } from "./simple-input.js"; import { htmlEscape } from "escape-goat"; import { extname } from "node:path"; export class File extends SimpleInput { getType() { return "file"; } async renderFilePreview( _ctx: Context, file: FilePointer | null ): Promise { const class_name = "file_preview"; const empty_container = `
`; if (!file) { return empty_container; } if (file instanceof PathFilePointer) { const filename = await file.getOriginalFilename(); return tempstream /* HTML */ `
${extname(filename)} ${filename}
`; } return tempstream /* HTML */ `
${file.getOriginalFilename()}
`; } async preInput( fctx: FormControlContext, data: Record ) { let { parsed } = await this.field.getParsedValue(fctx.ctx, data); if (parsed === null) { parsed = { old: null, new: null }; } return tempstream /* HTML */ `${this.renderFilePreview( fctx.ctx, parsed.old )} `; } async getInputAttributes( fctx: FormControlContext ): Promise> { const original = await super.getInputAttributes(fctx); const { parsed } = await this.field.getParsedValue( fctx.ctx, fctx.data.raw_values ); return { ...original, name: this.field.name + "[new]", required: original.required && !parsed?.old, value: false, }; } }