import { escapeHtml, html } from '/public/ts/utils/misc.ts'; export interface FormField { name: string; label: string; value?: string | string[] | null; overrideValue?: string; description?: string; placeholder?: string; type: | 'text' | 'email' | 'tel' | 'url' | 'date' | 'datetime-local' | 'number' | 'range' | 'select' | 'textarea' | 'checkbox' | 'hidden' | 'password' | 'file'; step?: string; max?: string; min?: string; rows?: string; options?: { label: string; value: string; }[]; checked?: boolean; multiple?: boolean; required?: boolean; disabled?: boolean; readOnly?: boolean; extraAttributes?: string; extraInputAttributes?: string; extraClasses?: string; signupFormStep?: number; } export function getFormDataField(formData: FormData, field: string) { return ((formData.get(field) || '') as string).trim(); } export function getFormDataFieldArray(formData: FormData, field: string) { return ((formData.getAll(field) || []) as string[]).map((value) => value.trim()); } export function generateFieldHtml(field: FormField, formData: FormData) { let value = typeof field.overrideValue !== 'undefined' ? field.overrideValue : (field.multiple ? getFormDataFieldArray(formData, field.name) : getFormDataField(formData, field.name)) || field.value; if (typeof field.overrideValue === 'undefined' && field.multiple && Array.isArray(value) && value.length === 0) { value = field.value; } if (field.type === 'hidden') { return html` ${generateInputHtml(field, value)} `; } return html`
${generateInputHtml(field, value)} ${field.description ? html` ` : ''}
`; } function generateInputHtml( { name, placeholder, type, options, step, max, min, rows = '6', checked, multiple, disabled, required, readOnly, extraInputAttributes, }: FormField, value?: string | string[] | null, ) { const stepAttribute = step && `step="${step}"`; const maxAttribute = max && `max="${max}"`; const minAttribute = min && `min="${min}"`; const checkedAttribute = checked && type === 'checkbox' && value && 'checked'; const multipleAttribute = multiple && 'multiple'; const requiredAttritbute = required && 'required'; const disabledAttribute = disabled && 'disabled'; const readOnlyAttritubte = readOnly && 'readonly'; const additionalAttributes = [ stepAttribute, maxAttribute, minAttribute, checkedAttribute, multipleAttribute, requiredAttritbute, disabledAttribute, readOnlyAttritubte, ].filter(Boolean).join(' '); if (type === 'select') { return html` `; } if (type === 'hidden') { return html` `; } if (type === 'textarea') { return html` `; } if (type === 'checkbox') { return html` `; } if (type === 'password') { return html` `; } if (type === 'file') { return html` `; } return html` `; }