Skip to content

Beautiful Open-Source Form Builder

Make form saving explicit and save directly from Settings (#1359)

Julien Nahum2d3e17b3e18e
diff --git a/README.md b/README.md
index 9dccd33f1..cd51c61ba 100644
--- a/README.md
+++ b/README.md
@@ -98,6 +98,8 @@ Clearing a date with a click, Enter, or Space keeps the calendar closed. Reopen
## Editor history
+The form editor shows whether changes are saved. For an existing form, **Save Changes** saves both its design and settings; changes to a published form take effect immediately. In **Settings**, use **Save and close** to save directly, or **Close** to return to the editor with your changes still pending. While saving, Settings cannot be edited or dismissed. Failed saves preserve the pending edits for retry, and validation errors lead to the relevant field editor. For a new form, **Done** applies settings without creating or publishing it. Leaving the editor with unsaved changes asks for confirmation.
+
Clearing editor history uses the currently loaded form as the undo baseline and discards pending history updates. A subsequent edit can be undone back to that form without restoring an earlier loading state.
## Spreadsheet exports
diff --git a/client/components/open/forms/components/FormEditor.vue b/client/components/open/forms/components/FormEditor.vue
index 334589747..351465936 100644
--- a/client/components/open/forms/components/FormEditor.vue
+++ b/client/components/open/forms/components/FormEditor.vue
@@ -41,6 +41,8 @@
:back-button="backButton"
:update-form-loading="form.busy"
:save-button-class="saveButtonClass"
+ :is-edit="isEdit"
+ :has-unsaved-changes="hasUnsavedChanges"
@go-back="goBack"
@save-form="saveForm"
>
@@ -118,6 +120,7 @@
:show="showFormErrorModal"
:error-summary="saveErrorSummary"
@close="handleFormErrorModalClose"
+ @after:leave="finishValidationRecovery"
@edit-field="editInvalidField"
@edit-computed-variable="editInvalidComputedVariable"
/>
@@ -151,6 +154,10 @@ import { normalizeFormSaveErrors } from '~/lib/forms/form-save-errors'
// Define props
const props = defineProps({
+ hasUnsavedChanges: {
+ type: Boolean,
+ default: null,
+ },
isEdit: {
required: false,
type: Boolean,
@@ -188,6 +195,7 @@ const emit = defineEmits(['mounted', 'on-save', 'openRegister', 'go-back', 'save
// Reactive data
const showFormErrorModal = ref(false)
+const validationRecovery = ref(null)
const validationErrorResponse = ref(null)
const hasBackgroundValidationErrors = ref(false)
const backgroundValidatedFormId = ref(null)
@@ -304,6 +312,7 @@ const displayFormModificationAlert = (responseData) => {
}
const showValidationErrors = () => {
+ formEditorNavbar.value?.closeSettings()
showFormErrorModal.value = true
}
@@ -355,10 +364,15 @@ watch(
const handleFormErrorModalClose = () => {
showFormErrorModal.value = false
-
- nextTick(() => {
+ validationRecovery.value = () => {
document.querySelector('[data-testid="save-form-button"]')?.focus()
- })
+ }
+}
+
+function finishValidationRecovery() {
+ const recover = validationRecovery.value
+ validationRecovery.value = null
+ recover?.()
}
const editInvalidField = ({ fieldId, fieldIndex, targetTab }) => {
@@ -376,16 +390,18 @@ const editInvalidField = ({ fieldId, fieldIndex, targetTab }) => {
}
showFormErrorModal.value = false
- workingFormStore.activeTab = 'build'
- workingFormStore.openSettingsForField(targetIndex, true, targetTab)
+ validationRecovery.value = () => {
+ workingFormStore.activeTab = 'build'
+ workingFormStore.openSettingsForField(targetIndex, true, targetTab)
- nextTick(() => {
- document.getElementById('form-field-settings')?.focus()
- document.getElementById(`block-${properties[targetIndex].id}`)?.scrollIntoView({
- block: 'center',
- behavior: 'auto',
+ nextTick(() => {
+ document.getElementById('form-field-settings')?.focus()
+ document.getElementById(`block-${properties[targetIndex].id}`)?.scrollIntoView({
+ block: 'center',
+ behavior: 'auto',
+ })
})
- })
+ }
}
const editInvalidComputedVariable = ({ variableId, variableIndex }) => {
@@ -399,13 +415,12 @@ const editInvalidComputedVariable = ({ variableId, variableIndex }) => {
}
showFormErrorModal.value = false
-
- nextTick(() => {
+ validationRecovery.value = () => {
formEditorNavbar.value?.openComputedVariable({
variableId: targetVariable.id,
variableIndex: computedVariables.indexOf(targetVariable),
})
- })
+ }
}
const saveForm = () => {
diff --git a/client/components/open/forms/components/FormEditorNavbar.vue b/client/components/open/forms/components/FormEditorNavbar.vue
index 3d6c9d304..5b3e9d0b4 100644
--- a/client/components/open/forms/components/FormEditorNavbar.vue
+++ b/client/components/open/forms/components/FormEditorNavbar.vue
@@ -35,6 +35,9 @@
v-model="settingsModal"
v-model:active-tab="settingsModalActiveTab"
:computed-variable-edit-request="computedVariableEditRequest"
+ :saving="updateFormLoading"
+ :save-label="isEdit ? 'Save and close' : 'Done'"
+ @save="saveSettings"
@close="settingsModal = false"
/>
@@ -90,32 +93,43 @@
</UTooltip>
</TrackClick>
<slot name="before-save" />
- <UTooltip arrow :content="{side: 'bottom'}">
- <template #content>
- <UKbd
- value="meta"
- size="xs"
- />
- <UKbd
- value="s"
- size="xs"
- />
- </template>
- <TrackClick
- name="save_form_click"
+ <div class="flex shrink-0 flex-col items-end">
+ <UTooltip arrow :content="{side: 'bottom'}">
+ <template #content>
+ <UKbd
+ value="meta"
+ size="xs"
+ />
+ <UKbd
+ value="s"
+ size="xs"
+ />
+ </template>
+ <TrackClick
+ name="save_form_click"
+ >
+ <UButton
+ color="primary"
+ class="px-8 md:px-4 py-2"
+ :loading="updateFormLoading"
+ :class="saveButtonClass"
+ data-testid="save-form-button"
+ icon="i-ic-outline-save"
+ @click="emit('save-form')"
+ :label="isEdit || form.visibility !== 'public' ? 'Save Changes' : 'Publish Form'"
+ />
+ </TrackClick>
+ </UTooltip>
+ <span
+ v-if="hasUnsavedChanges !== null"
+ role="status"
+ class="mt-1 text-xs whitespace-nowrap"
+ :class="hasUnsavedChanges ? 'text-amber-700' : 'text-neutral-500'"
+ data-testid="form-save-status"
>
- <UButton
- color="primary"
- class="px-8 md:px-4 py-2"
- :loading="updateFormLoading"
- :class="saveButtonClass"
- data-testid="save-form-button"
- icon="i-ic-outline-save"
- @click="emit('save-form')"
- :label="form.visibility === 'public' ? 'Publish Form' : 'Save Changes'"
- />
- </TrackClick>
- </UTooltip>
+ {{ updateFormLoading ? 'Saving changes…' : hasUnsavedChanges ? 'Unsaved changes' : 'All changes saved' }}
+ </span>
+ </div>
</div>
</div>
</template>
@@ -130,7 +144,15 @@ import { useFeatureFlag } from '~/composables/useFeatureFlag'
const FormSettingsModal = defineAsyncComponent(() => import('~/components/open/forms/components/form-components/FormSettingsModal.vue'))
-defineProps({
+const props = defineProps({
+ isEdit: {
+ type: Boolean,
+ default: false
+ },
+ hasUnsavedChanges: {
+ type: Boolean,
+ default: null
+ },
backButton: {
type: Boolean,
default: true
@@ -160,6 +182,14 @@ const form = computed(() => workingFormStore.content)
const { activeTab } = storeToRefs(workingFormStore)
const settingsModal = ref(false)
+function saveSettings() {
+ if (props.isEdit) {
+ emit('save-form')
+ } else {
+ settingsModal.value = false
+ }
+}
+
const settingsModalActiveTab = ref('general')
const computedVariableEditRequest = ref(null)
let computedVariableEditRequestId = 0
@@ -185,7 +215,11 @@ function openComputedVariableCreator() {
settingsModal.value = true
}
-defineExpose({ openComputedVariable, openComputedVariableCreator })
+function closeSettings() {
+ settingsModal.value = false
+}
+
+defineExpose({ openComputedVariable, openComputedVariableCreator, closeSettings })
const isSelfHosted = computed(() => useFeatureFlag('self_hosted'))
</script>
diff --git a/client/components/open/forms/components/FormFieldsEditor.vue b/client/components/open/forms/components/FormFieldsEditor.vue
index ffe2f1e96..9155406bc 100644
--- a/client/components/open/forms/components/FormFieldsEditor.vue
+++ b/client/components/open/forms/components/FormFieldsEditor.vue
@@ -127,6 +127,7 @@
</template>
<script>
+import { applyEditorFieldDefaults } from '~/composables/forms/initForm.js'
import { VueDraggable } from 'vue-draggable-plus'
import EditableTag from '~/components/app/EditableTag.vue'
import BlockTypeIcon from './BlockTypeIcon.vue'
@@ -172,15 +173,7 @@ export default {
if (!this.form.properties) {
return
}
- this.form.properties = this.form.properties.map((field) => {
- // Add more field properties
- field.placeholder = field.placeholder || null
- field.prefill = field.prefill || null
- field.help = field.help || null
- field.help_position = field.help_position || "below_input"
-
- return field
- })
+ this.form.properties = applyEditorFieldDefaults(this.form.properties)
},
openAddFieldSidebar () {
this.workingFormStore.openAddFieldSidebar(null)
diff --git a/client/components/open/forms/components/form-components/FormErrorModal.vue b/client/components/open/forms/components/form-components/FormErrorModal.vue
index 2b2cea7f3..52898025c 100644
--- a/client/components/open/forms/components/form-components/FormErrorModal.vue
+++ b/client/components/open/forms/components/form-components/FormErrorModal.vue
@@ -3,6 +3,8 @@
v-model:open="isOpen"
:ui="{ content: 'sm:max-w-xl' }"
:title="modalTitle"
+ :content="{ onCloseAutoFocus: (event) => event.preventDefault() }"
+ @after:leave="emit('after:leave')"
>
<template #body>
<div
@@ -195,7 +197,7 @@ const props = defineProps({
},
})
-const emit = defineEmits(['close', 'edit-field', 'edit-computed-variable'])
+const emit = defineEmits(['close', 'edit-field', 'edit-computed-variable', 'after:leave'])
const fieldGroups = computed(() => props.errorSummary?.fieldGroups || [])
const computedVariableGroups = computed(() => props.errorSummary?.computedVariableGroups || [])
diff --git a/client/components/open/forms/components/form-components/FormSettingsModal.vue b/client/components/open/forms/components/form-components/FormSettingsModal.vue
index 33927ab93..01421643c 100644
--- a/client/components/open/forms/components/form-components/FormSettingsModal.vue
+++ b/client/components/open/forms/components/form-components/FormSettingsModal.vue
@@ -2,6 +2,8 @@
<SettingsModal
v-model="isOpen"
v-model:activeTab="activeTab"
+ title="Form settings"
+ :busy="saving"
@close="closeModal"
>
<SettingsModalPage
@@ -60,6 +62,18 @@
<ComputedVariablesTab :edit-request="computedVariableEditRequest" />
</SettingsModalPage>
+ <template #footer>
+ <div class="flex items-center justify-end gap-3">
+ <UButton label="Close" color="neutral" variant="outline" :disabled="saving" @click="closeModal" />
+ <UButton
+ :label="saveLabel"
+ :loading="saving"
+ icon="i-ic-outline-save"
+ data-testid="save-form-settings-button"
+ @click="emit('save')"
+ />
+ </div>
+ </template>
</SettingsModal>
</template>
@@ -75,9 +89,17 @@ const FormCustomCode = defineAsyncComponent(() => import('~/components/open/form
const ComputedVariablesTab = defineAsyncComponent(() => import('~/components/open/forms/components/computed-variables/ComputedVariablesTab.vue'))
const FormAnalyticsSettings = defineAsyncComponent(() => import('~/components/open/forms/components/form-components/FormAnalyticsSettings.vue'))
-const emit = defineEmits(['close', 'update:activeTab'])
+const emit = defineEmits(['close', 'update:activeTab', 'save'])
const props = defineProps({
+ saving: {
+ type: Boolean,
+ default: false
+ },
+ saveLabel: {
+ type: String,
+ default: 'Done'
+ },
modelValue: {
type: Boolean,
default: false
@@ -106,6 +128,7 @@ const activeTab = computed({
// Methods
const closeModal = () => {
+ if (props.saving) return
isOpen.value = false
}
diff --git a/client/components/pages/settings/SettingsModal.vue b/client/components/pages/settings/SettingsModal.vue
index 613252444..6f50db991 100644
--- a/client/components/pages/settings/SettingsModal.vue
+++ b/client/components/pages/settings/SettingsModal.vue
@@ -4,7 +4,8 @@
:ui="{
content: 'max-w-5xl h-[80vh] overflow-hidden',
}"
- title=""
+ :title="title"
+ :dismissible="!busy"
:content="{
onPointerDownOutside: (event) => { if (event.target?.closest('.crisp-client')) {return event.preventDefault()}}
}"
@@ -12,7 +13,7 @@
<template #content>
<div class="flex h-full flex-col sm:flex-row">
<!-- Left Sidebar -->
- <aside class="flex flex-col border-b border-neutral-200 bg-neutral-50 sm:w-56 sm:shrink-0 sm:border-r sm:border-b-0">
+ <aside :inert="busy" class="flex flex-col border-b border-neutral-200 bg-neutral-50 sm:w-56 sm:shrink-0 sm:border-r sm:border-b-0">
<!-- Navigation Menu -->
<nav class="relative p-2 pt-2 sm:flex-1 sm:overflow-y-auto sm:pt-4">
<slot name="nav-top" />
@@ -58,7 +59,7 @@
<!-- Main Content -->
<main class="relative flex flex-1 flex-col overflow-hidden">
<!-- Content Body -->
- <div class="flex-1 overflow-y-auto">
+ <div :inert="busy" class="flex-1 overflow-y-auto">
<div class="p-6">
<!-- Modal pages will register themselves and render here -->
<slot />
@@ -78,6 +79,9 @@
</div>
</div>
</div>
+ <div v-if="$slots.footer" class="shrink-0 border-t border-neutral-200 p-4">
+ <slot name="footer" />
+ </div>
</main>
</div>
</template>
@@ -96,6 +100,14 @@ const emit = defineEmits(['close', 'item-changed', 'update:activeTab'])
const registeredPages = ref([])
const props = defineProps({
+ busy: {
+ type: Boolean,
+ default: false
+ },
+ title: {
+ type: String,
+ default: 'Settings'
+ },
modelValue: {
type: Boolean,
default: false
@@ -299,4 +311,4 @@ provide('unregisterModalPage', unregisterModalPage)
ul::-webkit-scrollbar {
display: none;
}
-</style>
\ No newline at end of file
+</style>
diff --git a/client/composables/forms/initForm.js b/client/composables/forms/initForm.js
index 60a9000be..b09a8b457 100644
--- a/client/composables/forms/initForm.js
+++ b/client/composables/forms/initForm.js
@@ -3,6 +3,31 @@ import { isReadonly } from 'vue'
import { generateUUID } from "../../lib/utils.js"
export const DEFAULT_COLOR = '#3B82F6'
+// Apply these before taking an editor's clean snapshot as well as on mount.
+export function applyEditorFieldDefaults(properties) {
+ return properties.map((field) => {
+ field.placeholder = field.placeholder || null
+ field.prefill = field.prefill || null
+ field.help = field.help || null
+ field.help_position = field.help_position || 'below_input'
+ return field
+ })
+}
+
+// Settings panels add these values on mount. Include them in the clean baseline.
+export function applyEditorSettingsDefaults(formData) {
+ const defaults = {
+ seo_meta: { page_title: null, page_description: null, page_thumbnail: null, page_favicon: null },
+ analytics: { provider: null, tracking_id: null },
+ translations: {},
+ }
+ for (const [key, values] of Object.entries(defaults)) {
+ const current = formData[key]
+ formData[key] = { ...values, ...(current && typeof current === 'object' && !Array.isArray(current) ? current : {}) }
+ }
+ return formData
+}
+
export const initForm = (defaultValue = {}, withDefaultProperties = false) => {
return useForm({
title: "Contact Form",
diff --git a/client/pages/forms/[slug]/edit.vue b/client/pages/forms/[slug]/edit.vue
index 21ddb14e0..d418fa532 100644
--- a/client/pages/forms/[slug]/edit.vue
+++ b/client/pages/forms/[slug]/edit.vue
@@ -5,6 +5,7 @@
v-if="!error"
ref="editor"
:is-edit="true"
+ :has-unsaved-changes="hasUnsavedChanges"
@on-save="formInitialHash = null"
:loading="formsLoading"
/>
@@ -35,7 +36,7 @@
<script setup>
import FormEditor from "~/components/open/forms/components/FormEditor.vue"
-import { setFormDefaults } from "~/composables/forms/initForm.js"
+import { applyEditorFieldDefaults, applyEditorSettingsDefaults, setFormDefaults } from "~/composables/forms/initForm.js"
import { hash } from "~/lib/utils.js"
// Composables
@@ -65,6 +66,7 @@ const errorMessage = computed(() => {
const updatedForm = storeToRefs(workingFormStore).content
const formInitialHash = ref(null)
+const hasUnsavedChanges = computed(() => Boolean(isDirty()))
function isDirty() {
try {
@@ -84,7 +86,9 @@ function initUpdatedForm() {
return
}
- updatedForm.value = useForm(setFormDefaults(form.value))
+ const formData = applyEditorSettingsDefaults(setFormDefaults(form.value))
+ formData.properties = applyEditorFieldDefaults(formData.properties)
+ updatedForm.value = useForm(formData)
if (!updatedForm.value) {
return
}
@@ -108,25 +112,24 @@ watch(
)
onBeforeRouteLeave((to, from, next) => {
- if (isDirty()) {
- if (window.confirm('Changes you made may not be saved. Are you sure want to leave?')) {
- window.onbeforeunload = null
- next()
- } else {
- next(false)
- }
+ if (hasUnsavedChanges.value && !window.confirm('You have unsaved changes. Leave without saving?')) {
+ return next(false)
}
next()
})
-onBeforeMount(() => {
- if (import.meta.client) {
- window.onbeforeunload = () => {
- if (isDirty()) {
- return false
- }
- }
+function warnBeforeUnload(event) {
+ if (hasUnsavedChanges.value) {
+ event.preventDefault()
+ event.returnValue = ''
}
+}
+
+onMounted(() => {
+ window.addEventListener('beforeunload', warnBeforeUnload)
+})
+onBeforeUnmount(() => {
+ window.removeEventListener('beforeunload', warnBeforeUnload)
})
useOpnSeoMeta({
diff --git a/client/test/e2e/editor-save-ux.spec.ts b/client/test/e2e/editor-save-ux.spec.ts
new file mode 100644
index 000000000..8a91acf81
--- /dev/null
+++ b/client/test/e2e/editor-save-ux.spec.ts
@@ -0,0 +1,240 @@
+import { expect, test } from '@playwright/test'
+import { waitForAnonymousApiBudget, waitForAuthenticatedApiBudget } from './api-budget'
+
+test.setTimeout(60_000)
+
+const api = process.env.PLAYWRIGHT_API_BASE_URL || 'http://127.0.0.1:8089'
+let headers: Record<string, string>
+let form: { id: number, slug: string }
+
+test.beforeEach(async ({ page, request }, testInfo) => {
+ await waitForAnonymousApiBudget(request, testInfo)
+ const login = await request.post(`${api}/login`, { data: {
+ email: '[email protected]', password: 'Abcd@1234', remember: false,
+ } })
+ expect(login.ok(), await login.text()).toBeTruthy()
+ const token = (await login.json()).token
+ headers = { Authorization: `Bearer ${token}`, Accept: 'application/json' }
+ await waitForAuthenticatedApiBudget(request, testInfo, headers)
+ const workspaces = await request.get(`${api}/open/workspaces`, { headers })
+ expect(workspaces.ok()).toBeTruthy()
+ const workspaceId = (await workspaces.json())[0].id
+ const response = await request.post(`${api}/open/forms`, { headers, data: {
+ title: `Save UX ${Date.now()}`, workspace_id: workspaceId, visibility: 'public',
+ properties: [{ id: 'answer', name: 'Answer', type: 'text' }],
+ 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: {},
+ } })
+ expect(response.ok(), await response.text()).toBeTruthy()
+ form = (await response.json()).form
+ await page.context().addCookies([{ name: 'opnform_token', value: token, url: testInfo.project.use.baseURL as string }])
+})
+
+test.afterEach(async ({ request }) => {
+ if (form) {
+ const removed = await request.delete(`${api}/open/forms/${form.id}`, { headers })
+ expect(removed.ok(), await removed.text()).toBeTruthy()
+ }
+})
+
+for (const [visibility, label] of [
+ ['draft', 'Draft - not publicly accessible'],
+ ['closed', "Closed - won't accept new submissions"],
+ ['public', 'Published'],
+]) {
+ test(`settings save ${visibility} in one click and persist after reload`, async ({ page, request }) => {
+ await page.goto(`/forms/${form.slug}/edit`)
+ await expect(page.getByTestId('form-save-status')).toHaveText('All changes saved', { timeout: 15_000 })
+ await expect(page.getByTestId('save-form-button')).toHaveText('Save Changes')
+ await page.getByRole('button', { name: 'Settings', exact: true }).click()
+ const settings = page.getByRole('dialog', { name: 'Form settings', exact: true })
+ await expect(settings).toBeVisible()
+ const title = `Saved ${visibility} ${Date.now()}`
+ await settings.getByRole('textbox', { name: 'Form Name', exact: true }).fill(title)
+ await settings.getByRole('radio', { name: label, exact: true }).check()
+ let saves = 0
+ page.on('request', request => {
+ if (request.method() === 'PUT' && request.url() === `${api}/open/forms/${form.id}`) saves++
+ })
+ await settings.getByRole('button', { name: 'Save and close', exact: true }).click()
+ await expect(page).toHaveURL(`/forms/${form.slug}/show/share`)
+ expect(saves).toBe(1)
+ await page.reload()
+ await expect(page.getByRole('heading', { name: title, exact: true })).toBeVisible()
+ const stored = await request.get(`${api}/open/forms/${form.id}`, { headers })
+ expect(stored.ok()).toBeTruthy()
+ expect(await stored.json()).toMatchObject({ title, visibility })
+ })
+}
+
+test('design status follows edits and reversions; cancelling departure keeps the changes', async ({ page, request }) => {
+ await page.setViewportSize({ width: 1024, height: 768 })
+ await page.goto(`/forms/${form.slug}/edit`)
+ const status = page.getByTestId('form-save-status')
+ await expect(status).toHaveText('All changes saved', { timeout: 15_000 })
+ await page.getByRole('tab', { name: 'Design', exact: true }).click()
+ const uppercase = page.getByRole('switch', { name: 'Uppercase Input Labels', exact: true })
+ await uppercase.check()
+ await expect(status).toHaveText('Unsaved changes')
+ await expect(status).toBeInViewport({ ratio: 1 })
+ await expect(page.getByTestId('save-form-button')).toBeInViewport({ ratio: 1 })
+ await uppercase.uncheck()
+ await expect(status).toHaveText('All changes saved', { timeout: 15_000 })
+ await uppercase.check()
+ await expect(status).toHaveText('Unsaved changes')
+ let confirmations = 0
+ page.once('dialog', async dialog => {
+ confirmations++
+ expect(dialog.message()).toBe('You have unsaved changes. Leave without saving?')
+ await dialog.dismiss()
+ })
+ await page.locator('#form-editor a[href="#"]').first().click()
+ await expect(page).toHaveURL(`/forms/${form.slug}/edit`)
+ expect(confirmations).toBe(1)
+ await expect(uppercase).toBeChecked()
+ await expect(status).toHaveText('Unsaved changes')
+ const storedBefore = await request.get(`${api}/open/forms/${form.id}`, { headers })
+ expect((await storedBefore.json()).uppercase_labels).toBe(false)
+ await page.getByTestId('save-form-button').click()
+ await expect(page).toHaveURL(`/forms/${form.slug}/show/share`)
+ // A saved form must not leave a stale beforeunload warning on its next page.
+ page.on('dialog', async dialog => {
+ confirmations++
+ await dialog.dismiss()
+ })
+ await page.reload()
+ expect(confirmations).toBe(1)
+ await page.getByRole('link', { name: 'Edit form', exact: true }).click()
+ await page.getByRole('tab', { name: 'Design', exact: true }).click()
+ await expect(uppercase).toBeChecked()
+ await expect(status).toHaveText('All changes saved', { timeout: 15_000 })
+})
+
+test('settings keep edits after a failed save and allow retry', async ({ page }) => {
+ await page.goto(`/forms/${form.slug}/edit`)
+ await expect(page.getByTestId('form-save-status')).toHaveText('All changes saved', { timeout: 15_000 })
+ await page.getByRole('button', { name: 'Settings', exact: true }).click()
+ const settings = page.getByRole('dialog', { name: 'Form settings', exact: true })
+ await settings.getByRole('textbox', { name: 'Form Name', exact: true }).fill('Retry these settings')
+ let release: () => void = () => {}
+ const pending = new Promise<void>(resolve => { release = resolve })
+ const endpoint = `${api}/open/forms/${form.id}`
+ await page.route(endpoint, async route => {
+ if (route.request().method() !== 'PUT') return route.continue()
+ await pending
+ await route.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ message: 'Local test failure' }) })
+ })
+ try {
+ await settings.getByRole('button', { name: 'Save and close', exact: true }).click()
+ await expect(page.getByTestId('form-save-status')).toHaveText('Saving changes…')
+ await expect(settings.getByTestId('save-form-settings-button')).toBeDisabled()
+ } finally {
+ release()
+ }
+ await expect(page.getByTestId('form-save-status')).toHaveText('Unsaved changes')
+ await expect(settings).toBeVisible()
+ await expect(settings.getByRole('textbox', { name: 'Form Name', exact: true })).toHaveValue('Retry these settings')
+ await expect(settings.getByRole('button', { name: 'Save and close', exact: true })).toBeEnabled()
+ await page.unroute(endpoint)
+ await settings.getByRole('button', { name: 'Save and close', exact: true }).click()
+ await expect(page).toHaveURL(`/forms/${form.slug}/show/share`)
+ await expect(page.getByRole('heading', { name: 'Retry these settings', exact: true })).toBeVisible()
+})
+
+test('new form settings apply with Done without creating a form', async ({ page }) => {
+ await page.goto('/forms/create')
+ await page.getByTestId('form-style-classic').click()
+ await page.getByTestId('form-base-simple-contact').click()
+ await expect(page.locator('#form-editor')).toBeVisible()
+ let creates = 0
+ page.on('request', request => {
+ if (request.method() === 'POST' && request.url() === `${api}/open/forms`) creates++
+ })
+ await page.getByRole('button', { name: 'Settings', exact: true }).click()
+ const settings = page.getByRole('dialog', { name: 'Form settings', exact: true })
+ await settings.getByRole('textbox', { name: 'Form Name', exact: true }).fill('Unpublished new form')
+ await settings.getByRole('button', { name: 'Done', exact: true }).click()
+ await expect(settings).not.toBeVisible()
+ await expect(page.locator('#form-editor-title')).toHaveText('Unpublished new form')
+ await expect(page).toHaveURL('/forms/create')
+ expect(creates).toBe(0)
+})
+
+test('settings cannot change or close while a successful save is pending', async ({ page, request }) => {
+ await page.goto(`/forms/${form.slug}/edit`)
+ await expect(page.getByTestId('form-save-status')).toHaveText('All changes saved', { timeout: 15_000 })
+ await page.getByRole('button', { name: 'Settings', exact: true }).click()
+ const settings = page.getByRole('dialog', { name: 'Form settings', exact: true })
+ const title = settings.locator('input#title')
+ await title.fill('Submitted title')
+ let release: () => void = () => {}
+ const pending = new Promise<void>(resolve => { release = resolve })
+ await page.route(`${api}/open/forms/${form.id}`, async route => {
+ if (route.request().method() === 'PUT') await pending
+ await route.continue()
+ })
+ try {
+ await settings.getByRole('button', { name: 'Save and close', exact: true }).click()
+ await expect(page.getByTestId('form-save-status')).toHaveText('Saving changes…')
+ await expect(settings.getByRole('button', { name: 'Close', exact: true })).toBeDisabled()
+ // Inert content ignores both pointer focus and subsequent keyboard input.
+ await title.click({ force: true })
+ await page.keyboard.type(' should not be lost')
+ await expect(title).toHaveValue('Submitted title')
+ await expect(title).not.toBeFocused()
+ await page.keyboard.press('Escape')
+ await expect(settings).toBeVisible()
+ } finally {
+ release()
+ }
+ await expect(page).toHaveURL(`/forms/${form.slug}/show/share`)
+ const stored = await request.get(`${api}/open/forms/${form.id}`, { headers })
+ expect(stored.ok()).toBeTruthy()
+ expect((await stored.json()).title).toBe('Submitted title')
+})
+
+test('validation errors from Settings lead to an accessible field editor', async ({ page }) => {
+ await page.goto(`/forms/${form.slug}/edit`)
+ await expect(page.getByTestId('form-save-status')).toHaveText('All changes saved', { timeout: 15_000 })
+ await page.getByRole('button', { name: 'Settings', exact: true }).click()
+ const settings = page.getByRole('dialog', { name: 'Form settings', exact: true })
+ await settings.getByRole('textbox', { name: 'Form Name', exact: true }).fill('Keep pending title')
+ await page.route(`${api}/open/forms/${form.id}`, async route => {
+ if (route.request().method() !== 'PUT') return route.continue()
+ await route.fulfill({ status: 422, contentType: 'application/json', body: JSON.stringify({
+ message: 'The name is invalid.', errors: { 'properties.0.name': ['The name is invalid.'] },
+ }) })
+ })
+ await settings.getByRole('button', { name: 'Save and close', exact: true }).click()
+ await expect(page.getByTestId('form-save-error-modal')).toBeVisible()
+ await page.getByTestId('edit-form-field-answer').click()
+ await expect(settings).not.toBeVisible()
+ await expect(page.getByTestId('form-save-error-modal')).not.toBeVisible()
+ const fieldSettings = page.getByTestId('form-field-settings')
+ await expect(fieldSettings).toBeVisible()
+ await expect(fieldSettings).toBeFocused()
+ await expect(page.getByTestId('form-save-status')).toHaveText('Unsaved changes')
+ await expect(page.locator('#form-editor-title')).toHaveText('Keep pending title')
+})
+
+test('visiting every Settings tab without edits keeps the form clean', async ({ page }) => {
+ await page.goto(`/forms/${form.slug}/edit`)
+ const status = page.getByTestId('form-save-status')
+ await expect(status).toHaveText('All changes saved', { timeout: 15_000 })
+ await page.getByRole('button', { name: 'Settings', exact: true }).click()
+ const settings = page.getByRole('dialog', { name: 'Form settings', exact: true })
+ for (const tab of ['General', 'Submission Settings', 'Security & Access', 'SEO & Social Sharing', 'Analytics', 'Custom Code', 'Variables']) {
+ await settings.getByRole('button', { name: tab, exact: true }).click()
+ await expect(settings.getByRole('heading', { name: new RegExp(`^${tab}`) }).first()).toBeVisible()
+ await expect(status).toHaveText('All changes saved')
+ }
+ await settings.getByRole('button', { name: 'Close', exact: true }).click()
+ await expect(status).toHaveText('All changes saved')
+ let confirmations = 0
+ page.on('dialog', async dialog => { confirmations++; await dialog.dismiss() })
+ await page.locator('#form-editor a[href="#"]').first().click()
+ await expect(page).toHaveURL(`/forms/${form.slug}/show/submissions`)
+ expect(confirmations).toBe(0)
+})
diff --git a/client/test/unit/init-form-defaults.test.ts b/client/test/unit/init-form-defaults.test.ts
index dd550cfc9..2b0ef61cd 100644
--- a/client/test/unit/init-form-defaults.test.ts
+++ b/client/test/unit/init-form-defaults.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { setFormDefaults } from '../../composables/forms/initForm.js'
+import { applyEditorFieldDefaults, applyEditorSettingsDefaults, setFormDefaults } from '../../composables/forms/initForm.js'
describe('setFormDefaults', () => {
it('does not invent respondent-facing field labels', () => {
@@ -30,3 +30,38 @@ describe('setFormDefaults', () => {
expect(setFormDefaults({ properties: 'malformed' }).properties).toEqual([])
})
})
+
+describe('editor field initialization', () => {
+ it('does not change a clean snapshot when fields mount', () => {
+ const fields = applyEditorFieldDefaults([{ id: 'answer', name: 'Answer', type: 'text' }])
+ const snapshot = JSON.stringify(fields)
+
+ expect(fields[0]).toMatchObject({ placeholder: null, prefill: null, help: null, help_position: 'below_input' })
+ expect(JSON.stringify(applyEditorFieldDefaults(fields))).toBe(snapshot)
+ })
+
+ it('preserves configured field options', () => {
+ const fields = [{ id: 'answer', placeholder: 'Type here', prefill: 'Example', help: 'Required details', help_position: 'above_input' }]
+ expect(applyEditorFieldDefaults(structuredClone(fields))).toEqual(fields)
+ })
+})
+
+
+describe('editor settings initialization', () => {
+ it.each([undefined, null, [], {}])('normalizes empty settings before taking a clean snapshot (%j)', (empty) => {
+ const form = applyEditorSettingsDefaults({ seo_meta: empty, analytics: empty, translations: empty })
+ expect(form.seo_meta).toEqual({ page_title: null, page_description: null, page_thumbnail: null, page_favicon: null })
+ expect(form.analytics).toEqual({ provider: null, tracking_id: null })
+ expect(form.translations).toEqual({})
+ })
+
+ it('preserves configured settings and is stable on repeated initialization', () => {
+ const configured = { seo_meta: { page_title: 'My form', extra: true }, analytics: { provider: 'gtm', tracking_id: 'GTM-TEST' }, translations: { focused_next_button_text: 'Continue' } }
+ const form = applyEditorSettingsDefaults(structuredClone(configured))
+ expect(form.seo_meta).toMatchObject(configured.seo_meta)
+ expect(form.analytics).toEqual(configured.analytics)
+ expect(form.translations).toEqual(configured.translations)
+ const snapshot = JSON.stringify(form)
+ expect(JSON.stringify(applyEditorSettingsDefaults(form))).toBe(snapshot)
+ })
+})