WIP: form attachments (e-mail only) — core, endpoint, Graph large upload
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
0ba0014ed5
commit
6003b3d7d7
@@ -8,14 +8,21 @@ import type { BuilderField, BuilderFormAction, BuilderFormDoc, BuilderFormTexts,
|
||||
|
||||
import { safeHref } from '../links/resolveLinkHref.js'
|
||||
import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js'
|
||||
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
|
||||
import { autoCompleteFor, fileFieldError, fileFieldRules, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
|
||||
import { formAnalyticsOnSuccess } from './formAnalytics.js'
|
||||
import { useForm } from './useForm.js'
|
||||
|
||||
export type UseBuilderFormOptions = {
|
||||
/** Bound server action (RenderForm binds createSubmitAction to formId + locale). */
|
||||
action: BuilderFormAction
|
||||
/**
|
||||
* Where a submission WITH files is posted. Default: the form's own
|
||||
* `fileSubmitUrl` (set by the server), then '/api/ipal/forms/submit'.
|
||||
*/
|
||||
fileSubmitUrl?: string
|
||||
form: BuilderFormDoc
|
||||
/** The page language — sent with a submission that carries files (prepareBuilderForm sets it). */
|
||||
locale?: string
|
||||
/** Router navigation for redirect forms (e.g. router.push). Default: window.location.assign. */
|
||||
navigate?: (href: string) => void
|
||||
/** After a successful submit — on top of the panel's analytics event. */
|
||||
@@ -46,7 +53,7 @@ export type UseBuilderFormOptions = {
|
||||
* <button type="submit">{f.isLast ? form.submitButtonLabel : texts.next}</button>
|
||||
* </form>
|
||||
*/
|
||||
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts, values: pageValues }: UseBuilderFormOptions) {
|
||||
export function useBuilderForm({ action, fileSubmitUrl, form, locale, navigate, onSuccess, redirectHref, texts, values: pageValues }: UseBuilderFormOptions) {
|
||||
const fields = useMemo(() => form.fields ?? [], [form.fields])
|
||||
// Fields behind a failed "Show only when" are neither shown, validated nor sent.
|
||||
const visibleInputs = useCallback((values: Record<string, unknown>) => inputFields(visibleFields(fields, values)), [fields])
|
||||
@@ -56,10 +63,37 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
|
||||
// A field error returned by the server (e.g. "email invalid") — applied after useForm records the failure.
|
||||
const serverFieldError = useRef<{ field: string; message: string } | null>(null)
|
||||
// One key per submit attempt: a repeated request (double click, a resend by the
|
||||
// browser or a proxy) carries the same key and the server sends nothing twice.
|
||||
// A new key only once the server has answered.
|
||||
const attemptKey = useRef('')
|
||||
const submitAction = useCallback(
|
||||
async (values: Record<string, unknown>, token?: string) => {
|
||||
const shown = new Set(visibleInputs(values).map((field) => field.name))
|
||||
const result = await action(Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name))), token)
|
||||
const shownFields = visibleInputs(values)
|
||||
const shown = new Set(shownFields.map((field) => field.name))
|
||||
const fileNames = new Set(shownFields.filter((field) => field.blockType === 'file').map((field) => field.name))
|
||||
const answers = Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name) && !fileNames.has(name)))
|
||||
const files = [...fileNames].flatMap((name) => (Array.isArray(values[name]) ? (values[name] as File[]) : []).map((file) => ({ name, file })))
|
||||
|
||||
let result: Awaited<ReturnType<BuilderFormAction>>
|
||||
if (files.length > 0) {
|
||||
// Files never go through the server action: one multipart request to the
|
||||
// plugin's endpoint — the answers first, the files last — read there as a stream.
|
||||
attemptKey.current ||= (globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`).replace(/[^\w-]/g, '')
|
||||
const body = new FormData()
|
||||
body.append('_form', String(form.id))
|
||||
if (locale) {body.append('_locale', locale)}
|
||||
body.append('_attempt', attemptKey.current)
|
||||
if (token) {body.append('_token', token)}
|
||||
body.append('_values', JSON.stringify(answers))
|
||||
for (const { name, file } of files) {body.append(name, file, file.name)}
|
||||
const url = fileSubmitUrl ?? form.fileSubmitUrl ?? '/api/ipal/forms/submit'
|
||||
const response = await fetch(locale ? `${url}?locale=${encodeURIComponent(locale)}` : url, { body, credentials: 'omit', method: 'POST' })
|
||||
result = (await response.json()) as Awaited<ReturnType<BuilderFormAction>>
|
||||
attemptKey.current = ''
|
||||
} else {
|
||||
result = await action(answers, token)
|
||||
}
|
||||
if (result.success) {setResultMessage(result.message ?? null)}
|
||||
else if (result.field) {
|
||||
// No message from the server → name the field by its label, as the visitor sees it.
|
||||
@@ -68,7 +102,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
}
|
||||
return result
|
||||
},
|
||||
[action, fields, texts.validation, visibleInputs],
|
||||
[action, fields, fileSubmitUrl, form.fileSubmitUrl, form.id, locale, texts.validation, visibleInputs],
|
||||
)
|
||||
|
||||
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts])
|
||||
@@ -242,6 +276,81 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
[f, getFieldProps, textValue],
|
||||
)
|
||||
|
||||
const helpId = useCallback((field: BuilderField) => `${fieldId(field)}-help`, [fieldId])
|
||||
|
||||
// File fields: the selected files live in the form values (File[]); the native
|
||||
// inputs are kept in step with them, so removing a file really removes it.
|
||||
const fileInputs = useRef(new Map<string, HTMLInputElement>())
|
||||
const syncFileInput = useCallback((name: string, files: File[]) => {
|
||||
const input = fileInputs.current.get(name)
|
||||
if (!input) {return}
|
||||
try {
|
||||
const transfer = new DataTransfer()
|
||||
for (const file of files) {transfer.items.add(file)}
|
||||
input.files = transfer.files
|
||||
} catch {
|
||||
if (files.length === 0) {input.value = ''}
|
||||
}
|
||||
}, [])
|
||||
|
||||
/** The files picked for a File field. */
|
||||
const getFiles = useCallback(
|
||||
(field: BuilderField): File[] => {
|
||||
const value = f.values[field.name ?? '']
|
||||
return Array.isArray(value) ? (value as File[]) : []
|
||||
},
|
||||
[f.values],
|
||||
)
|
||||
|
||||
const setFiles = useCallback(
|
||||
(field: BuilderField, files: File[]) => {
|
||||
const name = field.name ?? ''
|
||||
f.setField(name, files)
|
||||
syncFileInput(name, files)
|
||||
// Instant feedback: too large, wrong type, too many — the server checks again, and the content too.
|
||||
const problem = files.length ? fileFieldError(field, files, texts) : undefined
|
||||
if (problem) {setErrors((prev) => ({ ...prev, [name]: problem }))}
|
||||
},
|
||||
[f, setErrors, syncFileInput, texts],
|
||||
)
|
||||
|
||||
/** Props of the `<input type="file">` of a File field. */
|
||||
const getFileProps = useCallback(
|
||||
(field: BuilderField) => {
|
||||
const name = field.name ?? ''
|
||||
const rules = fileFieldRules(field)
|
||||
const base = getFieldProps(field)
|
||||
return {
|
||||
...base,
|
||||
type: 'file' as const,
|
||||
accept: rules.accept || undefined,
|
||||
'aria-describedby': [field.help ? helpId(field) : undefined, base['aria-describedby']].filter(Boolean).join(' ') || undefined,
|
||||
multiple: rules.maxFiles > 1,
|
||||
onChange: (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const picked = Array.from(e.target.files ?? [])
|
||||
// Several files: each pick adds to the list (the same file twice counts once).
|
||||
const current = rules.maxFiles > 1 ? getFiles(field) : []
|
||||
const known = new Set(current.map((file) => `${file.name}:${file.size}`))
|
||||
setFiles(field, [...current, ...picked.filter((file) => !known.has(`${file.name}:${file.size}`))])
|
||||
},
|
||||
ref: (input: HTMLInputElement | null) => {
|
||||
if (input) {fileInputs.current.set(name, input)}
|
||||
else {fileInputs.current.delete(name)}
|
||||
},
|
||||
}
|
||||
},
|
||||
[getFieldProps, getFiles, helpId, setFiles],
|
||||
)
|
||||
|
||||
/** Removes one picked file and puts the focus back on the field. */
|
||||
const removeFile = useCallback(
|
||||
(field: BuilderField, index: number) => {
|
||||
setFiles(field, getFiles(field).filter((_, i) => i !== index))
|
||||
fileInputs.current.get(field.name ?? '')?.focus()
|
||||
},
|
||||
[getFiles, setFiles],
|
||||
)
|
||||
|
||||
/** Props of one option's input in a radio group or checkboxGroup. */
|
||||
const getOptionProps = useCallback(
|
||||
(field: BuilderField, option: BuilderOption, i: number) => {
|
||||
@@ -279,15 +388,19 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
fieldId,
|
||||
form,
|
||||
getFieldProps,
|
||||
getFileProps,
|
||||
getFiles,
|
||||
getInputProps,
|
||||
getOptionProps,
|
||||
getSelectProps,
|
||||
getTextareaProps,
|
||||
goTo,
|
||||
helpId,
|
||||
isFirst,
|
||||
isFixed,
|
||||
isLast,
|
||||
next,
|
||||
removeFile,
|
||||
/** Message the server returned on success (Notifications → success). */
|
||||
resultMessage,
|
||||
step,
|
||||
|
||||
Reference in New Issue
Block a user