Beautiful Open-Source Form Builder
Fix conditional field flashes during SSR and draft hydration (#1312)
Julien Nahumc11b04554acb
diff --git a/client/components/forms/core/ScaleInput.vue b/client/components/forms/core/ScaleInput.vueindex 36980091f..17009d60b 100644--- a/client/components/forms/core/ScaleInput.vue+++ b/client/components/forms/core/ScaleInput.vue@@ -101,8 +101,8 @@ export default {},mounted() {- if (this.compVal && typeof this.compVal === "string") {- this.compVal = parseInt(this.compVal)+ if (typeof this.compVal === "string" && this.compVal.trim() !== "" && Number.isFinite(Number(this.compVal))) {+ this.compVal = Number(this.compVal)}},diff --git a/client/components/open/forms/BlockRenderer.vue b/client/components/open/forms/BlockRenderer.vueindex 8d0e98905..49cdb5b4c 100644--- a/client/components/open/forms/BlockRenderer.vue+++ b/client/components/open/forms/BlockRenderer.vue@@ -1,6 +1,6 @@<template><ClientOnlyWrapper v-if="block && hasComponent" :client-only="clientOnlyVal" :key="'dyn-' + (block?.id || 'dyn')">- <Suspense>+ <Suspense suspensible><component:is="componentVal"v-bind="boundProps"diff --git a/client/components/open/forms/OpenCompleteForm.vue b/client/components/open/forms/OpenCompleteForm.vueindex 29622b367..d72f970e0 100644--- a/client/components/open/forms/OpenCompleteForm.vue+++ b/client/components/open/forms/OpenCompleteForm.vue@@ -2,6 +2,8 @@<divv-if="form"class="open-complete-form flex flex-col min-h-full"+ :inert="isRestoringDraft || undefined"+ :aria-busy="isRestoringDraft || undefined":dir="form?.layout_rtl ? 'rtl' : 'ltr'":style="formStyle">@@ -182,13 +184,22 @@ const passwordForm = useForm({ password: null })// Removed unused hidePasswordDisabledMsg (was always false and unused)// submission_id is a public UUID identifierconst submissionId = ref(route.query.submission_id || null)+// Match SSR markup while keeping browser-only draft restoration non-interactive.+const isRestoringDraft = ref(!!props.form.auto_save && !submissionId.value)const submittedData = ref(null)const showFirstSubmissionModal = ref(false)-const queryString = route.fullPath.split('?')[1] || ''+const getUrlParams = () => {+ const params = new URLSearchParams()+ Object.entries(route.query).forEach(([key, value]) => {+ const values = Array.isArray(value) ? value : [value]+ values.forEach(value => params.append(key, value ?? ''))+ })+ return params+}// Check for auto_submit parameter during setup-const isAutoSubmit = ref(import.meta.client && window.location.href.includes('auto_submit=true'))+const isAutoSubmit = ref(getUrlParams().get('auto_submit') === 'true')// Create a reactive reference directly from the prop@@ -203,6 +214,8 @@ provide('formBorderRadius', computed(() => props.form.border_radius || 'small'))provide('formPresentationStyle', computed(() => props.form.presentation_style || 'classic'))let formManager = null+let restoreDraftAfterHydration = false+let draftRestoration = Promise.resolve()const sdkBridge = shallowRef(null)let resolveSdkBridgeReadyconst sdkBridgeReady = new Promise((resolve) => {@@ -214,12 +227,34 @@ if (props.form) {mode: modeRef})+ // Hydrate the server's answers first. Browser-only drafts must update mounted+ // controls, rather than hydrating a different value into the server's markup.+ restoreDraftAfterHydration = import.meta.client && nuxtApp.isHydrating &&+ !submissionId.value && formManager.pendingSubmission.enabled.value+ if (restoreDraftAfterHydration) {+ formManager.pendingSubmission.pauseAutosave()+ draftRestoration = new Promise((resolve) => {+ const removeHook = nuxtApp.hooks.hookOnce('app:suspense:resolve', () => {+ formManager.restorePendingSubmission()+ formManager.startBackgroundSync()+ restoreDraftAfterHydration = false+ isRestoringDraft.value = false+ resolve()+ })+ onBeforeUnmount(removeHook)+ })+ }+// Await initialization so SSR includes form structure and fieldsawait formManager.initialize({submissionId: submissionId.value,- urlParams: new URLSearchParams(queryString),+ urlParams: getUrlParams(),+ skipPendingSubmission: restoreDraftAfterHydration,+ deferBackgroundSync: restoreDraftAfterHydration,})+ if (import.meta.client && !restoreDraftAfterHydration) isRestoringDraft.value = false+}// Watch for changes to the form prop and update formManager@@ -229,7 +264,7 @@ watch(() => props.form, (newForm) => {// Update form manager with the new configformManager.updateConfig(newForm, {submissionId: submissionId.value,- urlParams: new URLSearchParams(queryString),+ urlParams: getUrlParams(),})}})@@ -259,6 +294,7 @@ onMounted(() => {if (isAutoSubmit.value && formManager) {// Using nextTick to ensure form is fully rendered and initializednextTick(async () => {+ await draftRestorationconst bridge = shouldLoadSdkBridge.value ? await sdkBridgeReady : nullawait bridge?.waitForHandshake?.()triggerSubmit()@@ -384,6 +420,7 @@ const handleScrollToError = () => {}const triggerSubmit = () => {+ if (restoreDraftAfterHydration) return draftRestoration.then(triggerSubmit)if (!formManager || isProcessing.value) return// Emit SDK submitStart event@@ -443,8 +480,7 @@ const restart = async () => {if (!formManager) returnsubmittedData.value = nullsubmissionId.value = null- const queryString = route.fullPath.split('?')[1] || ''- const urlParams = new URLSearchParams(queryString)+ const urlParams = getUrlParams()// Determine if we should clear the form completely for a fresh startconst shouldClearUrl = props.form.editable_submissionsdiff --git a/client/composables/forms/useComputedVariables.js b/client/composables/forms/useComputedVariables.jsindex affa3e3ae..16612b4a4 100644--- a/client/composables/forms/useComputedVariables.js+++ b/client/composables/forms/useComputedVariables.js@@ -1,12 +1,13 @@import { evaluateFormula, buildDependencyGraph } from '~/lib/formulas/index.js'+import { computed } from 'vue'/*** Composable for managing computed variables during form fill* Provides reactive evaluation of computed variables based on form data*/export function useComputedVariables(form, formData) {- // Store for evaluated variable values- const values = ref({})+ // Derive values directly from answers, including during SSR where watchers do not rerun.+ const values = computed(() => evaluateAll())// Get computed variables from formconst computedVariables = computed(() => form.value?.computed_variables || [])@@ -66,27 +67,9 @@ export function useComputedVariables(form, formData) {}}- values.value = newValues+ return newValues}- // Watch for changes in form data and re-evaluate- watch(- () => formData.value,- () => {- evaluateAll()- },- { deep: true, immediate: true }- )-- // Also re-evaluate when computed variables change- watch(- computedVariables,- () => {- evaluateAll()- },- { deep: true }- )-// Get a specific variable valueconst getValue = (variableId) => {return values.value[variableId]diff --git a/client/composables/forms/usePartialSubmission.js b/client/composables/forms/usePartialSubmission.jsindex de352d1c6..ed85d9c7c 100644--- a/client/composables/forms/usePartialSubmission.js+++ b/client/composables/forms/usePartialSubmission.js@@ -147,7 +147,7 @@ export function usePartialSubmission(formConfig, formDataRef, pendingSubmissionS* @param {boolean} options.skipFinalSync - If true, skip the final sync (use when about to do a complete submission)*/const stopSync = (options = {}) => {- if (import.meta.server) return+ if (import.meta.server || !dataWatcher) returnconst { skipFinalSync = false } = optionsdiff --git a/client/lib/forms/composables/useFormInitialization.js b/client/lib/forms/composables/useFormInitialization.jsindex c4d198f2e..0d684a69e 100644--- a/client/lib/forms/composables/useFormInitialization.js+++ b/client/lib/forms/composables/useFormInitialization.js@@ -46,8 +46,7 @@ export function useFormInitialization(formConfig, form, pendingSubmission) {}// 3. Try loading from pendingSubmission- if (!(options.skipPendingSubmission ?? false) && tryLoadFromPendingSubmission()) {- updateSpecialFields()+ if (!(options.skipPendingSubmission ?? false) && restorePendingSubmission()) {return // Exit if loaded successfully}@@ -65,16 +64,12 @@ export function useFormInitialization(formConfig, form, pendingSubmission) {applyDefaultValues(defaultValuesToApply, config?.properties)}- // 7. Process any select fields to ensure IDs are converted to names- // This is crucial when receiving data that might contain IDs instead of names- const currentData = form.data()- if (Object.keys(currentData).length > 0) {- resetAndFill(currentData)- }+ // 7. Normalize field values before resolving visibility or rendering inputs.+ resetAndFill(form.data())}/**- * Wrapper for form.resetAndFill that converts select option IDs to names+ * Normalize input values before rendering and convert select option IDs to names.* @param {Object} formData - Form data to clean and fill*/const resetAndFill = (formData) => {@@ -85,6 +80,7 @@ export function useFormInitialization(formConfig, form, pendingSubmission) {// Clone the data to avoid mutating the originalconst cleanData = clonedeep(formData)+ const implicitDefaults = {}// Process select fields to convert IDs to namesif (!formConfig.value || !formConfig.value.properties || !Array.isArray(formConfig.value.properties)) {@@ -98,11 +94,36 @@ export function useFormInitialization(formConfig, form, pendingSubmission) {// Basic validationif (!field || typeof field !== 'object') returnif (!field.id || !field.type) return++ // Match unchecked inputs before SSR/visibility evaluation, including hidden checkboxes.+ // Focused Yes/No selectors must remain unanswered until a selection is made.+ const isFocusedToggle = formConfig.value.presentation_style === 'focused' && field.use_focused_toggle !== false+ if (field.type === 'checkbox' && (cleanData[field.id] == null || cleanData[field.id] === '') && !isFocusedToggle) {+ implicitDefaults[field.id] = false+ delete cleanData[field.id]+ return+ }++ // Rating and slider inputs previously supplied these defaults only on mount.+ // Include hidden controls so their conditions never depend on render order.+ const value = cleanData[field.id]+ if ((field.type === 'rating' && (value == null || value === '')) ||+ (field.type === 'slider' && (value == null || value === '' || !Number.isFinite(Number(value))))) {+ implicitDefaults[field.id] = 0+ delete cleanData[field.id]+ return+ }+// Skip only when value is truly undefined or nullif (cleanData[field.id] === undefined || cleanData[field.id] === null) return+ // Preserve fractional scale values; parseInt on mount used to truncate them.+ if (['rating', 'slider', 'scale'].includes(field.type) &&+ typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) {+ cleanData[field.id] = Number(value)+ }// Process checkbox fields - convert string and numeric values to boolean- if (field.type === 'checkbox') {+ else if (field.type === 'checkbox') {const value = cleanData[field.id]if (typeof value === 'string' && value.toLowerCase() === 'true' || value === '1' || value === 1) {cleanData[field.id] = true@@ -136,6 +157,12 @@ export function useFormInitialization(formConfig, form, pendingSubmission) {// Fill with cleaned dataform.resetAndFill(cleanData)++ // Match mounted inputs without retaining an unanswered default as an explicit answer.+ // This lets a new configured prefill apply when the form is reinitialized.+ Object.entries(implicitDefaults).forEach(([fieldId, value]) => {+ form[fieldId] = value+ })}/**@@ -278,7 +305,15 @@ export function useFormInitialization(formConfig, form, pendingSubmission) {return false}- resetAndFill(pendingData)+ // Apply configured prefill to omitted draft fields before initializing checkbox defaults.+ form.resetAndFill(pendingData)+ return true+ }++ const restorePendingSubmission = () => {+ if (!tryLoadFromPendingSubmission()) return false+ updateSpecialFields()+ resetAndFill(form.data())return true}@@ -286,6 +321,7 @@ export function useFormInitialization(formConfig, form, pendingSubmission) {initialize,applyUrlParameters,applyDefaultValues,+ restorePendingSubmission,resetAndFill // Export our wrapped function for use elsewhere}}diff --git a/client/lib/forms/composables/useFormManager.js b/client/lib/forms/composables/useFormManager.jsindex 212d84bb8..d05722b01 100644--- a/client/lib/forms/composables/useFormManager.js+++ b/client/lib/forms/composables/useFormManager.js@@ -99,6 +99,19 @@ export function useFormManager(initialFormConfig, initialMode = FormMode.LIVE, o} catch { /* no-op */ }}+ function restorePendingSubmission() {+ if (!initialization.restorePendingSubmission()) return false+ replaceStructure()+ return true+ }++ function startBackgroundSync() {+ pendingSubmissionService.resumeAutosave()+ if (import.meta.client && config.value.enable_partial_submissions && strategy.value.submission.enablePartialSubmissions) {+ partialSubmissionService.startSync()+ }+ }+const validation = useFormValidation(config, form, state)const payment = useFormPayment(config, form)const submission = useFormSubmission(config, form, submissionAttribution.attribution)@@ -154,10 +167,8 @@ export function useFormManager(initialFormConfig, initialMode = FormMode.LIVE, o// Ensure structure is built after initializationreplaceStructure()- // Start partial submission sync if enabled in both config and strategy- if (import.meta.client && config.value.enable_partial_submissions && strategy.value.submission.enablePartialSubmissions) {- partialSubmissionService.startSync()- }+ // Resume draft saving and partial sync only once the answers are ready.+ if (!options.deferBackgroundSync) startBackgroundSync()state.isProcessing = false}@@ -315,6 +326,7 @@ export function useFormManager(initialFormConfig, initialMode = FormMode.LIVE, o}// 7. Clear pending submission data on successful submit+ pendingSubmissionService?.pauseAutosave()pendingSubmissionService?.clear()// 8. Clear partial submission hash to prevent stale data@@ -438,6 +450,8 @@ export function useFormManager(initialFormConfig, initialMode = FormMode.LIVE, o// Core Methodsinitialize,+ restorePendingSubmission,+ startBackgroundSync,updateConfig, // New method to update form confignextPage,previousPage,diff --git a/client/lib/forms/composables/usePendingSubmission.js b/client/lib/forms/composables/usePendingSubmission.jsindex b1980cbd4..7958fd9dc 100644--- a/client/lib/forms/composables/usePendingSubmission.js+++ b/client/lib/forms/composables/usePendingSubmission.js@@ -83,12 +83,14 @@ export function usePendingSubmission(formConfig, formDataRef) {}// Watch formDataRef with throttling- watchThrottled(+ let autosavePaused = false+ const autosave = watchThrottled(formDataRef,- (newData) => {+ () => {// Only persist full draft when auto-save is on (not only partial-submission metadata)- if (import.meta.client && enabled.value) {- saveData(mergeStoredMetadata(newData))+ // A trailing throttle callback can still run after the watcher is paused.+ if (import.meta.client && enabled.value && !autosavePaused) {+ saveData(mergeStoredMetadata(formDataRef.value))}},{ deep: true, throttle: 1000 } // Throttle saving to once per second@@ -96,6 +98,16 @@ export function usePendingSubmission(formConfig, formDataRef) {// --- Exposed Methods ---+ const pauseAutosave = () => {+ autosavePaused = true+ autosave.pause()+ }++ const resumeAutosave = () => {+ autosavePaused = false+ autosave.resume()+ }+const remove = () => {// Clear the data from storagesaveData(null)@@ -141,6 +153,8 @@ export function usePendingSubmission(formConfig, formDataRef) {return {formPendingSubmissionKey, // Keep for potential external use (e.g., partial submission hash map key)enabled,+ pauseAutosave,+ resumeAutosave,get, // Method to retrieve stored dataremove, // Method to clear stored datasetSubmissionHash, // Method to specifically set the submission hashdiff --git a/client/test/e2e/form-initialization-ssr.spec.ts b/client/test/e2e/form-initialization-ssr.spec.tsnew file mode 100644index 000000000..c030ef824--- /dev/null+++ b/client/test/e2e/form-initialization-ssr.spec.ts@@ -0,0 +1,385 @@+import { test, expect, type APIRequestContext, type Page } from '@playwright/test'+import { readFileSync } from 'node:fs'+import { hash } from '../../lib/utils.js'++const api = process.env.PLAYWRIGHT_API_BASE_URL || 'http://127.0.0.1:8089'+let headers: Record<string, string>+let workspaceId: number++test.beforeAll(async ({ request }) => {+ const login = await request.post(`${api}/login`, { data: {+ email: '[email protected]', password: 'Abcd@1234', remember: false,+ } })+ expect(login.ok()).toBeTruthy()+ const { token } = await login.json()+ headers = { Accept: 'application/json', Authorization: `Bearer ${token}` }+ const response = await request.get(`${api}/open/workspaces`, { headers })+ expect(response.ok()).toBeTruthy()+ workspaceId = (await response.json())[0].id+})++async function createForm(request: APIRequestContext, properties: unknown[], overrides = {}) {+ const response = await request.post(`${api}/open/forms`, { headers, data: {+ title: `SSR visibility ${Date.now()} ${Math.random().toString(36).slice(2, 6)}`,+ workspace_id: workspaceId, visibility: 'public', properties,+ language: 'en', theme: 'default', presentation_style: 'classic', width: 'centered',+ size: 'md', border_radius: 'small', no_branding: false,+ dark_mode: 'light', color: '#3B82F6', uppercase_labels: false, transparent_background: false,+ auto_save: false, auto_focus: false, use_captcha: false,+ settings: { auto_next: false },+ ...overrides,+ } })+ expect(response.ok(), await response.text()).toBeTruthy()+ return (await response.json()).form+}++function collectHydrationWarnings(page: Page) {+ const warnings: string[] = []+ page.on('console', message => {+ if (/hydration.*mismatch/i.test(message.text())) warnings.push(message.text())+ })+ return warnings+}++async function nextFocusedStep(page: Page) {+ const next = page.getByRole('button', { name: /next/i })+ // The outgoing step remains in the DOM for the slide transition.+ await expect(next).toHaveCount(1)+ await next.click()+}++async function holdRatingInput(page: Page) {+ const component = 'components/forms/heavy/RatingInput.vue'+ let pattern = `**/${component}*`+ if (process.env.PLAYWRIGHT_DEV_SERVER !== '1') {+ const manifest = readFileSync(new URL('../../.output/server/chunks/build/client.manifest.mjs', import.meta.url), 'utf8')+ const file = manifest.match(/"components\/forms\/heavy\/RatingInput.vue":\s*\{[\s\S]*?"file":\s*"([^"]+)"/)?.[1]+ expect(file, 'RatingInput must have an async client bundle').toBeTruthy()+ pattern = `**/_nuxt/${file}`+ }+ let held = false+ let release: () => void+ const blocked = new Promise<void>(resolve => { release = resolve })+ await page.route(pattern, route => {+ held = true+ return blocked.then(() => route.continue())+ })+ return { isHeld: () => held, release: () => release() }+}++const numericCases = [+ { name: 'empty rating', type: 'rating', field: { rating_max_value: 5 }, value: 0 },+ { name: 'empty slider', type: 'slider', field: { slider_min_value: 0, slider_max_value: 50, slider_step_value: 5 }, value: 0 },+ { name: 'prefilled scale', type: 'scale', field: { prefill: '3', scale_min_value: 1, scale_max_value: 5, scale_step_value: 1 }, value: 3 },+ { name: 'decimal scale', type: 'scale', field: { prefill: '2.5', scale_min_value: 1, scale_max_value: 5, scale_step_value: 0.5 }, value: 2.5 },+ { name: 'URL scale', type: 'scale', field: { scale_min_value: 1, scale_max_value: 5, scale_step_value: 0.5 }, value: 2.5, query: '?control=2.5' },+ { name: 'computed prefill', type: 'number', field: { prefill: 5 }, value: 10, computed: true },+ { name: 'computed URL', type: 'number', field: {}, value: 10, query: '?control=5', computed: true },+]++for (const style of ['classic', 'focused']) {+ for (const item of numericCases) {+ test(`${style} SSR visibility stays stable for ${item.name}`, async ({ page, request, browser }) => {+ const warnings = collectHydrationWarnings(page)+ const form = await createForm(request, [+ // Put the dependent first so Focused also exposes an incorrect first question.+ { id: 'dependent', name: 'Dependent', type: 'text', hidden: false, required: true,+ logic: { conditions: { identifier: item.computed ? 'cv_total' : 'control', value: {+ operator: item.computed ? 'greater_than' : 'equals', property_meta: item.computed+ ? { id: 'cv_total', type: 'computed', result_type: 'number' }+ : { id: 'control', type: item.type }, value: item.value,+ } }, actions: ['hide-block'] } },+ { id: 'control', name: 'Control', type: item.type, hidden: false, required: false, ...item.field },+ { id: 'feedback', name: 'Feedback', type: 'text', hidden: false, prefill: 'Kept answer' },+ { id: 'static_hidden', name: 'Static hidden', type: 'text', hidden: true },+ ], { presentation_style: style, computed_variables: item.computed ? [+ { id: 'cv_total', name: 'Total', formula: '{cv_double} + 1', result_type: 'number' },+ { id: 'cv_double', name: 'Double', formula: '{control} * 2', result_type: 'number' },+ ] : [] })+ const path = `/forms/${form.slug}${item.query || ''}`+ const response = await request.get(path)+ expect(response.ok()).toBeTruthy()+ const html = await response.text()+ expect(html).not.toContain('data-testid="open-form-field-dependent"')+ expect(html).not.toContain('data-testid="open-form-field-static_hidden"')+ expect(html).not.toMatch(/<label[^>]*for="dependent"/)++ const context = await browser.newContext({ javaScriptEnabled: false })+ try {+ const firstRender = await context.newPage()+ await firstRender.goto(new URL(path, response.url()).href)+ await expect(firstRender.locator('label[for="control"]')).toBeVisible()+ await expect(firstRender.locator('label[for="dependent"]')).toHaveCount(0)+ if (item.type === 'scale') {+ await expect(firstRender.getByRole('radio', { name: `Scale value ${item.value}`, exact: true }))+ .toHaveAttribute('aria-checked', 'true')+ }+ } finally {+ await context.close()+ }++ await page.goto(path)+ await page.waitForLoadState('networkidle')+ await expect(page.locator('label[for="control"]')).toBeVisible()+ await expect(page.locator('label[for="dependent"]')).toHaveCount(0)+ await expect(page.locator('label[for="static_hidden"]')).toHaveCount(0)+ if (item.type === 'scale') {+ await expect(page.getByRole('radio', { name: `Scale value ${item.value}`, exact: true }))+ .toHaveAttribute('aria-checked', 'true')+ }+ expect(warnings).toEqual([])++ if (item.computed) {+ await page.getByLabel('Control', { exact: true }).fill('1')+ await expect(page.getByLabel('Dependent', { exact: true })).toBeVisible()+ await page.getByLabel('Dependent', { exact: true }).fill('Recomputed answer')+ }+ if (style === 'classic') {+ const submission = page.waitForRequest(request => request.method() === 'POST' &&+ request.url().endsWith(`/forms/${form.slug}/answer`))+ await page.getByRole('button', { name: /submit/i }).click()+ const payload = (await submission).postDataJSON()+ expect(Number(payload.control)).toBe(item.computed ? 1 : item.value)+ expect(payload.feedback).toBe('Kept answer')+ if (item.computed) expect(payload.dependent).toBe('Recomputed answer')+ await expect.poll(async () => {+ const response = await request.get(`${api}/open/forms/${form.slug}/submissions`, { headers })+ expect(response.ok()).toBeTruthy()+ return (await response.json()).data[0]?.data+ }).toMatchObject({ control: payload.control, feedback: 'Kept answer' })+ }+ })+ }+}++for (const toggle of [false, true]) {+ for (const checked of [true, false]) {+ test(`${toggle ? 'switch' : 'checkbox'} restores a ${checked ? 'checked' : 'unchecked'} draft after hydration and keeps autosave consistent`, async ({ page, request }, testInfo) => {+ const warnings = collectHydrationWarnings(page)+ const form = await createForm(request, [+ { id: 'choice', name: 'Choice', type: 'checkbox', use_toggle_switch: toggle, prefill: !checked, hidden: false },+ { id: 'feedback', name: 'Feedback', type: 'text', prefill: 'Configured answer', hidden: false },+ { id: 'scale', name: 'Scale', type: 'scale', scale_min_value: 1, scale_max_value: 5, scale_step_value: 0.5 },+ { id: 'details', name: 'Details', type: 'text', logic: {+ conditions: { identifier: 'choice', value: {+ operator: 'is_not_checked', property_meta: { id: 'choice', type: 'checkbox' },+ } }, actions: ['hide-block'],+ } },+ ], { auto_save: true })+ const definition = await request.get(`${api}/forms/${form.slug}`)+ const publicForm = await definition.json()+ const path = `/forms/${form.slug}`+ const key = `${publicForm.form_pending_submission_key}-${hash(new URL(path, testInfo.project.use.baseURL as string).href)}`+ await page.addInitScript(({ key, checked }) => {+ if (localStorage.getItem(key) === null) {+ localStorage.setItem(key, JSON.stringify({ choice: checked, feedback: 'Saved answer', scale: '2.5' }))+ }+ }, { key, checked })+ await page.goto(path)+ await page.waitForLoadState('networkidle')+ const control = page.getByRole(toggle ? 'switch' : 'checkbox', { name: 'Choice', exact: true })+ await expect(control).toBeChecked({ checked })+ await expect(page.getByLabel('Feedback', { exact: true })).toHaveValue('Saved answer')+ await expect(page.getByRole('radio', { name: 'Scale value 2.5', exact: true })).toHaveAttribute('aria-checked', 'true')+ await expect(page.getByTestId('open-form-field-details')).toHaveCount(checked ? 1 : 0)+ expect(warnings).toEqual([])++ await page.getByLabel('Feedback', { exact: true }).fill('Updated answer')+ await control.press('Space')+ await expect.poll(async () => page.evaluate(key => JSON.parse(localStorage.getItem(key) || '{}'), key))+ .toMatchObject({ choice: !checked, feedback: 'Updated answer', scale: 2.5 })+ await page.reload()+ await page.waitForLoadState('networkidle')+ await expect(control).toBeChecked({ checked: !checked })+ await expect(page.getByLabel('Feedback', { exact: true })).toHaveValue('Updated answer')+ await expect(page.getByTestId('open-form-field-details')).toHaveCount(checked ? 0 : 1)++ const submission = page.waitForRequest(request => request.method() === 'POST' &&+ request.url().endsWith(`/forms/${form.slug}/answer`))+ await page.getByRole('button', { name: /submit/i }).click()+ expect((await submission).postDataJSON()).toMatchObject({ choice: !checked, feedback: 'Updated answer', scale: 2.5 })+ await expect.poll(async () => page.evaluate(key => localStorage.getItem(key), key)).toBeNull()+ // Check after the trailing autosave timer, not only immediately after clearing.+ await page.waitForTimeout(1100)+ expect(await page.evaluate(key => localStorage.getItem(key), key)).toBeNull()+ expect(warnings).toEqual([])+ })+ }+}++test('focused drafts restore No and lazy numeric controls before stepping and submitting', async ({ page, request }, testInfo) => {+ const warnings = collectHydrationWarnings(page)+ const form = await createForm(request, [+ { id: 'choice', name: 'Choice', type: 'checkbox', prefill: true },+ { id: 'rating', name: 'Rating', type: 'rating', rating_max_value: 5 },+ { id: 'scale', name: 'Scale', type: 'scale', scale_min_value: 1, scale_max_value: 5, scale_step_value: 0.5 },+ { id: 'feedback', name: 'Feedback', type: 'text', prefill: 'Configured answer' },+ ], { auto_save: true, presentation_style: 'focused' })+ const publicForm = await (await request.get(`${api}/forms/${form.slug}`)).json()+ const path = `/forms/${form.slug}`+ const key = `${publicForm.form_pending_submission_key}-${hash(new URL(path, testInfo.project.use.baseURL as string).href)}`+ await page.addInitScript(key => {+ localStorage.setItem(key, JSON.stringify({ choice: false, rating: 4, scale: '2.5', feedback: 'Saved answer' }))+ }, key)+ await page.goto(path)+ await page.waitForLoadState('networkidle')+ await expect(page.getByRole('option', { name: /No/i })).toHaveAttribute('aria-selected', 'true')+ await nextFocusedStep(page)+ await expect(page.getByRole('slider')).toHaveAttribute('aria-valuenow', '4')+ await nextFocusedStep(page)+ await expect(page.getByRole('radio', { name: 'Scale value 2.5', exact: true })).toHaveAttribute('aria-checked', 'true')+ await nextFocusedStep(page)+ await expect(page.getByLabel('Feedback', { exact: true })).toHaveValue('Saved answer')+ const submission = page.waitForRequest(request => request.method() === 'POST' && request.url().endsWith(`/forms/${form.slug}/answer`))+ await page.getByRole('button', { name: /submit/i }).click()+ expect((await submission).postDataJSON()).toMatchObject({ choice: false, rating: 4, scale: 2.5, feedback: 'Saved answer' })+ await expect.poll(async () => page.evaluate(key => localStorage.getItem(key), key)).toBeNull()+ expect(warnings).toEqual([])+})++for (const partialSync of [true, false]) {+ test(`slow draft hydration protects ${partialSync ? 'partial synchronization' : 'manual editing and submission'}`, async ({ page, request }, testInfo) => {+ const warnings = collectHydrationWarnings(page)+ const form = await createForm(request, [+ { id: 'rating', name: 'Rating', type: 'rating', rating_max_value: 5 },+ { id: 'choice', name: 'Choice', type: 'checkbox', use_toggle_switch: true },+ { id: 'feedback', name: 'Feedback', type: 'text', prefill: 'Configured answer' },+ ], { auto_save: true, enable_partial_submissions: partialSync })+ const publicForm = await (await request.get(`${api}/forms/${form.slug}`)).json()+ const path = `/forms/${form.slug}`+ const key = `${publicForm.form_pending_submission_key}-${hash(new URL(path, testInfo.project.use.baseURL as string).href)}`+ const draft = { rating: 4, choice: true, feedback: 'Saved answer', ...(partialSync ? { submission_hash: 'saved-partial-hash' } : {}) }+ await page.addInitScript(({ key, draft }) => localStorage.setItem(key, JSON.stringify(draft)), { key, draft })+ const submissions: Record<string, unknown>[] = []+ await page.route(`**/forms/${form.slug}/answer`, route => {+ submissions.push(route.request().postDataJSON())+ return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({+ submission_id: 'saved-submission', submission_hash: 'saved-partial-hash',+ }) })+ })+ const input = await holdRatingInput(page)+ try {+ await page.goto(path, { waitUntil: 'domcontentloaded' })+ await expect.poll(input.isHeld).toBe(true)+ await expect(page.locator('.open-complete-form')).toHaveAttribute('inert', '')+ if (!partialSync) {+ // Native events must not change or submit the SSR answers while a draft is pending.+ await page.getByLabel('Feedback', { exact: true }).click({ force: true })+ await page.keyboard.type('Premature answer')+ await page.getByRole('button', { name: /submit/i }).click({ force: true })+ }+ // Cross the partial-sync debounce while the component is deliberately held.+ await page.waitForTimeout(2500)+ expect(submissions).toEqual([])+ expect(await page.evaluate(key => JSON.parse(localStorage.getItem(key) || '{}'), key)).toEqual(draft)++ input.release()+ await expect(page.locator('.open-complete-form')).not.toHaveAttribute('inert')+ await expect(page.getByLabel('Feedback', { exact: true })).toHaveValue('Saved answer')+ await expect(page.getByRole('switch', { name: 'Choice', exact: true })).toBeChecked()+ if (partialSync) {+ await expect.poll(() => submissions.length).toBe(1)+ expect(submissions[0]).toMatchObject({ ...draft, is_partial: true })+ } else {+ await page.getByLabel('Feedback', { exact: true }).fill('Updated answer')+ await page.getByRole('button', { name: /submit/i }).click()+ await expect.poll(() => submissions.length).toBe(1)+ expect(submissions[0]).toMatchObject({ rating: 4, choice: true, feedback: 'Updated answer' })+ await expect.poll(async () => page.evaluate(key => localStorage.getItem(key), key)).toBeNull()+ await page.waitForTimeout(1100)+ expect(await page.evaluate(key => localStorage.getItem(key), key)).toBeNull()+ }+ expect(warnings).toEqual([])+ } finally {+ input.release()+ }+ })+}++for (const fragment of ['', '#section']) {+ test(`auto-submit uses restored draft answers after hydration without flashing the form${fragment}`, async ({ page, request }, testInfo) => {+ const warnings = collectHydrationWarnings(page)+ const form = await createForm(request, [+ { id: 'choice', name: 'Choice', type: 'checkbox', use_toggle_switch: true, prefill: false, required: true },+ { id: 'feedback', name: 'Feedback', type: 'text', required: true },+ { id: 'scale', name: 'Scale', type: 'scale', scale_min_value: 1, scale_max_value: 5, scale_step_value: 0.5 },+ ], { auto_save: true })+ const publicForm = await (await request.get(`${api}/forms/${form.slug}`)).json()+ const path = `/forms/${form.slug}?auto_submit=true${fragment}`+ const response = await request.get(path)+ expect(response.ok()).toBeTruthy()+ expect(await response.text()).not.toContain('data-testid="open-form-field-choice"')+ const key = `${publicForm.form_pending_submission_key}-${hash(new URL(path, testInfo.project.use.baseURL as string).href)}`+ await page.addInitScript(key => {+ localStorage.setItem(key, JSON.stringify({ choice: true, feedback: 'Saved auto-submit answer', scale: '2.5' }))+ }, key)+ const submission = page.waitForResponse(response => response.request().method() === 'POST' &&+ response.url().endsWith(`/forms/${form.slug}/answer`))+ await page.goto(path)+ expect((await submission).ok()).toBeTruthy()+ expect((await submission).request().postDataJSON()).toMatchObject({ choice: true, feedback: 'Saved auto-submit answer', scale: 2.5 })+ await page.waitForLoadState('networkidle')+ expect(warnings).toEqual([])+ })+}++for (const autoSubmit of [false, true]) {+ test(`encoded and repeated query values survive SSR and ${autoSubmit ? 'auto-submission' : 'refilling'}`, async ({ page, request, browser }, testInfo) => {+ const warnings = collectHydrationWarnings(page)+ const prefill = 'Why? #section & A+B 100%'+ const form = await createForm(request, [+ { id: 'feedback', name: 'Feedback', type: 'text', required: true },+ { id: 'choices', name: 'Choices', type: 'multi_select', hidden: true,+ multi_select: { options: [{ id: 'one', name: 'One' }, { id: 'two', name: 'Two' }] } },+ ], { auto_save: true, re_fillable: true, re_fill_button_text: 'Fill again' })+ const publicForm = await (await request.get(`${api}/forms/${form.slug}`)).json()+ const query = new URLSearchParams({ feedback: prefill })+ query.append('choices[]', 'one')+ query.append('choices[]', 'two')+ if (autoSubmit) query.append('auto_submit', 'true')+ const path = `/forms/${form.slug}?${query}#section`++ const ssr = await browser.newContext({ javaScriptEnabled: false, baseURL: testInfo.project.use.baseURL as string })+ try {+ const serverPage = await ssr.newPage()+ await serverPage.goto(path)+ if (autoSubmit) {+ await expect(serverPage.getByLabel('Feedback', { exact: true })).toHaveCount(0)+ } else {+ await expect(serverPage.getByLabel('Feedback', { exact: true })).toHaveValue(prefill)+ }+ } finally {+ await ssr.close()+ }++ const submissions: Record<string, unknown>[] = []+ await page.route(`**/forms/${form.slug}/answer`, route => {+ submissions.push(route.request().postDataJSON())+ return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ submission_id: 'saved-submission' }) })+ })+ await page.goto(path)+ await page.waitForLoadState('networkidle')+ // Vue Router canonicalizes escaped query characters; drafts use the browser URL.+ const key = `${publicForm.form_pending_submission_key}-${hash(page.url())}`+ if (!autoSubmit) {+ await expect(page.getByLabel('Feedback', { exact: true })).toHaveValue(prefill)+ await page.getByRole('button', { name: /submit/i }).click()+ }+ await expect(page.getByRole('button', { name: 'Fill again', exact: true })).toBeVisible()+ expect(submissions).toHaveLength(1)+ expect(submissions[0]).toMatchObject({ feedback: prefill, choices: ['One', 'Two'] })+ await page.waitForTimeout(1100)+ expect(await page.evaluate(key => localStorage.getItem(key), key)).toBeNull()++ if (!autoSubmit) {+ await page.getByRole('button', { name: 'Fill again', exact: true }).click()+ await expect(page.getByLabel('Feedback', { exact: true })).toHaveValue(prefill)+ await page.getByLabel('Feedback', { exact: true }).fill('New draft after refilling')+ await expect.poll(async () => page.evaluate(key => JSON.parse(localStorage.getItem(key) || '{}'), key))+ .toMatchObject({ feedback: 'New draft after refilling', choices: ['One', 'Two'] })+ await page.reload()+ await expect(page.getByLabel('Feedback', { exact: true })).toHaveValue('New draft after refilling')+ }+ expect(warnings).toEqual([])+ })+}diff --git a/client/test/e2e/opnform-flows.spec.ts b/client/test/e2e/opnform-flows.spec.tsindex 44e56d71d..8ac894358 100644--- a/client/test/e2e/opnform-flows.spec.ts+++ b/client/test/e2e/opnform-flows.spec.ts@@ -1,4 +1,5 @@import { expect, test, type APIRequestContext, type Page } from "@playwright/test"+import { hash } from "../../lib/utils.js"test.setTimeout(240_000)@@ -391,6 +392,7 @@ async function openPublicForm(page: Page, slug: string) {await gotoPageWithRetry(page, `/forms/${slug}`, async () => {await expect(page.getByTestId("public-form-page")).toBeVisible()})+ await page.waitForLoadState("networkidle")}async function expectSubmissionSuccess(page: Page) {@@ -936,6 +938,227 @@ test("public form surfaces required and invalid email validation errors", asyncawait expectFieldError(page, "required_email", /valid email address/i)})+for (const toggle of [false, true]) {+ for (const prefill of ["", "true", "false"]) {+ const checked = prefill === "true"+ test(`public form initial visibility with ${toggle ? "toggle" : "checkbox"} and ${prefill || "empty"} prefill`, async ({ page, request, browser }) => {+ const form = await apiCreateForm(request, {+ title: uniqueTitle("Initial Visibility"),+ payloadOverrides: {+ auto_save: false,+ properties: [+ buildCheckboxField("include_files", "Include files", { use_toggle_switch: toggle }),+ {+ id: "attachments",+ name: "Attach files (optional)",+ type: "files",+ hidden: false,+ required: false,+ logic: {+ conditions: {+ identifier: "include_files",+ value: {+ operator: "is_not_checked",+ property_meta: { id: "include_files", type: "checkbox" },+ },+ },+ actions: ["hide-block"],+ },+ },+ buildTextField("internal", "Internal field", { hidden: true }),+ ],+ },+ })+ const path = `/forms/${form.slug}${prefill ? `?include_files=${prefill}` : ""}`+ const response = await request.get(path)+ expect(response.ok()).toBeTruthy()+ const html = await response.text()+ expect(html.includes('data-testid="open-form-field-attachments"')).toBe(checked)+ expect(html).not.toContain('data-testid="open-form-field-internal"')++ // Inspect the actual first paint without allowing hydration to hide a wrong SSR field.+ const context = await browser.newContext({ javaScriptEnabled: false })+ try {+ const firstRender = await context.newPage()+ await firstRender.goto(new URL(path, response.url()).href)+ await expect(firstRender.getByLabel("Include files", { exact: true })).toBeVisible()+ await expect(getOpenFormField(firstRender, "attachments")).toHaveCount(checked ? 1 : 0)+ await expect(getOpenFormField(firstRender, "internal")).toHaveCount(0)+ } finally {+ await context.close()+ }++ await openPublicForm(page, `${form.slug}${prefill ? `?include_files=${prefill}` : ""}`)+ await page.waitForLoadState("networkidle")+ const control = page.getByRole(toggle ? "switch" : "checkbox", { name: "Include files", exact: true })+ await expect(control).toBeChecked({ checked })+ await expect(getOpenFormField(page, "attachments")).toHaveCount(checked ? 1 : 0)+ await control.click()+ await expect(getOpenFormField(page, "attachments")).toHaveCount(checked ? 0 : 1)+ await control.click()+ await expect(getOpenFormField(page, "attachments")).toHaveCount(checked ? 1 : 0)+ await expect(getOpenFormField(page, "internal")).toHaveCount(0)+ })+ }+}++for (const toggle of [false, true]) {+ test(`initialized ${toggle ? "toggle" : "checkbox"} preserves required validation and submitted answers`, async ({ page, request }) => {+ const form = await apiCreateForm(request, {+ payloadOverrides: {+ auto_save: false,+ properties: [+ buildCheckboxField("consent", "Consent", { required: true, use_toggle_switch: toggle }),+ buildCheckboxField("optional", "Optional checkbox"),+ buildCheckboxField("internal", "Internal checkbox", { hidden: true, required: true }),+ buildTextField("details", "Details", {+ required: true,+ logic: {+ conditions: { identifier: "consent", value: {+ operator: "is_not_checked", property_meta: { id: "consent", type: "checkbox" },+ } },+ actions: ["hide-block"],+ },+ }),+ ],+ },+ })+ await openPublicForm(page, form.slug)+ await page.waitForLoadState("networkidle")+ await expect(getOpenFormField(page, "details")).toHaveCount(0)+ await page.getByRole("button", { name: /submit/i }).click()+ await expectFieldError(page, "consent", /Consent.*accepted/)++ const control = page.getByRole(toggle ? "switch" : "checkbox", { name: "Consent", exact: true })+ await control.focus()+ await control.press("Space")+ await expect(control).toBeChecked()+ await expect(getOpenFormField(page, "details")).toBeVisible()+ await page.getByRole("button", { name: /submit/i }).click()+ await expectFieldError(page, "details", /Details.*required/)+ await fillFieldInput(page, "details", "Preserved answer")+ await page.getByRole("button", { name: /submit/i }).click()+ await expectSubmissionSuccess(page)++ const submissions = await apiListSubmissions(request, await apiLogin(request), form.slug)+ expect(submissions.data).toHaveLength(1)+ expect(submissions.data[0].data).toMatchObject({ consent: true, optional: false, details: "Preserved answer" })+ })+}++for (const checked of [false, true]) {+ test(`checkbox initialization preserves ${checked ? "a checked" : "an unchecked"} draft, autosave and other answers`, async ({ page, request }, testInfo) => {+ const form = await apiCreateForm(request, {+ payloadOverrides: {+ auto_save: true,+ properties: [+ buildCheckboxField("include_files", "Include files", { prefill: !checked }),+ buildTextField("feedback", "Feedback", { prefill: "Configured answer" }),+ buildTextField("details", "Details", {+ logic: { conditions: { identifier: "include_files", value: {+ operator: "is_not_checked", property_meta: { id: "include_files", type: "checkbox" },+ } }, actions: ["hide-block"] },+ }),+ ],+ },+ })+ const definition = await request.get(`${API_BASE_URL}/forms/${form.slug}`)+ const publicForm = await definition.json()+ const url = new URL(`/forms/${form.slug}`, testInfo.project.use.baseURL as string).href+ const key = `${publicForm.form_pending_submission_key}-${hash(url)}`+ await page.addInitScript(({ key, checked }) => {+ if (localStorage.getItem(key) === null) {+ localStorage.setItem(key, JSON.stringify({ include_files: checked, feedback: "Saved answer" }))+ }+ }, { key, checked })+ await openPublicForm(page, form.slug)+ await page.waitForLoadState("networkidle")+ const control = page.getByRole("checkbox", { name: "Include files", exact: true })+ await expect(control).toBeChecked({ checked })+ await expect(page.getByLabel("Feedback", { exact: true })).toHaveValue("Saved answer")+ await expect(getOpenFormField(page, "details")).toHaveCount(checked ? 1 : 0)+ await fillFieldInput(page, "feedback", "Updated answer")+ await control.click()+ await expect.poll(async () => page.evaluate((key) => JSON.parse(localStorage.getItem(key) || "{}"), key))+ .toMatchObject({ include_files: !checked, feedback: "Updated answer" })+ await page.reload()+ await page.waitForLoadState("networkidle")+ await expect(control).toBeChecked({ checked: !checked })+ await expect(page.getByLabel("Feedback", { exact: true })).toHaveValue("Updated answer")+ await expect(getOpenFormField(page, "details")).toHaveCount(checked ? 0 : 1)+ await page.getByRole("button", { name: /submit/i }).click()+ await expectSubmissionSuccess(page)+ const submissions = await apiListSubmissions(request, await apiLogin(request), form.slug)+ expect(submissions.data[0].data).toMatchObject({ include_files: !checked, feedback: "Updated answer" })+ await expect.poll(async () => page.evaluate((key) => localStorage.getItem(key), key)).toBeNull()+ })+}++for (const required of [false, true]) {+ test(`focused ${required ? "required Yes" : "optional No"} checkbox stays unanswered and submits the selected value`, async ({ page, request }) => {+ const form = await apiCreateForm(request, {+ presentationStyle: "focused",+ payloadOverrides: {+ auto_save: false,+ settings: { navigation_arrows: true, auto_next: false },+ properties: [buildCheckboxField("choice", "Your choice", { required })],+ },+ })+ await openPublicForm(page, form.slug)+ await page.waitForLoadState("networkidle")+ const yes = page.getByRole("option", { name: /Yes/i })+ const no = page.getByRole("option", { name: /No/i })+ await expect(yes).toHaveAttribute("aria-selected", "false")+ await expect(no).toHaveAttribute("aria-selected", "false")+ if (required) {+ const validation = page.waitForResponse((response) => response.url().endsWith(`/forms/${form.slug}/answer`))+ await page.getByRole("button", { name: /submit/i }).click()+ expect((await validation).status()).toBe(422)+ await expect(yes).toHaveAttribute("aria-selected", "false")+ await expect(no).toHaveAttribute("aria-selected", "false")+ }+ await (required ? yes : no).click()+ await expect(required ? yes : no).toHaveAttribute("aria-selected", "true")+ await page.getByRole("button", { name: /submit/i }).click()+ await expectSubmissionSuccess(page)+ const submissions = await apiListSubmissions(request, await apiLogin(request), form.slug)+ expect(submissions.data[0].data.choice).toBe(required)+ })+}++test("checkbox initialization preserves answers when editing a stored submission", async ({ page, request }) => {+ const form = await apiCreateForm(request, {+ payloadOverrides: {+ auto_save: false,+ editable_submissions: true,+ properties: [+ buildCheckboxField("choice", "Your choice"),+ buildTextField("feedback", "Feedback", { required: true }),+ ],+ },+ })+ await openPublicForm(page, form.slug)+ await page.waitForLoadState("networkidle")+ await fillFieldInput(page, "feedback", "Original answer")+ const submitted = page.waitForResponse((response) => response.url().endsWith(`/forms/${form.slug}/answer`))+ await page.getByRole("button", { name: /submit/i }).click()+ await expectSubmissionSuccess(page)+ const { submission_id: submissionId } = await (await submitted).json()+ expect(submissionId).toBeTruthy()++ await openPublicForm(page, `${form.slug}?submission_id=${submissionId}`)+ await page.waitForLoadState("networkidle")+ await expect(page.getByRole("checkbox", { name: "Your choice", exact: true })).not.toBeChecked()+ await expect(page.getByLabel("Feedback", { exact: true })).toHaveValue("Original answer")+ await page.getByRole("checkbox", { name: "Your choice", exact: true }).check()+ await fillFieldInput(page, "feedback", "Edited answer")+ await page.getByRole("button", { name: /submit/i }).click()+ await expectSubmissionSuccess(page)+ const submissions = await apiListSubmissions(request, await apiLogin(request), form.slug)+ expect(submissions.data).toHaveLength(1)+ expect(submissions.data[0].data).toMatchObject({ choice: true, feedback: "Edited answer" })+})+test("public form logic reveals and requires follow-up details conditionally", async ({ page, request }) => {const form = await apiCreateForm(request, {title: uniqueTitle("Conditional Logic"),diff --git a/client/test/nuxt/computed-variables.spec.ts b/client/test/nuxt/computed-variables.spec.tsindex e0bcc76d9..a50ce4c08 100644--- a/client/test/nuxt/computed-variables.spec.ts+++ b/client/test/nuxt/computed-variables.spec.ts@@ -188,4 +188,22 @@ describe('useComputedVariables', () => {expect(aIdx).toBeLessThan(bIdx)expect(bIdx).toBeLessThan(cIdx)})++ it('resolves answers, formulas and field changes synchronously without a watcher tick', () => {+ const form = ref({+ computed_variables: [{ id: 'cv_total', name: 'Total', formula: '{amount} * 2' }],+ properties: [{ id: 'amount', name: 'Amount' }],+ })+ const formData = ref({ amount: 5, replacement: 7 })+ const { values } = useComputedVariables(form, formData)+ expect(values.value.cv_total).toBe(10)++ formData.value.amount = 9+ expect(values.value.cv_total).toBe(18)+ form.value.computed_variables[0].formula = '{replacement} * 3'+ form.value.properties = [{ id: 'replacement', name: 'Replacement' }]+ expect(values.value.cv_total).toBe(21)+ form.value.computed_variables = []+ expect(values.value).toEqual({})+ })})diff --git a/client/test/nuxt/form-initialization-visibility.spec.ts b/client/test/nuxt/form-initialization-visibility.spec.tsnew file mode 100644index 000000000..5563a42e7--- /dev/null+++ b/client/test/nuxt/form-initialization-visibility.spec.ts@@ -0,0 +1,364 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { computed, createSSRApp, h, reactive, ref, watch } from 'vue'+import { renderToString } from 'vue/server-renderer'+import { formsApi } from '~/api'+import Form from '~/composables/lib/vForm/Form.js'+import { createFormModeStrategy, FormMode } from '~/lib/forms/FormModeStrategy'+import { useFieldState } from '~/lib/forms/composables/useFieldState'+import { useFormInitialization } from '~/lib/forms/composables/useFormInitialization'+import { useFocusedStructure } from '~/lib/forms/composables/useFocusedStructure'+import { useFormStructure } from '~/lib/forms/composables/useFormStructure'+import { useComputedVariables } from '~/composables/forms/useComputedVariables'++vi.mock('~/api', () => ({+ apiService: {},+ formsApi: { submissions: { get: vi.fn() } },+}))++vi.mock('#app', async () => ({ createError: (await import('h3')).createError }))++function createFixture(configOverrides = {}, pendingData = null) {+ const config = ref({+ slug: 'feedback',+ presentation_style: 'classic',+ properties: [+ { id: 'include_files', type: 'checkbox', hidden: false },+ {+ id: 'attachments', type: 'files', hidden: false,+ logic: {+ conditions: {+ identifier: 'include_files',+ value: {+ operator: 'is_not_checked',+ property_meta: { id: 'include_files', type: 'checkbox' },+ },+ },+ actions: ['hide-block'],+ },+ },+ ],+ ...configOverrides,+ })+ const form = reactive(new Form())+ const initialization = useFormInitialization(config, form, {+ enabled: ref(true),+ get: () => pendingData,+ })+ const fieldState = useFieldState(+ computed(() => form.data()), config, ref(createFormModeStrategy(FormMode.LIVE)),+ )+ return { config, form, initialization, fieldState }+}++describe('form visibility before inputs mount', () => {+ beforeEach(() => vi.clearAllMocks())++ it('hides the file field on the first render when its controlling checkbox is empty', async () => {+ const { config, form, initialization, fieldState } = createFixture()++ await initialization.initialize()++ expect(form.include_files).toBe(false)+ expect(fieldState.getState(config.value.properties[1]).hidden).toBe(true)++ form.include_files = true+ expect(fieldState.getState(config.value.properties[1]).hidden).toBe(false)+ form.include_files = false+ expect(fieldState.getState(config.value.properties[1]).hidden).toBe(true)+ })++ it.each([undefined, null, ''])('treats a %s checkbox value as unchecked', async (value) => {+ const { config, form, initialization, fieldState } = createFixture()++ await initialization.initialize({ defaultData: { include_files: value } })++ expect(form.include_files).toBe(false)+ expect(fieldState.getState(config.value.properties[1]).hidden).toBe(true)+ })++ it.each([+ ['true', true], ['false', false], ['1', true], ['0', false], ['', false],+ ])('resolves URL prefill %s before visibility is evaluated', async (value, expected) => {+ const { config, form, initialization, fieldState } = createFixture()++ await initialization.initialize({ urlParams: new URLSearchParams({ include_files: value }) })++ expect(form.include_files).toBe(expected)+ expect(fieldState.getState(config.value.properties[1]).hidden).toBe(!expected)+ })++ it.each([true, false])('preserves the configured checkbox prefill %s', async (prefill) => {+ const fixture = createFixture()+ fixture.config.value.properties[0].prefill = prefill++ await fixture.initialization.initialize()++ expect(fixture.form.include_files).toBe(prefill)+ expect(fixture.fieldState.getState(fixture.config.value.properties[1]).hidden).toBe(!prefill)+ })++ it.each([true, false])('preserves the explicit default answer %s', async (value) => {+ const { config, form, initialization, fieldState } = createFixture()++ await initialization.initialize({ defaultData: { include_files: value } })++ expect(form.include_files).toBe(value)+ expect(fieldState.getState(config.value.properties[1]).hidden).toBe(!value)+ })++ it('initializes a hidden controlling checkbox even though it will never mount', async () => {+ const fixture = createFixture()+ fixture.config.value.properties[0].hidden = true++ await fixture.initialization.initialize()++ expect(fixture.form.include_files).toBe(false)+ expect(fixture.fieldState.getState(fixture.config.value.properties[1]).hidden).toBe(true)+ })++ it('applies a new configured prefill when reinitializing an initially unanswered checkbox', async () => {+ const { config, form, initialization } = createFixture()+ await initialization.initialize()+ expect(form.include_files).toBe(false)++ config.value = {+ ...config.value,+ properties: config.value.properties.map(field => field.id === 'include_files' ? { ...field, prefill: true } : field),+ }+ await initialization.initialize()++ expect(form.include_files).toBe(true)+ })++ it('retains an explicit unchecked answer when reinitializing with a checked prefill', async () => {+ const { config, form, initialization } = createFixture()+ await initialization.initialize({ defaultData: { include_files: false } })+ config.value.properties[0].prefill = true++ await initialization.initialize()++ expect(form.include_files).toBe(false)+ })++ it('allows a new prefill after an initially empty checkbox string', async () => {+ const { config, form, initialization } = createFixture()+ await initialization.initialize({ defaultData: { include_files: '' } })+ config.value.properties[0].prefill = true++ await initialization.initialize()++ expect(form.include_files).toBe(true)+ })++ it.each([undefined, null])('applies a changed prefill after initializing an unanswered %s checkbox value', async (value) => {+ const { config, form, initialization } = createFixture()+ await initialization.initialize({ defaultData: { include_files: value } })+ expect(form.include_files).toBe(false)+ config.value.properties[0].prefill = true++ await initialization.initialize()++ expect(form.include_files).toBe(true)+ })++ it('adds an unchecked default when restoring a draft that omits the checkbox', async () => {+ const { config, form, initialization, fieldState } = createFixture({}, { feedback: 'Saved feedback' })++ await initialization.initialize()++ expect(form.feedback).toBe('Saved feedback')+ expect(form.include_files).toBe(false)+ expect(fieldState.getState(config.value.properties[1]).hidden).toBe(true)+ })++ it.each(['true', 'false'])('preserves a restored draft checkbox value of %s', async (value) => {+ const { config, form, initialization, fieldState } = createFixture({}, { include_files: value })++ await initialization.initialize()++ expect(form.include_files).toBe(value === 'true')+ expect(fieldState.getState(config.value.properties[1]).hidden).toBe(value !== 'true')+ })++ it('applies configured prefill to an omitted draft checkbox before resolving visibility', async () => {+ const fixture = createFixture({}, { feedback: 'Saved feedback' })+ fixture.config.value.properties[0].prefill = true++ await fixture.initialization.initialize()++ expect(fixture.form.include_files).toBe(true)+ expect(fixture.fieldState.getState(fixture.config.value.properties[1]).hidden).toBe(false)+ })++ it.each([{}, { include_files: true }])('normalizes existing submission answers %j', async (data) => {+ vi.mocked(formsApi.submissions.get).mockResolvedValue({ data })+ const { config, form, initialization, fieldState } = createFixture()++ await initialization.initialize({ submissionId: 'submission-id' })++ expect(form.include_files).toBe(data.include_files ?? false)+ expect(fieldState.getState(config.value.properties[1]).hidden).toBe(!data.include_files)+ })++ it('keeps an unanswered focused Yes/No field unanswered', async () => {+ const { form, initialization } = createFixture({ presentation_style: 'focused' })++ await initialization.initialize()++ expect(form.include_files).toBeUndefined()+ })++ it('initializes a standard checkbox in a focused form when the Yes/No selector is disabled', async () => {+ const fixture = createFixture({ presentation_style: 'focused' })+ fixture.config.value.properties[0].use_focused_toggle = false++ await fixture.initialization.initialize()++ expect(fixture.form.include_files).toBe(false)+ const structure = useFocusedStructure(fixture.config, { currentPage: 0 }, fixture.form, fixture.fieldState)+ expect(structure.pageCount.value).toBe(1)+ })++ it('evaluates conditional page breaks before building the first page', async () => {+ const fixture = createFixture()+ fixture.config.value.properties[1].type = 'nf-page-break'+ fixture.config.value.properties.push({ id: 'email', type: 'email', hidden: false })++ await fixture.initialization.initialize()++ const structure = useFormStructure(fixture.config, { currentPage: 0 }, fixture.form, fixture.fieldState)+ expect(structure.pageCount.value).toBe(1)+ expect(structure.getPageFields(0).map(field => field.id)).toContain('email')+ })++ for (const style of ['classic', 'focused']) {+ it.each(['rating', 'slider'])(`preserves an explicit zero ${style} %s answer on reinitialization`, async (type) => {+ const fixture = createFixture({ presentation_style: style })+ fixture.config.value.properties[0] = { id: 'control', type, prefill: 4 }+ await fixture.initialization.initialize({ defaultData: { control: 0 } })++ await fixture.initialization.initialize()++ expect(fixture.form.control).toBe(0)+ })+ it.each([undefined, null, ''])(`keeps an empty ${style} scale unanswered (%s)`, async (value) => {+ const fixture = createFixture({ presentation_style: style })+ fixture.config.value.properties[0] = { id: 'control', type: 'scale' }++ await fixture.initialization.initialize({ defaultData: { control: value } })++ expect(fixture.form.control).toBe(value)+ })+ for (const type of ['rating', 'slider']) {+ it.each([undefined, null, ''])(`initializes an empty ${style} ${type} before resolving visibility (%s)`, async (value) => {+ const fixture = createFixture({ presentation_style: style })+ fixture.config.value.properties[0] = { id: 'control', type, hidden: true }+ fixture.config.value.properties[1].logic.conditions = {+ identifier: 'control', value: {+ operator: 'equals', property_meta: { id: 'control', type }, value: 0,+ },+ }++ await fixture.initialization.initialize({ defaultData: { control: value } })++ expect(fixture.form.control).toBe(0)+ expect(fixture.fieldState.getState(fixture.config.value.properties[1]).hidden).toBe(true)+ fixture.config.value.properties[0].prefill = 4+ await fixture.initialization.initialize()+ expect(fixture.form.control).toBe(4)+ })+ }+ it.each(['configured prefill', 'URL', 'default data', 'draft', 'submission'])(`normalizes a ${style} decimal scale from %s without changing the source answer`, async (source) => {+ const data = { control: '2.5' }+ const fixture = createFixture({ presentation_style: style }, source === 'draft' ? data : null)+ fixture.config.value.properties[0] = { id: 'control', type: 'scale', prefill: '2.5' }+ fixture.config.value.properties[1].logic.conditions = {+ identifier: 'control', value: {+ operator: 'equals', property_meta: { id: 'control', type: 'scale' }, value: 2.5,+ },+ }+ if (source === 'submission') vi.mocked(formsApi.submissions.get).mockResolvedValue({ data })++ await fixture.initialization.initialize(source === 'URL'+ ? { urlParams: new URLSearchParams(data) }+ : source === 'default data' ? { defaultData: data }+ : source === 'submission' ? { submissionId: 'stored-id' } : {})++ expect(fixture.form.control).toBe(2.5)+ expect(fixture.fieldState.getState(fixture.config.value.properties[1]).hidden).toBe(true)+ expect(data.control).toBe('2.5')+ })++ for (const source of ['default data', 'draft', 'submission']) {+ it(`preserves other ${style} answers loaded from ${source} without mutating the source`, async () => {+ const data = {+ include_files: true, text: 'Original answer', number: 7, date: '2026-10-01',+ matrix: { Service: 'Good' }, select: 'first', multi: ['first'], submission_hash: 'stored-hash',+ }+ const original = structuredClone(data)+ const fixture = createFixture({ presentation_style: style }, source === 'draft' ? data : null)+ fixture.config.value.properties.push(+ { id: 'text', type: 'text' }, { id: 'number', type: 'number' }, { id: 'date', type: 'date' },+ { id: 'matrix', type: 'matrix' },+ { id: 'select', type: 'select', select: { options: [{ id: 'first', name: 'First' }] } },+ { id: 'multi', type: 'multi_select', multi_select: { options: [{ id: 'first', name: 'First' }] } },+ )+ if (source === 'submission') vi.mocked(formsApi.submissions.get).mockResolvedValue({ data })++ await fixture.initialization.initialize(source === 'default data'+ ? { defaultData: data }+ : source === 'submission' ? { submissionId: 'stored-id' } : {})++ expect(fixture.form.data()).toMatchObject({ ...data, select: 'First', multi: ['First'] })+ expect(data).toEqual(original)+ })+ }+ }++ it.each(['configured prefill', 'URL', 'default data', 'submission'])('renders chained computed visibility from %s during SSR', async (source) => {+ vi.stubGlobal('ref', ref)+ vi.stubGlobal('computed', computed)+ vi.stubGlobal('watch', watch)+ const data = { control: 5 }+ if (source === 'submission') vi.mocked(formsApi.submissions.get).mockResolvedValue({ data })+ const app = createSSRApp({+ async setup() {+ const fixture = createFixture({+ properties: [+ { id: 'control', type: 'number', ...(source === 'configured prefill' ? { prefill: 5 } : {}) },+ { id: 'dependent', type: 'text', logic: {+ conditions: { identifier: 'cv_total', value: {+ operator: 'greater_than', property_meta: { id: 'cv_total', type: 'computed', result_type: 'number' }, value: 10,+ } }, actions: ['hide-block'],+ } },+ ],+ computed_variables: [+ { id: 'cv_total', name: 'Total', formula: '{cv_double} + 1' },+ { id: 'cv_double', name: 'Double', formula: '{control} * 2' },+ ],+ })+ const variables = useComputedVariables(fixture.config, computed(() => fixture.form.data()))+ // Resolve once before initialization, as consumers can do during setup.+ expect(variables.values.value.cv_total).toBeNull()+ const states = useFieldState(computed(() => fixture.form.data()), fixture.config,+ ref(createFormModeStrategy(FormMode.LIVE)), variables.values)+ await fixture.initialization.initialize(source === 'URL'+ ? { urlParams: new URLSearchParams({ control: '5' }) }+ : source === 'default data' ? { defaultData: data }+ : source === 'submission' ? { submissionId: 'stored-id' } : {})+ return () => h('div', [+ h('span', String(variables.values.value.cv_total)),+ ...(states.getState(fixture.config.value.properties[1]).hidden ? [] : [h('input', { name: 'dependent' })]),+ ])+ },+ })+ try {+ const html = await renderToString(app)+ expect(html).toContain('<span>11</span>')+ expect(html).not.toContain('name="dependent"')+ } finally {+ vi.unstubAllGlobals()+ }+ })+})diff --git a/client/test/nuxt/partial-submission-hydration.spec.ts b/client/test/nuxt/partial-submission-hydration.spec.tsnew file mode 100644index 000000000..fbbf68fad--- /dev/null+++ b/client/test/nuxt/partial-submission-hydration.spec.ts@@ -0,0 +1,87 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mount } from '@vue/test-utils'+import { defineComponent, h, ref } from 'vue'+import { formsApi } from '~/api'+import { usePartialSubmission } from '~/composables/forms/usePartialSubmission'++vi.mock('~/api', () => ({+ formsApi: { submissions: { answer: vi.fn().mockResolvedValue({ submission_hash: 'saved-hash' }) } },+}))++describe('partial submissions during draft hydration', () => {+ const wrappers = []++ beforeEach(() => {+ vi.useFakeTimers()+ vi.clearAllMocks()+ })++ afterEach(() => {+ wrappers.splice(0).forEach(wrapper => wrapper.unmount())+ vi.useRealTimers()+ })++ function createSync() {+ const data = ref({ choice: false, feedback: 'Server defaults' })+ const pending = {+ formPendingSubmissionKey: ref('hydration-draft'),+ getSubmissionHash: () => 'saved-hash',+ setSubmissionHash: vi.fn(),+ }+ let service+ wrappers.push(mount(defineComponent({+ setup() {+ service = usePartialSubmission(ref({ slug: 'feedback', enable_partial_submissions: true }), data, pending)+ return () => h('div')+ },+ })))+ return { data, service, wrapper: wrappers[wrappers.length - 1] }+ }++ it('never sends server defaults on unmount if synchronization has not started', async () => {+ const { wrapper } = createSync()++ await vi.advanceTimersByTimeAsync(5000)+ wrapper.unmount()+ wrappers.pop()++ expect(formsApi.submissions.answer).not.toHaveBeenCalled()+ })++ it('starts with restored answers and the existing partial submission hash', async () => {+ const { data, service } = createSync()+ await vi.advanceTimersByTimeAsync(5000)+ expect(formsApi.submissions.answer).not.toHaveBeenCalled()++ data.value = { choice: true, feedback: 'Saved answer' }+ service.startSync()+ await vi.advanceTimersByTimeAsync(2000)++ expect(formsApi.submissions.answer).toHaveBeenCalledExactlyOnceWith('feedback', {+ choice: true, feedback: 'Saved answer', submission_hash: 'saved-hash', is_partial: true,+ })+ })++ it('still sends a final update when an active partial submission is stopped', async () => {+ const { data, service } = createSync()+ data.value = { choice: true, feedback: 'Saved answer' }+ service.startSync()++ service.stopSync()+ await vi.advanceTimersByTimeAsync(5000)++ expect(formsApi.submissions.answer).toHaveBeenCalledExactlyOnceWith('feedback', {+ choice: true, feedback: 'Saved answer', submission_hash: 'saved-hash', is_partial: true,+ })+ })++ it('does not send a trailing partial update when stopping for a final submission', async () => {+ const { service } = createSync()+ service.startSync()++ service.stopSync({ skipFinalSync: true })+ await vi.advanceTimersByTimeAsync(5000)++ expect(formsApi.submissions.answer).not.toHaveBeenCalled()+ })+})diff --git a/client/test/nuxt/usePendingSubmission.spec.ts b/client/test/nuxt/usePendingSubmission.spec.tsindex e1a6662dc..133c89401 100644--- a/client/test/nuxt/usePendingSubmission.spec.ts+++ b/client/test/nuxt/usePendingSubmission.spec.ts@@ -1,13 +1,14 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'-import { ref, computed, nextTick } from 'vue'+import { ref, computed, nextTick, effectScope } from 'vue'import { usePendingSubmission } from '../../lib/forms/composables/usePendingSubmission.js'const { storageRefs } = vi.hoisted(() => ({storageRefs: new Map()}))-vi.mock('@vueuse/core', async () => {- const { ref, watch } = await import('vue')+vi.mock('@vueuse/core', async (importOriginal) => {+ const { ref } = await import('vue')+ const { watchThrottled } = await importOriginal<typeof import('@vueuse/core')>()return {useStorage: (key, defaultValue = null) => {@@ -17,15 +18,12 @@ vi.mock('@vueuse/core', async () => {return storageRefs.get(key)},- watchThrottled: (source, callback, options = {}) => {- return watch(source, (value, oldValue, onCleanup) => {- callback(value, oldValue, onCleanup)- }, options)- }+ watchThrottled}})describe('usePendingSubmission', () => {+ const scopes = []beforeEach(() => {vi.useFakeTimers()storageRefs.clear()@@ -33,6 +31,8 @@ describe('usePendingSubmission', () => {})afterEach(() => {+ scopes.splice(0).forEach(scope => scope.stop())+ vi.clearAllTimers()vi.useRealTimers()storageRefs.clear()})@@ -45,7 +45,9 @@ describe('usePendingSubmission', () => {...configOverrides})const formData = ref(initialFormData)- const pendingSubmission = usePendingSubmission(formConfig, computed(() => formData.value))+ const scope = effectScope()+ scopes.push(scope)+ const pendingSubmission = scope.run(() => usePendingSubmission(formConfig, computed(() => formData.value)))!return {formData,@@ -55,7 +57,7 @@ describe('usePendingSubmission', () => {async function flushAutosave() {await nextTick()- await nextTick()+ await vi.advanceTimersByTimeAsync(1000)}it('stores submission hash when only partial submissions are enabled', () => {@@ -93,4 +95,56 @@ describe('usePendingSubmission', () => {})expect(pendingSubmission.getSubmissionHash()).toBe('submission-hash-2')})++ it('keeps a stored draft intact while server answers hydrate, then autosaves restored answers', async () => {+ const { formData, pendingSubmission } = createPendingSubmission({ auto_save: true })+ formData.value = { choice: true, feedback: 'Saved answer' }+ await flushAutosave()++ pendingSubmission.pauseAutosave()+ formData.value = { choice: false, feedback: 'Server prefill' }+ await flushAutosave()+ expect(pendingSubmission.get()).toEqual({ choice: true, feedback: 'Saved answer' })++ formData.value = pendingSubmission.get()+ pendingSubmission.resumeAutosave()+ await flushAutosave()+ formData.value = { choice: false, feedback: 'Updated answer' }+ await flushAutosave()+ expect(pendingSubmission.get()).toEqual({ choice: false, feedback: 'Updated answer' })+ })++ it('does not recreate a cleared draft from a queued autosave after submission', async () => {+ const { formData, pendingSubmission } = createPendingSubmission({ auto_save: true })+ formData.value = { feedback: 'First answer' }+ await nextTick()+ formData.value = { feedback: 'Submitted answer' }+ await nextTick()+ expect(pendingSubmission.get()).toEqual({ feedback: 'First answer' })++ pendingSubmission.pauseAutosave()+ pendingSubmission.clear()+ await vi.advanceTimersByTimeAsync(1100)++ expect(pendingSubmission.get()).toEqual({})+ })++ it('saves current answers when refilling before an earlier autosave timer expires', async () => {+ const { formData, pendingSubmission } = createPendingSubmission({ auto_save: true })+ formData.value = { feedback: 'First answer' }+ await nextTick()+ formData.value = { feedback: 'Submitted answer' }+ await nextTick()++ pendingSubmission.pauseAutosave()+ pendingSubmission.clear()+ formData.value = { feedback: 'Fresh prefill' }+ pendingSubmission.resumeAutosave()+ await flushAutosave()+ expect(pendingSubmission.get()).toEqual({ feedback: 'Fresh prefill' })++ formData.value = { feedback: 'New answer' }+ await flushAutosave()+ expect(pendingSubmission.get()).toEqual({ feedback: 'New answer' })+ })})