import type { BuilderField, BuilderFileLimits, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js' import { describeFileTypes, fileExtensions, MB } from './attachments/fileTypes.js' import { NON_INPUT_TYPES } from './builderTypes.js' import { isEmail } from './validators.js' /** * Pure logic of a panel form — steps, initial values, validation. No React, so * it's shared by useBuilderForm and tested on its own. The server re-checks * everything (validateSubmission); this is only for instant feedback. */ /** Fields that hold a value (have a name and aren't message/step). */ export function inputFields(fields: BuilderField[] | null | undefined): ({ name: string } & BuilderField)[] { return (fields ?? []).filter( (f): f is { name: string } & BuilderField => typeof f.name === 'string' && f.name !== '' && !NON_INPUT_TYPES.has(f.blockType), ) } /** * Splits the field list at `step` blocks. Fields before the first Step form * the first screen; a form without Steps is one screen. * * `isShown` (e.g. membership in visibleFields) leaves hidden fields — and a * hidden Step with everything under it — out, while `index` stays the field's * position in the full list (RenderForm renders `message` blocks by it). */ export function splitSteps(fields: BuilderField[] | null | undefined, isShown?: (field: BuilderField) => boolean): BuilderStep[] { const steps: BuilderStep[] = [] let current: BuilderStep | null = null let skipping = false ;(fields ?? []).forEach((field, index) => { if (field.blockType === 'step') { skipping = isShown ? !isShown(field) : false if (skipping) {return} current = { description: field.description ?? undefined, fields: [], index: steps.length, title: field.title ?? undefined } steps.push(current) return } if (skipping || (isShown && !isShown(field))) {return} if (!current) { current = { fields: [], index: 0 } steps.push(current) } current.fields.push({ field, index }) }) // Drop screens a trailing / doubled Step left empty. const kept = steps.filter((s) => s.fields.length > 0) return (kept.length ? kept : [{ fields: [], index: 0 }]).map((s, i) => ({ ...s, index: i })) } const isBlankValue = (v: unknown) => v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0) /** The minimum a field needs for conditional visibility — panel docs on the server, BuilderField on the client. */ type ConditionalField = { blockType?: null | string; name?: null | string; showWhen?: FieldCondition | null } const conditionValues = (condition: FieldCondition | null | undefined) => (condition?.values ?? '').split(',').map((v) => v.trim()).filter(Boolean) /** * The fields (Steps and messages included) a visitor sees for the given values, * in panel order. A field is hidden when its own "Show only when" fails, when * its Step's condition fails (the whole step goes), or when the field its * condition points at is itself hidden. A condition naming a field that doesn't * exist hides the field — a typo shows up in the preview instead of passing silently. * * Shared by the browser (useBuilderForm: which steps and fields to show and * validate) and the server (validateSubmission: hidden fields are neither * required nor stored), so both agree on what was on screen. */ export function visibleFields(fields: F[] | null | undefined, values: Record): F[] { const list = fields ?? [] const byName = new Map(list.filter((f) => f.name && f.blockType !== 'step').map((f) => [f.name as string, f])) const stepOf = new Map() let currentStep: F | undefined for (const field of list) { if (field.blockType === 'step') {currentStep = field} stepOf.set(field, field.blockType === 'step' ? undefined : currentStep) } const cache = new Map() const met = (condition: FieldCondition | null | undefined, seen: Set): boolean => { const ref = condition?.field?.trim() if (!ref) {return true} const target = byName.get(ref) if (!target || seen.has(target) || !visible(target, seen)) {return false} const value = values[ref] const wanted = conditionValues(condition) if (wanted.length === 0) {return !isBlankValue(value)} if (Array.isArray(value)) {return value.some((v) => wanted.includes(String(v)))} return value != null && value !== '' && wanted.includes(String(value as boolean | number | string)) } const visible = (field: F, seen: Set = new Set()): boolean => { const cached = cache.get(field) if (cached !== undefined) {return cached} const nextSeen = new Set(seen).add(field) const step = stepOf.get(field) const result = (!step || met(step.showWhen, nextSeen)) && met(field.showWhen, nextSeen) cache.set(field, result) return result } return list.filter((field) => visible(field)) } /** A selected file as the logic needs it — a browser `File` fits. */ export type BuilderFile = { name: string; size: number } /** * The limits of a File field in the browser: what the server resolved * (`field.resolved`), else the field's own values with the built-in types. */ export function fileFieldRules(field: BuilderField): Required { const own = describeFileTypes(field.allowedTypes) const r = field.resolved ?? {} const maxSizeMB = r.maxSizeMB ?? field.maxSizeMB ?? 10 return { accept: r.accept ?? own.accept, extensions: r.extensions ?? own.extensions, maxFiles: r.maxFiles ?? field.maxFiles ?? 1, maxSizeMB, maxTotalMB: r.maxTotalMB ?? maxSizeMB, typeLabels: r.typeLabels ?? own.labels, } } /** * The first problem with the files picked for a File field, as the visitor's * message — the same rules the server enforces (it checks the content too). */ export function fileFieldError( field: BuilderField, files: readonly BuilderFile[], texts: Pick, ): string | undefined { const rules = fileFieldRules(field) const label = field.label || field.name || '' const generic = texts.validation.replace('{field}', label) // On a field that is not required the visitor may also send the form without the file — say so. const say = (text: string | undefined, fill: (text: string) => string) => text ? `${fill(text)}${!field.required && texts.fileOptional ? ` ${texts.fileOptional}` : ''}` : generic if (files.length > rules.maxFiles) {return say(texts.fileCount, (t) => t.replace('{field}', label).replace('{max}', String(rules.maxFiles)))} for (const file of files) { if (rules.extensions.length > 0 && !rules.extensions.includes(fileExtensions(file.name).at(-1) ?? '')) { return say(texts.fileType, (t) => t.replace('{file}', file.name).replace('{types}', rules.typeLabels)) } if (file.size > rules.maxSizeMB * MB || file.size === 0) { return say(texts.fileTooLarge, (t) => t.replace('{file}', file.name).replace('{max}', String(rules.maxSizeMB))) } } if (files.reduce((sum, f) => sum + f.size, 0) > rules.maxTotalMB * MB) { return say(texts.fileTooLarge, (t) => t.replace('{file}', files.at(-1)?.name ?? '').replace('{max}', String(rules.maxTotalMB))) } return undefined } /** Starting values: checkbox → boolean, checkboxGroup → string[], file → File[], the rest → string. */ export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record { return Object.fromEntries( inputFields(fields).map((f) => { if (f.blockType === 'checkbox') {return [f.name, f.defaultValue === true]} if (f.blockType === 'checkboxGroup') {return [f.name, Array.isArray(f.defaultValue) ? f.defaultValue : []]} if (f.blockType === 'file') {return [f.name, []]} const v = f.defaultValue return [f.name, typeof v === 'string' || typeof v === 'number' ? String(v) : ''] }), ) } const isBlank = isBlankValue /** Errors for the given fields (one message per field), empty object = valid. */ export function validateBuilderFields( fields: BuilderField[], values: Record, texts: Pick, ): Record { const errors: Record = {} for (const f of inputFields(fields)) { const v = values[f.name] const msg = texts.validation.replace('{field}', f.label || f.name) if (isBlank(v)) { if (f.required) {errors[f.name] = msg} continue } if (f.blockType === 'file') { const problem = Array.isArray(v) ? fileFieldError(f, v as BuilderFile[], texts) : msg if (problem) {errors[f.name] = problem} } else if (f.blockType === 'email' && !isEmail(v)) {errors[f.name] = msg} else if (f.blockType === 'number' && !Number.isFinite(Number(v))) {errors[f.name] = msg} else if (f.blockType === 'checkboxGroup' && Array.isArray(v)) { if ((f.minSelected && v.length < f.minSelected) || (f.maxSelected && v.length > f.maxSelected)) {errors[f.name] = msg} } } return errors } /** Index of the step holding a field — to jump back to it after a failed submit. */ export function stepOfField(steps: BuilderStep[], name: string): number { const i = steps.findIndex((s) => s.fields.some(({ field }) => field.name === name)) return i < 0 ? 0 : i } /** Browser autofill hint from the field type / a conventional name. */ export function autoCompleteFor(field: BuilderField): string | undefined { if (field.blockType === 'email') {return 'email'} if (field.blockType === 'country') {return 'country-name'} const n = (field.name ?? '').toLowerCase() if (/^(?:full_?)?name$|^imie/.test(n)) {return 'name'} if (/phone|tel/.test(n)) {return 'tel'} if (/company|organi[sz]ation|firma/.test(n)) {return 'organization'} return undefined }