Beautiful Open-Source Form Builder
ESC-855 - enhance form submission handling and storage management (#1082)
Chirag Chhatrala1595cd478839
diff --git a/client/lib/forms/composables/useFormManager.js b/client/lib/forms/composables/useFormManager.jsindex bea55fd5e..9f7807623 100644--- a/client/lib/forms/composables/useFormManager.js+++ b/client/lib/forms/composables/useFormManager.js@@ -232,6 +232,15 @@ export function useFormManager(initialFormConfig, initialMode = FormMode.LIVE, ostate.isProcessing = truetry {+ // Capture submission hash BEFORE stopSync: stopSync clears the in-memory hash map.+ // When auto_save is off, the hash is only in memory (not localStorage), so reading+ // after stopSync would lose it and the server would create a new completed row+ // instead of upgrading the partial submission.+ let submissionHash = null+ if (!import.meta.server && toValue(config).enable_partial_submissions && strategy.value.submission.enablePartialSubmissions) {+ submissionHash = partialSubmissionService.getSubmissionHash()+ }+// Stop partial submission sync during submission if enabled// Use skipFinalSync: true to prevent a race condition where the partial submission// (with is_partial: true) arrives at the server after the final submission,@@ -262,14 +271,8 @@ export function useFormManager(initialFormConfig, initialMode = FormMode.LIVE, o}}}-- // 3. Get submission hash from partialSubmission if enabled- let submissionHash = null- if (!import.meta.server && toValue(config).enable_partial_submissions && strategy.value.submission.enablePartialSubmissions) {- submissionHash = partialSubmissionService.getSubmissionHash()- }- // 4. Perform Submission (using submission composable)+ // 3. Perform Submission (using submission composable)const submissionResult = await submission.submit({formModeStrategy: strategy.value,completionTime: completionTime,diff --git a/client/lib/forms/composables/usePendingSubmission.js b/client/lib/forms/composables/usePendingSubmission.jsindex 8414fa77b..b1980cbd4 100644--- a/client/lib/forms/composables/usePendingSubmission.js+++ b/client/lib/forms/composables/usePendingSubmission.js@@ -2,6 +2,22 @@ import { hash } from "~/lib/utils.js"import { useStorage, watchThrottled } from "@vueuse/core"import { computed, toValue } from 'vue'+const PENDING_SUBMISSION_METADATA_KEYS = ['submission_hash']++function pickPendingSubmissionMetadata(value) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ return {}+ }++ return PENDING_SUBMISSION_METADATA_KEYS.reduce((metadata, key) => {+ if (Object.prototype.hasOwnProperty.call(value, key)) {+ metadata[key] = value[key]+ }++ return metadata+ }, {})+}+/*** Composable for managing pending form submission data and timer in localStorage.* Includes throttled auto-saving of form data.@@ -28,9 +44,15 @@ export function usePendingSubmission(formConfig, formDataRef) {return config.value?.auto_save ?? false})+ // Draft + submission_hash share the same storage key; allow reads/writes when either+ // auto-save or partial submissions need metadata (hash) persisted without full draft sync.+ const canUsePendingStorage = computed(() => {+ return enabled.value || (config.value?.enable_partial_submissions ?? false)+ })+// Internal function to save data to localStorageconst saveData = (value) => {- if (import.meta.server || !enabled.value || !formPendingSubmissionKey.value) return+ if (import.meta.server || !canUsePendingStorage.value || !formPendingSubmissionKey.value) returntry {useStorage(formPendingSubmissionKey.value).value =value === null ? null : JSON.stringify(value)@@ -41,7 +63,7 @@ export function usePendingSubmission(formConfig, formDataRef) {// Internal function to retrieve data from localStorageconst retrieveData = (defaultValue = {}) => {- if (import.meta.server || !enabled.value || !formPendingSubmissionKey.value) return defaultValue+ if (import.meta.server || !canUsePendingStorage.value || !formPendingSubmissionKey.value) return defaultValuetry {const storageValue = useStorage(formPendingSubmissionKey.value).valuereturn storageValue ? JSON.parse(storageValue) : defaultValue@@ -53,13 +75,20 @@ export function usePendingSubmission(formConfig, formDataRef) {}}+ const mergeStoredMetadata = (value = {}) => {+ return {+ ...value,+ ...pickPendingSubmissionMetadata(retrieveData({}))+ }+ }+// Watch formDataRef with throttlingwatchThrottled(formDataRef,(newData) => {- // Only save if enabled and on client+ // Only persist full draft when auto-save is on (not only partial-submission metadata)if (import.meta.client && enabled.value) {- saveData(newData)+ saveData(mergeStoredMetadata(newData))}},{ deep: true, throttle: 1000 } // Throttle saving to once per second@@ -78,7 +107,7 @@ export function usePendingSubmission(formConfig, formDataRef) {}const setSubmissionHash = (hash) => {- if (!enabled.value) return+ if (!canUsePendingStorage.value) returnconst currentData = retrieveData()saveData({...currentData,diff --git a/client/test/nuxt/usePendingSubmission.spec.ts b/client/test/nuxt/usePendingSubmission.spec.tsnew file mode 100644index 000000000..e1a6662dc--- /dev/null+++ b/client/test/nuxt/usePendingSubmission.spec.ts@@ -0,0 +1,96 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { ref, computed, nextTick } 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')++ return {+ useStorage: (key, defaultValue = null) => {+ if (!storageRefs.has(key)) {+ storageRefs.set(key, ref(defaultValue))+ }++ return storageRefs.get(key)+ },+ watchThrottled: (source, callback, options = {}) => {+ return watch(source, (value, oldValue, onCleanup) => {+ callback(value, oldValue, onCleanup)+ }, options)+ }+ }+})++describe('usePendingSubmission', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ storageRefs.clear()+ window.history.replaceState({}, '', '/forms/test')+ })++ afterEach(() => {+ vi.useRealTimers()+ storageRefs.clear()+ })++ function createPendingSubmission(configOverrides = {}, initialFormData = {}) {+ const formConfig = ref({+ form_pending_submission_key: 'pending-submission-test',+ auto_save: false,+ enable_partial_submissions: false,+ ...configOverrides+ })+ const formData = ref(initialFormData)+ const pendingSubmission = usePendingSubmission(formConfig, computed(() => formData.value))++ return {+ formData,+ pendingSubmission+ }+ }++ async function flushAutosave() {+ await nextTick()+ await nextTick()+ }++ it('stores submission hash when only partial submissions are enabled', () => {+ const { pendingSubmission } = createPendingSubmission({+ auto_save: false,+ enable_partial_submissions: true+ })++ pendingSubmission.setSubmissionHash('submission-hash-1')++ expect(pendingSubmission.getSubmissionHash()).toBe('submission-hash-1')+ expect(pendingSubmission.get()).toEqual({+ submission_hash: 'submission-hash-1'+ })+ })++ it('preserves submission hash when autosave updates the stored draft', async () => {+ const { formData, pendingSubmission } = createPendingSubmission({+ auto_save: true,+ enable_partial_submissions: true+ }, {+ name: 'Initial value'+ })++ pendingSubmission.setSubmissionHash('submission-hash-2')+ formData.value = {+ name: 'Updated value'+ }++ await flushAutosave()++ expect(pendingSubmission.get()).toEqual({+ name: 'Updated value',+ submission_hash: 'submission-hash-2'+ })+ expect(pendingSubmission.getSubmissionHash()).toBe('submission-hash-2')+ })+})