Refactor form rendering (#747)

* Update Dependencies and Refactor Form Components

- Upgraded various Sentry-related packages in `package-lock.json` to version 9.15.0, ensuring compatibility with the latest features and improvements.
- Refactored `FormProgressbar.vue` to utilize `config` for color and visibility settings instead of `form`, enhancing flexibility in form management.
- Removed the `FormTimer.vue` component as it was deemed unnecessary, streamlining the form component structure.
- Updated `OpenCompleteForm.vue` and `OpenForm.vue` to integrate `formManager`, improving the overall management of form states and properties.
- Enhanced `UrlFormPrefill.vue` to utilize `formManager` for better handling of pre-filled URL generation.

These changes aim to improve the maintainability and performance of the form components while ensuring they leverage the latest dependency updates.

* Refactor Form Components to Utilize Composables and Improve State Management

- Updated `FormProgressbar.vue` to access `config.value` and `data.value` for better reactivity.
- Refactored `OpenCompleteForm.vue` to use `useFormManager` for managing form state, enhancing clarity and maintainability.
- Modified `OpenForm.vue` to leverage `structure.value` and `config.value`, improving the handling of form properties and structure.
- Enhanced `UrlFormPrefill.vue` to initialize `useFormManager` within the setup function, streamlining form management.
- Updated `FormManager.js` and `FormStructureService.js` to improve validation logic and state management, ensuring better performance and reliability.

These changes aim to enhance the overall maintainability and performance of the form components by leveraging composables for state management and improving the reactivity of form properties.

* Refactor Form Components to Enhance State Management and Structure

- Updated `FormProgressbar.vue` to utilize `props.formManager?.config` and `structureService` for improved reactivity and data handling.
- Refactored `OpenCompleteForm.vue` to initialize `formManager` outside of `onMounted`, enhancing SSR compatibility and clarity in form state management.
- Modified `OpenForm.vue` to leverage `formManager.form` for data binding, streamlining the handling of form properties.
- Updated `OpenFormField.vue` to utilize `formManager` directly for field logic checks, improving maintainability and consistency.
- Removed obsolete `FormManager.js`, `FormInitializationService.js`, `FormPaymentService.js`, `FormStructureService.js`, `FormSubmissionService.js`, and `FormTimerService.js` files to simplify the codebase and reduce complexity.

These changes aim to enhance the maintainability and performance of the form components by leveraging composables for state management and improving the reactivity of form properties.

* Enhance OpenCompleteForm and OpenForm Components with Auto-Submit and State Management Improvements

- Updated `OpenCompleteForm.vue` to include an auto-submit feature that triggers form submission when the `auto_submit` parameter is present in the URL. This improves user experience by streamlining the submission process.
- Refactored `OpenForm.vue` to remove the loader display logic, simplifying the component structure and enhancing clarity.
- Enhanced `pendingSubmission.js` to include a `clear` method for better management of pending submissions.
- Modified `Form.js` to ensure that the submission payload correctly merges additional data, improving the robustness of form submissions.
- Updated `useFormInitialization.js` to handle pending submissions and URL parameters more effectively, ensuring a smoother user experience.

These changes aim to improve the overall functionality and maintainability of the form components by enhancing state management and user interaction capabilities.

* Enhance Partial Submission Functionality and Sync Mechanism

- Updated `usePartialSubmission.js` to improve the synchronization mechanism by increasing the debounce time from 1 second to 2 seconds, reducing the frequency of sync operations.
- Introduced a new `syncImmediately` function to allow immediate synchronization during critical events such as page unload, enhancing data reliability.
- Refactored the `syncToServer` function to handle computed ref patterns for form data more effectively, ensuring accurate data submission.
- Modified event handlers to utilize the new immediate sync functionality, improving responsiveness during visibility changes and window blur events.
- Enhanced the `stopSync` function to perform a final sync before stopping, ensuring no data is lost during component unmounting.

These changes aim to improve the reliability and performance of partial submissions, ensuring that user data is consistently synchronized with the server during critical interactions.

* Refactor OpenFormField Component to Use Composition API and Enhance Field Logic

- Converted `OpenFormField.vue` to utilize the Composition API with `<script setup>`, improving readability and maintainability.
- Defined props using `defineProps` for better type safety and clarity.
- Refactored computed properties and methods to leverage the new setup structure, enhancing performance and organization.
- Updated `FormFieldEdit.vue` to ensure the structure service is used for setting the page for the selected field, improving navigation consistency.
- Enhanced `useFormStructure.js` with additional validation for field indices and introduced a new `setPageForField` method to manage page navigation more effectively.
- Modified `working_form.js` to streamline the management of the current page index and ensure proper integration with the structure service.

These changes aim to improve the overall structure and functionality of the form components, enhancing user experience and maintainability.

* Enhance Captcha Handling and Refactor OpenForm Component

- Added error handling for resetting hCaptcha and reCAPTCHA in `HCaptchaV2.vue` and `RecaptchaV2.vue`, improving user experience by providing fallback mechanisms when the reset fails.
- Refactored `OpenForm.vue` to replace the `CaptchaInput` component with `CaptchaWrapper`, streamlining the captcha integration and enhancing maintainability.
- Removed obsolete captcha registration logic from `useFormManager.js` and `useFormValidation.js`, simplifying the form management process and improving code clarity.

These changes aim to improve the reliability and user experience of captcha handling within the form components, ensuring smoother interactions and better error management.

* Refactor PaymentInput Component to Enhance Stripe Elements Integration

- Replaced the `useStripeElements` composable with a new `createStripeElements` function, allowing for lazy initialization of Stripe elements based on provided props.
- Introduced a local instance for Stripe elements, improving fallback handling when payment data is not available.
- Updated computed properties to ensure proper access to Stripe state and methods, enhancing reliability in payment processing.
- Modified the `CaptchaWrapper` component to remove the dark mode prop, simplifying its interface.
- Refactored `OpenCompleteForm`, `OpenForm`, and `OpenFormField` components to derive theme and dark mode settings directly from `formManager`, improving consistency across form components.

These changes aim to streamline the integration of Stripe elements, enhance maintainability, and improve the overall user experience in payment processing within the form components.

* Enhance Payment Input and Form Components for Improved Stripe Integration

- Updated the `PaymentInput.client.vue` component to provide more informative messages during payment preview, including detailed error messages for missing configurations.
- Refactored the handling of Stripe elements to ensure proper initialization and state management, improving reliability in payment processing.
- Enhanced the `OpenCompleteForm.vue` and `OpenFormField.vue` components to streamline payment data retrieval and submission processes.
- Improved error handling in `OpenCompleteForm.vue` to provide clearer feedback on submission issues.
- Refactored `useStripeElements.js` to support lazy initialization of Stripe elements with an optional account ID, enhancing flexibility in payment configurations.

These changes aim to improve the user experience during payment processing by providing clearer feedback and ensuring robust integration with Stripe elements.

* Refactor FormPaymentController and Update Payment Intent Route

- Updated the `FormPaymentController` to utilize `CreatePaymentIntentRequest` for improved request validation and handling.
- Changed the `createIntent` method to accept a POST request instead of GET, aligning with RESTful practices for creating resources.
- Enhanced the payment intent creation logic to use a description from the payment block if available, improving clarity in payment processing.
- Modified the `useFormPayment` composable to reflect the change to a POST request, ensuring proper API interaction and logging.

These changes aim to enhance the payment processing flow by improving request handling and aligning with best practices for API design.

* Refactor UrlFormPrefill Component to Utilize Composition API

- Converted `UrlFormPrefill.vue` to use the Composition API with `<script setup>`, enhancing readability and maintainability.
- Defined props using `defineProps` for better type safety and clarity.
- Refactored the initialization of `formManager` to streamline setup and improve logging during form management.
- Updated the URL generation method to utilize reactive references, ensuring better state management and performance.
- Removed obsolete props and methods, simplifying the component structure.

These changes aim to improve the overall structure and functionality of the `UrlFormPrefill` component, enhancing user experience and maintainability.

* Enhance OpenCompleteForm and FormManager with Improved State Management and Debugging

- Added `workingFormStore` to `OpenCompleteForm.vue` for better integration with the working form state.
- Introduced a watcher in `OpenCompleteForm.vue` to share the structure service with the working form store when in admin edit context, enhancing form management capabilities.
- Updated `useFormManager.js` to include a watcher for `currentPage`, improving debugging by logging page changes.
- Modified payment processing logic in `useFormManager.js` to conditionally skip payment validation in non-LIVE modes, enhancing flexibility during development.
- Refactored `useFormStructure.js` to eliminate unnecessary calls to `toValue`, improving performance and clarity in state management.
- Adjusted `useFormValidation.js` to directly access `managerState.currentPage`, streamlining error handling during form validation.

These changes aim to improve the overall functionality and maintainability of the form components by enhancing state management, debugging capabilities, and flexibility in payment processing.

* Refactor Form Components for Improved Logic and State Management

- Updated `OpenForm.vue` to simplify the conditional rendering of the previous button by removing the loading state check, enhancing clarity in button visibility logic.
- Refactored `useFormInitialization.js` to streamline the `updateSpecialFields` function by removing the fields parameter and directly iterating over `formConfig.value.properties`, improving code readability and maintainability.
- Modified `useFormManager.js` to eliminate the passing of fields in the initialization options, simplifying the initialization process.
- Enhanced `useFormPayment.js` to check for existing payment intent IDs directly in the form data, improving the payment processing logic and reducing redundant checks.
- Updated `useFormStructure.js` to include a computed property for `currentPage`, enhancing the state management of the form structure.
- Refactored `working_form.js` to replace the structure service's current page access, improving the integration with the form state.

These changes aim to enhance the overall functionality and maintainability of the form components by improving state management and simplifying logic across various form-related files.

* Refactor Form Components and Improve Submission Logic

- Updated `OpenCompleteForm.vue` to enhance the submission logic by directly using `submissionId` from the variable instead of the route query, improving clarity and reducing dependency on route parameters.
- Modified `triggerSubmit` function in `OpenCompleteForm.vue` to streamline the handling of submission results, ensuring that `submittedData` is set directly from the result and simplifying the conditional checks for `submission_id` and `is_first_submission`.
- Removed the `pendingSubmission.js` file as it was no longer needed, consolidating the submission handling logic within the relevant components and composables.
- Enhanced `usePartialSubmission.js` to improve the management of submission hashes and ensure that the service integrates seamlessly with the new structure, prioritizing local storage for hash retrieval.
- Updated `useFormInitialization.js` to improve error handling and ensure that the form resets correctly when loading submissions fails, enhancing user experience.
- Refactored `useFormManager.js` to instantiate the new `usePendingSubmission` service, ensuring that local storage handling is properly integrated into the form management process.

These changes aim to improve the overall functionality, maintainability, and user experience of the form components by streamlining submission logic and enhancing state management.

* Refactor FormProgressbar Component for Improved Logic and Clarity

- Updated the `FormProgressbar.vue` component to simplify the condition for displaying the progress bar by directly using the `showProgressBar` computed property instead of accessing it through the `config` object.
- Refactored the computed properties to ensure they directly reference the necessary values from `formManager`, enhancing clarity and maintainability.
- Modified the logic for calculating progress to utilize `config.value?.properties` instead of `structureService`, streamlining the progress calculation process.

These changes aim to enhance the overall functionality and maintainability of the `FormProgressbar` component by improving the clarity of the progress display logic and ensuring accurate progress calculations.

* Refactor OpenCompleteForm and Index Page for Improved Logic and Clarity

- Updated `OpenCompleteForm.vue` to remove unnecessary margin from the password protected message, enhancing the visual layout.
- Added `addPasswordError` function to `defineExpose` in `OpenCompleteForm.vue`, allowing better error handling for password validation.
- Refactored the usage of the translation function in `index.vue` to destructure `t` from `useI18n`, improving code clarity and consistency.

These changes aim to enhance the overall functionality and maintainability of the form components by streamlining error handling and improving the clarity of the code structure.

* Enhance Form Submission Logic and Validation Rules

- Updated `PublicFormController.php` to dispatch the job for handling form submissions asynchronously, improving performance and responsiveness.
- Modified `AnswerFormRequest.php` to add validation rules for `completion_time` and make `submission_id` nullable, enhancing data integrity and flexibility.
- Added debugging output in `StoreFormSubmissionJob.php` to log form data and completion time, aiding in troubleshooting and monitoring.

These changes aim to improve the overall functionality and maintainability of the form submission process by optimizing job handling and enhancing validation mechanisms.

* Update ESLint Configuration and Add Vue Plugin

- Modified `.eslintrc.cjs` to ensure proper formatting by removing an unnecessary trailing comma.
- Updated `package.json` and `package-lock.json` to include `eslint-plugin-vue` version 10.1.0, enhancing linting capabilities for Vue components.

These changes aim to improve code quality and maintainability by ensuring consistent linting rules and support for Vue-specific linting features.

* Enhance User Management Tests and Form Components

- Updated `UserManagementTest.php` to include validation for Google reCAPTCHA by adding the `g-recaptcha-response` parameter in registration tests, ensuring comprehensive coverage of user registration scenarios.
- Modified `FormPaymentTest.php` to change the HTTP method from GET to POST for creating payment intents, aligning with RESTful practices and improving the accuracy of test cases.
- Enhanced `FlatSelectInput.vue` to support slot-based rendering for selected options and options, improving flexibility in how options are displayed and selected.
- Refactored `OpenCompleteForm.vue` to correct indentation in the form submission logic, enhancing code readability.
- Updated `FormSubmissionSettings.vue` to replace the `select-input` component with `flat-select-input`, improving consistency in form component usage.
- Enhanced `useFormManager.js` to add logging for form submissions and handle postMessage communication for iframe integration, improving debugging and integration capabilities.

These changes aim to improve the robustness of the testing suite and enhance the functionality and maintainability of form components by ensuring proper validation and consistent component usage.

* Refactor ESLint Configuration and Improve Error Handling in Components

- Deleted the obsolete `.eslintrc.cjs` file to streamline ESLint configuration management.
- Updated `eslint.config.cjs` to include ignores for `.nuxt/**`, `node_modules/**`, and `dist/**`, enhancing linting efficiency.
- Refactored error handling in various components (e.g., `DateInput.vue`, `FlatSelectInput.vue`, `CaptchaInput.vue`, etc.) by removing the error variable in catch blocks, simplifying the code and maintaining functionality.
- Improved the logic in `FormBlockLogicEditor.vue` to check for non-empty logic objects, enhancing validation accuracy.

These changes aim to improve code quality and maintainability by optimizing ESLint configurations and enhancing error handling across components.

* Fix Logic in useFormInitialization for Matrix Field Prefill Handling

- Updated the `updateSpecialFields` function in `useFormInitialization.js` to correct the logic for handling matrix fields. The condition now checks the form directly instead of using a separate `formData` parameter, ensuring that prefill data is applied correctly when the field is empty.

These changes aim to enhance the accuracy of form initialization by ensuring proper handling of matrix fields during the form setup process.

* Add findFirstPageWithError function to useFormValidation for improved error handling

- Introduced the `findFirstPageWithError` function in `useFormValidation.js` to identify the index of the first page containing validation errors. This function checks for existing errors and iterates through the nested array of field groups to determine if any page has errors, returning the appropriate index or -1 if no errors are found.

These changes aim to enhance the form validation process by providing a clear mechanism to locate pages with validation issues, improving user experience during form submissions.

* Enhance OpenCompleteForm Logic and Add Confetti Feature

- Updated `OpenCompleteForm.vue` to improve conditional rendering by changing `v-if` to `v-else-if` for better clarity in form submission states.
- Introduced a new computed property `shouldDisplayForm` to centralize the logic for determining form visibility based on submission status and admin controls.
- Modified `useFormManager.js` to include a confetti effect upon successful form submission, enhancing user engagement during the submission process.

These changes aim to improve the user experience by refining form visibility logic and adding a celebratory feature upon successful submissions.

* Refactor Form Submission Job and Storage File Logic

- Updated `StoreFormSubmissionJob.php` to streamline the constructor by combining the constructor body into a single line for improved readability.
- Removed debugging output in `StoreFormSubmissionJob.php` to clean up the code and enhance performance.
- Simplified the constructor in `StorageFile.php` by consolidating it into a single line, improving code clarity.
- Enhanced the logic in `StorageFile.php` to utilize a file name parser for checking file existence, ensuring more accurate file handling.

These changes aim to improve code readability and maintainability by simplifying constructors and enhancing file handling logic.

* Refactor Constructors in StoreFormSubmissionJob and StorageFile

- Updated the constructors in `StoreFormSubmissionJob.php` and `StorageFile.php` to include an explicit body, enhancing code clarity and consistency in constructor definitions.
- Improved readability by ensuring a uniform structure across class constructors.

These changes aim to improve code maintainability and readability by standardizing the constructor format in the affected classes.

---------

Co-authored-by: Chirag Chhatrala <chirag.chhatrala@gmail.com>
This commit is contained in:
Julien Nahum
2025-05-07 17:15:56 +02:00
committed by GitHub
parent 6b03808d36
commit 053abbf31b
66 changed files with 5413 additions and 3352 deletions

View File

@@ -290,14 +290,14 @@ function textConditionMet(propertyCondition, value) {
try {
const regex = new RegExp(propertyCondition.value)
return regex.test(value)
} catch (e) {
} catch {
return false
}
case 'does_not_match_regex':
try {
const regex = new RegExp(propertyCondition.value)
return !regex.test(value)
} catch (e) {
} catch {
return true
}
}

View File

@@ -37,7 +37,6 @@ export function createFormModeStrategy(mode) {
admin: {
allowDragging: false,
showAdminControls: false,
isEditingMode: false
}
}
@@ -78,7 +77,6 @@ export function createFormModeStrategy(mode) {
// Editing submission - same validation as LIVE mode, but show hidden fields
// This ensures edit mode behaves like live mode for validation
strategy.display.showHiddenFields = true
strategy.admin.isEditingMode = true
break
case FormMode.TEST:

View File

@@ -0,0 +1,207 @@
import { toValue } from 'vue'
import { opnFetch } from '~/composables/useOpnApi.js'
/**
* @fileoverview Composable for initializing form data, with complete handling of
* form state persistence, URL parameters, and default values.
*/
export function useFormInitialization(formConfig, form, pendingSubmission) {
/**
* Applies URL parameters to the form data.
* @param {URLSearchParams} params - The URL search parameters.
*/
const applyUrlParameters = (params) => {
if (!params) return
// First, handle regular parameters
params.forEach((value, key) => {
// Skip array parameters for now
if (key.endsWith('[]')) return
try {
// Try to parse JSON if the value starts with '{'
const parsedValue = (typeof value === 'string' && value.startsWith('{'))
? JSON.parse(value)
: value
form[key] = parsedValue
} catch {
// If parsing fails, use the original value
form[key] = value
}
})
// Handle array parameters (key[])
const paramKeys = [...new Set([...params.keys()])]
paramKeys.forEach(key => {
if (key.endsWith('[]')) {
const arrayValues = params.getAll(key)
if (arrayValues.length > 0) {
const baseKey = key.slice(0, -2)
form[baseKey] = arrayValues
}
}
})
}
/**
* Applies default data to form fields that don't already have values.
* @param {Object} defaultData - Default data object.
*/
const applyDefaultValues = (defaultData) => {
if (!defaultData || Object.keys(defaultData).length === 0) return
for (const key in defaultData) {
if (Object.hasOwnProperty.call(defaultData, key) && form[key] === undefined) {
form[key] = defaultData[key]
}
}
}
/**
* Updates special fields like dates with today's date if configured.
* @param {Array} fields - Form fields
*/
const updateSpecialFields = () => {
formConfig.value.properties.forEach(field => {
// Handle date fields with prefill_today
if (field.type === 'date' && field.prefill_today) {
form[field.id] = new Date().toISOString()
}
// Handle matrix fields with prefill data
else if (field.type === 'matrix' && !form[field.id] && field.prefill) {
form[field.id] = {...field.prefill}
} else if (field.id && !form[field.id]) {
form[field.id] = field.prefill
}
})
}
/**
* Attempts to load form data from an existing submission.
* @param {String} submissionId - ID of the submission to load
* @returns {Promise<Boolean>} - Whether loading was successful
*/
const tryLoadFromSubmissionId = async (submissionId) => {
const submissionIdValue = toValue(submissionId)
if (!submissionIdValue) return false
const config = toValue(formConfig) // Get the form config value
const slug = config?.slug // Extract the slug
if (!slug) {
console.error('Cannot load submission: Form slug is missing from config.')
form.reset() // Reset if config is invalid
return false
}
// Use the correct route format: /forms/{slug}/submissions/{submission_id}
return opnFetch(`/forms/${slug}/submissions/${submissionIdValue}`)
.then(submissionData => {
if (submissionData.data) {
form.resetAndFill(submissionData.data)
return true
} else {
console.warn(`Submission ${submissionIdValue} for form ${slug} loaded but returned no data.`)
form.reset()
return false
}
})
.catch(error => {
console.error(`Error loading submission ${submissionIdValue} for form ${slug}:`, error)
form.reset()
return false
})
}
/**
* Attempts to load form data from pendingSubmission in localStorage.
* @returns {Boolean} - Whether loading was successful
*/
const tryLoadFromPendingSubmission = () => {
// Skip on server or if pendingSubmission is not available
if (import.meta.server || !pendingSubmission) {
return false
}
// Check if auto-save is enabled for this form
if (!pendingSubmission.enabled?.value) {
return false
}
// Get the saved data
const pendingData = pendingSubmission.get()
if (!pendingData || Object.keys(pendingData).length === 0) {
return false
}
form.resetAndFill(pendingData)
return true
}
/**
* Main method to initialize the form data.
* Follows a clear priority order:
* 1. Load from submission ID (if provided)
* 2. Load from pendingSubmission (localStorage) - client-side only
* 3. Apply URL parameters
* 4. Apply default values for fields
*
* @param {Object} options - Initialization options
* @param {String} [options.submissionId] - ID of submission to load
* @param {URLSearchParams} [options.urlParams] - URL parameters
* @param {Object} [options.defaultData] - Default data to apply
* @param {Array} [options.fields] - Form fields for special handling
*/
const initialize = async (options = {}) => {
const config = toValue(formConfig)
// 1. Reset form state
form.reset()
form.errors.clear()
// 2. Try loading from submission ID
if (options.submissionId) {
const loaded = await tryLoadFromSubmissionId(options.submissionId)
if (loaded) return // Exit if loaded successfully
}
// 3. Try loading from pendingSubmission
if (tryLoadFromPendingSubmission()) {
updateSpecialFields()
return // Exit if loaded successfully
}
// 4. Start with empty form data
const formData = {}
// 5. Apply URL parameters
if (options.urlParams) {
applyUrlParameters(options.urlParams)
}
// 6. Apply special field handling
updateSpecialFields()
// 7. Apply default data from config or options
const defaultData = options.defaultData || config?.default_data
if (defaultData) {
for (const key in defaultData) {
if (!formData[key]) { // Only if not already set
formData[key] = defaultData[key]
}
}
}
// 8. Fill the form with the collected data
if (Object.keys(formData).length > 0) {
form.resetAndFill(formData)
}
}
return {
initialize,
applyUrlParameters,
applyDefaultValues
}
}

View File

@@ -0,0 +1,317 @@
import { reactive, computed, ref, toValue, onBeforeUnmount } from 'vue'
import { useForm } from '~/composables/useForm.js' // Assuming useForm handles vForm setup
import { FormMode, createFormModeStrategy } from '../FormModeStrategy'
import { useFormStructure } from './useFormStructure'
import { useFormInitialization } from './useFormInitialization'
import { useFormValidation } from './useFormValidation'
import { useFormSubmission } from './useFormSubmission'
import { useFormPayment } from './useFormPayment'
import { useFormTimer } from './useFormTimer'
import { usePendingSubmission } from '~/lib/forms/composables/usePendingSubmission.js'
import { usePartialSubmission } from '~/composables/forms/usePartialSubmission.js'
import { useIsIframe } from '~/composables/useIsIframe'
import { useAmplitude } from '~/composables/useAmplitude'
import { useConfetti } from '~/composables/useConfetti'
import { cloneDeep } from 'lodash'
/**
* @fileoverview Main orchestrator composable for form operations.
* Initializes and coordinates various form composables (Structure, Init, Validation, etc.)
* based on the provided form configuration and mode.
*/
export function useFormManager(initialFormConfig, mode = FormMode.LIVE, options = {}) {
// --- Reactive State ---
const config = ref(initialFormConfig) // Use ref for potentially replaceable config
const form = useForm() // Core vForm instance
const strategy = computed(() => createFormModeStrategy(mode)) // Strategy based on mode
// Use the passed darkMode ref if it's a ref, otherwise create a new ref
const darkMode = options.darkMode && typeof options.darkMode === 'object' && 'value' in options.darkMode
? options.darkMode
: ref(options.darkMode || false)
const state = reactive({
currentPage: 0,
isSubmitted: false,
isProcessing: false, // Unified flag for async ops
})
// --- Initialize services that depend on config and form data ---
// Create a reactive reference to the form data for dependent composables to watch
const formDataRef = computed(() => form.data())
// Instantiate pending submission service (handles localStorage saving)
const pendingSubmissionService = usePendingSubmission(config, formDataRef)
// Instantiate partial submission service (handles server auto-sync)
const partialSubmissionService = usePartialSubmission(config, formDataRef, pendingSubmissionService)
// --- Instantiate Other Composables (Services) ---
const timer = useFormTimer(pendingSubmissionService)
const initialization = useFormInitialization(config, form, pendingSubmissionService)
const structure = useFormStructure(config, state, form)
const validation = useFormValidation(config, form, state)
const payment = useFormPayment(config, form)
const submission = useFormSubmission(config, form)
/**
* Initializes the form: loads data, resets state, starts timer.
* @param {Object} options - Initialization options (passed to useFormInitialization).
*/
const initialize = async (options = {}) => {
state.isProcessing = true
state.isSubmitted = false
state.currentPage = 0
await initialization.initialize({
...options
})
timer.reset()
timer.start()
// Start partial submission sync if enabled
if (import.meta.client && config.value.enable_partial_submissions) {
partialSubmissionService.startSync()
}
state.isProcessing = false
}
/**
* Navigates to the next page, handling validation and payment intent creation.
*/
const nextPage = async () => {
if (state.isProcessing) return false
state.isProcessing = true
try {
const currentPageFields = structure.getPageFields(state.currentPage)
// Use computed isLastPage directly from structure composable
const isCurrentlyLastPage = structure.isLastPage.value
// 1. Validate current page
await validation.validateCurrentPage(currentPageFields, strategy.value)
// 2. Process payment (Create Payment Intent if applicable)
const paymentBlock = structure.currentPagePaymentBlock.value
if (paymentBlock) {
// In editor/test mode (not LIVE), skip payment validation
const isPaymentRequired = mode === FormMode.LIVE ? !!paymentBlock.required : false
// Pass required refs if Stripe needs them now (unlikely for just intent creation)
const paymentResult = await payment.processPayment(paymentBlock, isPaymentRequired)
if (!paymentResult.success) {
throw paymentResult.error || new Error('Payment intent creation failed')
}
}
// 3. Move to the next page if not the last
if (!isCurrentlyLastPage) {
state.currentPage++
}
state.isProcessing = false
return true
} catch {
// Use validation composable's failure handler
validation.onValidationFailure({
fieldGroups: structure.fieldGroups.value, // Pass reactive groups
setPageIndexCallback: (index) => { state.currentPage = index },
timerService: timer // Pass the timer composable instance
})
state.isProcessing = false
return false
}
}
/** Navigates to the previous page */
const previousPage = () => {
if (state.currentPage > 0 && !state.isProcessing) {
state.currentPage--
}
}
/**
* Attempts the final form submission.
* Handles timer stop, final validation, captcha, and submission call.
* @param {Object} submitOptions - Optional extra data for submission.
* @returns {Promise<Object>} Result from submission composable.
*/
const submit = async (submitOptions = {}) => {
if (state.isProcessing) {
return Promise.reject('Processing')
}
state.isProcessing = true
try {
// Stop partial submission sync during submission if enabled
if (!import.meta.server && toValue(config).enable_partial_submissions) {
partialSubmissionService.stopSync() // This will sync immediately before stopping
}
// 1. Stop Timer & Get Time
timer.stop()
const completionTime = timer.getCompletionTime()
// 2. Process payment if applicable
const paymentBlock = structure.currentPagePaymentBlock.value
if (paymentBlock) {
// In editor/test mode (not LIVE), skip payment validation
const isPaymentRequired = mode === FormMode.LIVE ? !!paymentBlock.required : false
const paymentResult = await payment.processPayment(paymentBlock, isPaymentRequired)
if (!paymentResult.success) {
// If payment was skipped because it's not required, we continue
if (!paymentResult.skipped) {
// Payment error - don't proceed with submission
state.isProcessing = false
throw new Error(paymentResult.error || 'Payment failed')
}
}
}
// 3. Get submission hash from partialSubmission if enabled
let submissionHash = null
if (!import.meta.server && toValue(config).enable_partial_submissions) {
submissionHash = partialSubmissionService.getSubmissionHash()
}
// 4. Perform Submission (using submission composable)
const submissionResult = await submission.submit({
formModeStrategy: strategy.value,
completionTime: completionTime,
submissionHash: submissionHash,
...submitOptions
})
// 5. Update State on Success
state.isSubmitted = true
state.isProcessing = false
// 6. Play confetti if enabled in config
if (import.meta.client && toValue(config).confetti_on_submission) {
useConfetti().play()
}
// 7. Clear pending submission data on successful submit
pendingSubmissionService?.clear()
// 8. Handle amplitude logging
if (import.meta.client) {
const amplitude = useAmplitude()
amplitude.logEvent('form_submission', {
workspace_id: toValue(config).workspace_id,
form_id: toValue(config).id
})
}
// 9. Handle postMessage communication for iframe integration
if (import.meta.client) {
const isIframe = useIsIframe()
const formConfig = toValue(config)
const payload = cloneDeep({
type: 'form-submitted',
form: {
slug: formConfig.slug,
id: formConfig.id,
redirect_target_url: (formConfig.is_pro && submissionResult?.redirect && submissionResult?.redirect_url)
? submissionResult.redirect_url
: null
},
submission_data: form.data(),
completion_time: completionTime
})
// Send message to parent if in iframe
if (isIframe) {
window.parent.postMessage(payload, '*')
}
// Also send to current window for potential internal listeners
window.postMessage(payload, '*')
}
// 10. Handle redirect if server response includes redirect info
if (import.meta.client && submissionResult?.redirect && submissionResult?.redirect_url) {
window.location.href = submissionResult.redirect_url
}
return submissionResult // Return result from submission composable
} catch (error) {
// Restart partial submission sync if there was an error and it's enabled
if (!import.meta.server && toValue(config).enable_partial_submissions) {
partialSubmissionService.startSync()
}
// Handle validation or submission errors using validation composable's handler
validation.onValidationFailure({
fieldGroups: structure.fieldGroups.value,
setPageIndexCallback: (index) => { state.currentPage = index },
timerService: timer
})
state.isProcessing = false
throw error
}
}
/** Resets the form to its initial state for refilling. */
const restart = async () => {
state.isSubmitted = false
state.currentPage = 0
state.isProcessing = false
form.reset() // Reset vForm data
form.errors.clear() // Clear vForm errors
timer.reset() // Reset timer via composable
timer.start() // Restart timer
// Restart partial submission if enabled
if (!import.meta.server && toValue(config).enable_partial_submissions) {
partialSubmissionService.stopSync() // This will sync immediately before stopping
partialSubmissionService.startSync() // Start fresh sync
}
}
// Clean up when component using the manager is unmounted
if (import.meta.client) {
onBeforeUnmount(() => {
if (toValue(config).enable_partial_submissions) {
partialSubmissionService.stopSync()
}
})
}
// --- Exposed API ---
return {
// Reactive State & Config
state, // Core state (currentPage, isProcessing, isSubmitted)
config, // Form configuration (ref)
form, // The vForm instance (from useForm)
strategy, // Current mode strategy (computed)
pendingSubmission: pendingSubmissionService, // Expose pendingSubmission service
partialSubmission: partialSubmissionService, // Expose partialSubmission service with debounced sync
// UI-related properties
darkMode, // Dark mode setting
setDarkMode: (isDark) => { darkMode.value = isDark }, // Method to update dark mode
// Composables (Expose if direct access needed, often not necessary)
structure,
payment, // Expose payment service
// Core Methods
initialize,
nextPage,
previousPage,
submit,
restart,
// Convenience Computed Getters for vForm state
data: computed(() => form.data()),
errors: computed(() => form.errors),
isDirty: computed(() => form.isDirty),
busy: computed(() => form.busy), // Or potentially combine with state.isProcessing
}
}

View File

@@ -0,0 +1,360 @@
import { toValue, ref } from 'vue'
import { createStripeElements } from '~/composables/useStripeElements'
import { opnFetch } from '~/composables/useOpnApi.js'
// Assume Stripe is loaded globally or via another mechanism if needed client-side
// For server-side/Nuxt API routes, import Stripe library properly.
/**
* @fileoverview Composable for handling payment processing, currently focused on Stripe.
*/
export function useFormPayment(formConfig, form) {
const stripeElements = ref(null)
/**
* Gets payment-related data for a specific payment block
* @param {Object} paymentBlock - The payment field configuration
* @returns {Object|null} Payment data including stripeElements or null if not applicable
*/
const getPaymentData = (paymentBlock) => {
if (!import.meta.client || !paymentBlock || paymentBlock.type !== 'payment') return null
// Create Stripe elements if needed and this is a Stripe payment
if (paymentBlock.provider === 'stripe' || !paymentBlock.provider) {
// Ensure account ID is a string (Stripe.js requires a string)
const accountId = paymentBlock.stripe_account_id ? String(paymentBlock.stripe_account_id) : null
if (!stripeElements.value) {
// Create the Stripe elements with the account ID
stripeElements.value = createStripeElements(accountId)
} else if (stripeElements.value && accountId) {
// Update the account ID if the instance already exists
// Use the proper setter method to avoid readonly errors
if (typeof stripeElements.value.setAccountId === 'function') {
stripeElements.value.setAccountId(accountId)
}
}
return {
stripeElements: stripeElements.value,
oauthProviderId: accountId
}
}
return null
}
/**
* Creates a payment intent with the Stripe API using a POST request.
* @param {Number} amount - The amount to charge in cents.
* @param {String} currency - The currency code (e.g., 'usd').
* @param {String} description - A description for the payment.
* @returns {Promise<Object>} The result of creating the payment intent.
*/
const _createPaymentIntent = async (_amount, _currency, _description) => {
if (!import.meta.client) {
return { success: false, error: 'Client-side only operation' }
}
try {
// Get form slug from config
const config = toValue(formConfig)
const formSlug = config.slug
if (!formSlug) {
console.error('Missing form slug in config')
return { success: false, error: 'Invalid form configuration' }
}
// Construct the URL (no query params needed for POST)
const url = `/forms/${formSlug}/stripe-connect/payment-intent`
// Use opnFetch with POST method and an empty body
const response = await opnFetch(url, {
method: 'POST',
body: {}
})
// Handle response structure with type and intent fields
if (response?.type === 'success' && response?.intent?.secret) {
return {
success: true,
client_secret: response.intent.secret,
intentId: response.intent.id
}
}
// Handle error response
return {
success: false,
error: response?.message || 'Could not create payment: Invalid response from server'
}
} catch (error) {
return {
success: false,
error: error.message || 'Failed to create payment'
}
}
}
/**
* Confirms the Stripe payment on the client-side using Stripe.js.
* @param {String} clientSecret - The Stripe client secret.
* @param {String} paymentBlockId - The ID of the payment block for setting errors.
* @returns {Promise<Object>} The result of the payment confirmation.
*/
const _confirmStripePayment = async (clientSecret, paymentBlockId) => {
if (!import.meta.client) {
return { success: false, error: 'Client-side only operation' }
}
if (!stripeElements.value || !stripeElements.value.state) {
return { success: false, error: 'Stripe elements not initialized' }
}
const state = stripeElements.value.state
const { stripe, card } = state
if (!stripe || !card) {
const error = 'Stripe or card element not available'
if (paymentBlockId) form.errors.set(paymentBlockId, error)
return { success: false, error }
}
try {
const result = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: card,
billing_details: {
name: state.cardHolderName || '',
email: state.cardHolderEmail || ''
}
},
receipt_email: state.cardHolderEmail
})
// Check for errors
if (result.error) {
console.error('Payment confirmation error:', result.error)
const errorMessage = result.error.message || 'Payment failed. Please try again.'
if (paymentBlockId) {
form.errors.set(paymentBlockId, errorMessage)
}
return {
success: false,
error: errorMessage,
code: result.error.code,
type: result.error.type
}
}
// Handle payment intent status
if (result.paymentIntent) {
const status = result.paymentIntent.status
const intentId = result.paymentIntent.id
// Store successful payment intent ID
if (status === 'succeeded' || status === 'processing') {
// Update form data with payment information
const updateData = {}
updateData['stripe_payment_intent_id'] = intentId
updateData['payment_status'] = status
// Update payment block field with intent ID
if (paymentBlockId) {
updateData[paymentBlockId] = intentId
}
// Update form data
form.update(updateData)
// Also update the Stripe state
if (state.intentId !== intentId && stripeElements.value.setIntentId) {
stripeElements.value.setIntentId(intentId)
}
return {
success: true,
paymentIntent: result.paymentIntent,
status: status,
intentId: intentId
}
} else {
// Payment intent exists but status is not successful
const failMessage = `Payment failed with status: ${status}`
console.error(failMessage)
if (paymentBlockId) {
form.errors.set(paymentBlockId, failMessage)
}
return { success: false, error: failMessage }
}
}
// If we get here, something unexpected happened
const unexpectedError = 'Payment failed with an unexpected error'
if (paymentBlockId) {
form.errors.set(paymentBlockId, unexpectedError)
}
return { success: false, error: unexpectedError }
} catch (error) {
console.error('Payment confirmation error:', error)
const errorMessage = error.message || 'Payment confirmation failed'
if (paymentBlockId) {
form.errors.set(paymentBlockId, errorMessage)
}
return {
success: false,
error: errorMessage,
code: error.code,
type: error.type
}
}
}
/**
* Process a payment for the form
* @param {Object} paymentBlock - The payment block from the form config
* @param {Boolean} isRequired - Whether payment is required
* @returns {Promise<Object>} The result of the payment processing
*/
const processPayment = async (paymentBlock, isRequired = true) => {
// Only process payments on the client side
if (!import.meta.client) {
console.warn('Payment processing attempted on server')
return { success: false, error: 'Payment can only be processed in the browser' }
}
// Validate the payment block
if (!paymentBlock || paymentBlock.type !== 'payment') {
console.error('Invalid payment block provided:', paymentBlock)
return { success: false, error: 'Invalid payment block' }
}
const paymentBlockId = paymentBlock.id
// First check for existing payment in form data
const existingPaymentId = form[paymentBlockId]
if (existingPaymentId && isPaymentIntentId(existingPaymentId)) {
return { success: true, intentId: existingPaymentId }
}
// Check if Stripe elements are initialized
if (!stripeElements.value || !stripeElements.value.state) {
console.error('Stripe elements not initialized')
if (paymentBlockId) form.errors.set(paymentBlockId, 'Payment system not ready')
return { success: false, error: 'Stripe elements not initialized' }
}
const state = stripeElements.value.state
const { stripe, card } = state
// Check if Stripe is loaded
if (!stripe) {
const error = 'Stripe.js not initialized'
console.error(error)
if (paymentBlockId) form.errors.set(paymentBlockId, error)
return { success: false, error }
}
// Check if card is complete
const cardComplete = card && !card._empty
if (!cardComplete) {
// If payment is not required and card is empty, just skip payment
if (!isRequired) {
return { success: true, skipped: true }
}
const error = 'Please enter your card details'
if (paymentBlockId) form.errors.set(paymentBlockId, error)
return { success: false, error }
}
// Validate billing details
if (!state.cardHolderName) {
const error = 'Please enter the name on your card'
if (paymentBlockId) form.errors.set(paymentBlockId, error)
return { success: false, error }
}
if (!state.cardHolderEmail) {
const error = 'Please enter your billing email'
if (paymentBlockId) form.errors.set(paymentBlockId, error)
return { success: false, error }
}
try {
// Step 1: Create payment intent
const config = toValue(formConfig)
const formSlug = config.slug
if (!formSlug) {
const error = 'Missing form slug'
if (paymentBlockId) form.errors.set(paymentBlockId, error)
return { success: false, error }
}
// Create payment intent
const intentResult = await _createPaymentIntent(
paymentBlock.amount,
paymentBlock.currency || 'usd',
paymentBlock.description || ''
)
if (!intentResult.success || !intentResult.client_secret) {
const error = intentResult.error || 'Failed to create payment intent'
console.error('Payment intent creation failed:', error)
if (paymentBlockId) form.errors.set(paymentBlockId, error)
return { success: false, error }
}
// Step 2: Confirm payment with Stripe
const confirmResult = await _confirmStripePayment(intentResult.client_secret, paymentBlockId)
// Return the result from confirmation
return confirmResult
} catch (error) {
console.error('Payment processing error:', error)
const errorMessage = error.message || 'Payment processing failed'
if (paymentBlockId) form.errors.set(paymentBlockId, errorMessage)
return { success: false, error: errorMessage }
}
}
/**
* Confirms a Stripe payment with given client secret.
* This method is available for direct usage if needed.
* @param {String} clientSecret - The client secret from a payment intent
* @param {String} [paymentBlockId] - Optional ID of payment block for error display
* @returns {Promise<Object>} The result of payment confirmation
*/
const confirmStripePayment = async (clientSecret, paymentBlockId) => {
if (!clientSecret) {
console.error('Missing client secret for payment confirmation')
return { success: false, error: 'Invalid payment data' }
}
return await _confirmStripePayment(clientSecret, paymentBlockId)
}
// Helper function to check if a value looks like a Stripe payment intent ID
const isPaymentIntentId = (value) => {
return typeof value === 'string' && value.startsWith('pi_')
}
// Expose the main payment processing function
return {
processPayment,
getPaymentData,
createPaymentIntent: _createPaymentIntent,
confirmStripePayment
}
}

View File

@@ -0,0 +1,366 @@
import { computed, toValue } from 'vue'
import FormLogicPropertyResolver from '~/lib/forms/FormLogicPropertyResolver.js'
/**
* @fileoverview Composable responsible for analyzing and managing the structural aspects of a form,
* including page breaks, field grouping, page boundaries, and determining field locations.
*/
export function useFormStructure(formConfig, managerState, formData) {
const form = computed(() => toValue(formConfig) || { properties: [] })
/**
* Checks if a field is hidden based on form logic.
* Uses FormLogicPropertyResolver.
* @param {Object} field - The field configuration object.
* @returns {Boolean} True if the field is hidden, false otherwise.
*/
const isFieldHidden = (field) => {
try {
// Use the formData ref passed into the composable
const currentFormData = toValue(formData) || {}
return new FormLogicPropertyResolver(field, currentFormData).isHidden()
} catch (e) {
console.error("Error checking if field is hidden:", field?.id, e)
return field?.hidden || false // Fallback
}
}
/**
* Calculates the groups of fields based on non-hidden page breaks.
* @returns {Array<Array<Object>>} Nested array where each inner array represents a page.
*/
const calculateFieldGroups = () => {
const properties = form.value.properties || []
if (properties.length === 0) return [[]]
const groups = []
let currentGroup = []
properties.forEach((field, index) => {
currentGroup.push(field)
// Check if the field is a page break AND it's not hidden
if (field.type === 'nf-page-break' && !isFieldHidden(field)) {
groups.push([...currentGroup])
if (index < properties.length - 1) {
currentGroup = []
}
}
})
// Add the last group if it's not empty AND the last field wasn't a non-hidden page break
const lastProperty = properties[properties.length - 1]
if (currentGroup.length > 0 && (!lastProperty || lastProperty.type !== 'nf-page-break' || isFieldHidden(lastProperty))) {
groups.push(currentGroup)
}
// Ensure at least one group exists
if (groups.length === 0) {
groups.push([])
}
return groups
}
/**
* Reactive computed property holding the field groups.
*/
const fieldGroups = computed(calculateFieldGroups)
/**
* Reactive computed property holding the total number of pages.
*/
const pageCount = computed(() => {
const groups = fieldGroups.value
const count = groups ? groups.length : 0
return count
})
/**
* Calculates the start and end indices for each page.
* @returns {Array<Object>} Array of boundary objects { start, end }.
*/
const calculatePageBoundaries = () => {
const properties = form.value.properties || []
if (properties.length === 0) {
return [{ start: 0, end: -1 }] // Empty form
}
const boundaries = []
let startIndex = 0
let visibleBreakFound = false
properties.forEach((field, index) => {
// Check if the field is a page break AND it's not hidden
if (field.type === 'nf-page-break' && !isFieldHidden(field)) {
visibleBreakFound = true
// The page ends *at* the page break field
boundaries.push({ start: startIndex, end: index })
// The next page starts *after* the page break field
startIndex = index + 1
}
})
// If no visible page breaks were found, the entire form is a single page
if (!visibleBreakFound) {
return [{ start: 0, end: properties.length - 1 }]
}
// Add the boundary for the last page if there are fields after the last visible break
if (startIndex < properties.length) {
boundaries.push({ start: startIndex, end: properties.length - 1 })
}
// If the last field was a visible page break, startIndex will equal properties.length,
// and we don't add an extra empty page boundary.
// Safety check: Ensure at least one boundary exists if properties are not empty
if (boundaries.length === 0 && properties.length > 0) {
return [{ start: 0, end: properties.length - 1 }]
}
return boundaries
}
/**
* Reactive computed property holding the page boundaries.
*/
const pageBoundaries = computed(calculatePageBoundaries)
/**
* Reactive computed property for the page break field ending the current page.
*/
const currentPageBreak = computed(() => {
const groups = fieldGroups.value
if (!managerState || !groups) return null
const currentPageIndex = managerState.currentPage
if (currentPageIndex < 0 || currentPageIndex >= groups.length) return null
const currentPageFields = groups[currentPageIndex] || []
if (currentPageFields.length === 0) return null
const lastField = currentPageFields[currentPageFields.length - 1]
// It's the current page break only if it's a page break and *not hidden*
return (lastField && lastField.type === 'nf-page-break' && !isFieldHidden(lastField)) ? lastField : null
})
/**
* Reactive computed property for the page break field ending the previous page.
*/
const previousPageBreak = computed(() => {
const groups = fieldGroups.value
if (!managerState || !groups || managerState.currentPage <= 0) return null
const previousPageIndex = managerState.currentPage - 1
if (previousPageIndex < 0 || previousPageIndex >= groups.length) return null
const previousPageFields = groups[previousPageIndex] || []
if (previousPageFields.length === 0) return null
const lastField = previousPageFields[previousPageFields.length - 1]
// It's the previous page break only if it's a page break and *not hidden*
return (lastField && lastField.type === 'nf-page-break' && !isFieldHidden(lastField)) ? lastField : null
})
/**
* Reactive computed property indicating if the current page is the last one.
*/
const isLastPage = computed(() => {
if (managerState?.currentPage === undefined || managerState?.currentPage === null || pageCount.value === undefined) {
// console.warn('[useFormStructure] isLastPage: Invalid state, returning default true.');
return true // Default true for safety in simple forms
}
const result = managerState.currentPage === pageCount.value - 1
return result
})
/**
* Reactive computed property checking if current page has a payment block
*/
const currentPageHasPaymentBlock = computed(() => {
if (managerState?.currentPage === undefined || managerState?.currentPage === null) return false
return hasPaymentBlock(managerState.currentPage)
})
/**
* Reactive computed property returning the payment block from the current page, if any
*/
const currentPagePaymentBlock = computed(() => {
if (managerState?.currentPage === undefined || managerState?.currentPage === null) return undefined
return getPaymentBlock(managerState.currentPage)
})
/**
* Gets the fields for a specific page index.
* @param {Number} pageIndex - The index of the page.
* @returns {Array<Object>} Array of field objects for the page.
*/
const getPageFields = (pageIndex) => {
const groups = fieldGroups.value
if (!groups) {
console.warn("useFormStructure: getPageFields called but fieldGroups is undefined.")
return []
}
return groups[pageIndex] || []
}
/**
* Determines the page index for a given field index within the form properties array.
* @param {Number} fieldIndex - The index of the field in the form.properties array.
* @returns {Number} The page index (0-based).
*/
const getPageForField = (fieldIndex) => {
// Basic validation for field index
if (fieldIndex === null || fieldIndex === undefined ||
typeof fieldIndex !== 'number' || isNaN(fieldIndex) || fieldIndex < 0) {
console.warn(`Invalid field index passed to getPageForField: ${fieldIndex}`)
return 0 // Default to first page for invalid indexes
}
const properties = form.value.properties || []
if (properties.length === 0 || fieldIndex >= properties.length) {
return 0 // Default to first page
}
const boundaries = pageBoundaries.value
if (!boundaries || boundaries.length === 0) return 0
// If only one boundary (covers all), it's page 0
if (boundaries.length === 1 && boundaries[0].start === 0) {
return 0
}
for (let i = 0; i < boundaries.length; i++) {
const { start, end } = boundaries[i]
if (fieldIndex >= start && fieldIndex <= end) {
return i
}
}
// Fallback: Should technically not be reached with correct boundaries
console.warn(`[useFormStructure] getPageForField: Field index ${fieldIndex} not found within calculated boundaries. Returning last page index.`)
return Math.max(0, boundaries.length - 1)
}
/**
* Checks if a given page contains a payment block.
* @param {Number} pageIndex - The page index.
* @returns {Boolean} True if a payment block exists on the page.
*/
const hasPaymentBlock = (pageIndex) => {
return getPageFields(pageIndex).some(field => field?.type === 'payment')
}
/**
* Gets the payment block field object from a given page.
* @param {Number} pageIndex - The page index.
* @returns {Object|undefined} The payment field object or undefined if not found.
*/
const getPaymentBlock = (pageIndex) => {
return getPageFields(pageIndex).find(field => field?.type === 'payment')
}
/**
* Determines the target index in the flat form.properties array for drag/drop operations.
* @param {number} currentFieldPageIndex - The relative index of the field within the current page's field list.
* @param {number} selectedFieldIndex - The original flat index of the field being dragged (often not needed here).
* @param {number} currentPageIndex - The index of the page where the drop occurs.
* @returns {number} The absolute index in the form.properties array.
*/
const getTargetDropIndex = (relativeDropIndex, targetPageIndex) => {
const groups = fieldGroups.value
if (!groups) return relativeDropIndex // Fallback
let precedingFields = 0
for(let i = 0; i < targetPageIndex; i++) {
precedingFields += groups[i]?.length || 0
}
return precedingFields + relativeDropIndex
}
/**
* Sets the current page to the page containing the specified field.
* @param {Number} fieldIndex - The index of the field in the form.properties array.
* @returns {Number} The page index that was set.
*/
const setPageForField = (fieldIndex) => {
// Get the page index, with additional validation
const pageIndex = getPageForField(fieldIndex)
// Ensure we have a valid numeric page index
if (typeof pageIndex !== 'number' || isNaN(pageIndex) || pageIndex < 0) {
console.warn('[useFormStructure] setPageForField: Invalid page index', pageIndex)
return
}
// Update the manager state with validated page index - DON'T USE toValue HERE
if (managerState && managerState.currentPage !== undefined) {
managerState.currentPage = pageIndex
}
return pageIndex
}
/**
* Determines the correct index to insert a new field.
* Considers selected field index and current page boundaries.
* @param {Number|null} selectedFieldIndex - The index of the currently selected field in form.properties.
* @param {Number} currentPageIndex - The current page index.
* @param {Number|null} [explicitIndex=null] - An explicitly provided insert index.
* @returns {Number} The calculated index for insertion.
*/
const determineInsertIndex = (selectedFieldIndex, currentPageIndex, explicitIndex = null) => {
if (explicitIndex !== null && typeof explicitIndex === 'number') {
return explicitIndex
}
if (selectedFieldIndex !== null && selectedFieldIndex !== undefined && selectedFieldIndex >= 0) {
return selectedFieldIndex + 1
}
const properties = form.value.properties || []
if (properties.length === 0) {
return 0
}
const boundaries = pageBoundaries.value
// Use managerState directly without toValue
const pageIdx = currentPageIndex ?? managerState?.currentPage ?? 0 // Use provided or state page index
if (!boundaries || boundaries.length === 0 || pageIdx >= boundaries.length || pageIdx < 0) {
// Fallback to end of the form if boundaries/page index is invalid
return properties.length
}
const currentBoundary = boundaries[pageIdx]
// Insert at the end of the current page (index after the last field of that page)
return currentBoundary.end + 1
}
// --- Exposed API ---
return {
// Reactive Computed Properties
fieldGroups,
pageCount,
pageBoundaries,
currentPageBreak,
previousPageBreak,
isLastPage,
currentPage: computed(() => managerState?.currentPage ?? 0),
currentPageHasPaymentBlock,
currentPagePaymentBlock,
// Methods
getPageFields, // Get fields for a specific page
getPageForField, // Find which page a field index belongs to
hasPaymentBlock, // Check if a page has a payment block
getPaymentBlock, // Get the payment block from a page
isFieldHidden, // Check if a specific field is hidden by logic
getTargetDropIndex, // Calculate absolute index for drag/drop
determineInsertIndex, // Calculate where to insert a new field
setPageForField // Set the current page to the page containing the specified field
}
}

View File

@@ -0,0 +1,77 @@
import { toValue } from 'vue'
/**
* @fileoverview Composable for handling the final form submission process.
*/
export function useFormSubmission(formConfig, form) {
/**
* Prepares additional metadata for the submission payload.
* Focuses only on metadata fields, not the form data itself.
* @param {Object} options - Options containing completionTime, captchaToken, etc.
* @returns {Object} Metadata to be included in the submission request.
*/
const _prepareMetadata = (options = {}) => {
const metadata = {}
// Add completion time if provided
if (options.completionTime !== undefined) {
metadata.completion_time = options.completionTime
}
// Add captcha token if provided
if (options.captchaToken) {
metadata.captcha_token = options.captchaToken
}
// Add submission hash if provided (for partial submissions)
if (options.submissionHash) {
metadata.submission_hash = options.submissionHash
}
// Add submission ID if provided (for editable submissions)
if (options.submissionId) {
metadata.submission_id = options.submissionId
}
return metadata
}
/**
* Performs the form submission.
* @param {Object} options - Submission options.
* @param {Object} options.formModeStrategy - The strategy object.
* @param {Number} [options.completionTime] - Form completion time in seconds.
* @param {String} [options.captchaToken] - Captcha verification token.
* @param {String} [options.submissionHash] - Hash for partial submissions.
* @param {String} [options.submissionId] - ID for editable submissions.
* @returns {Promise<Object>} The response data from the submission endpoint.
* @throws {Error} If submission fails.
*/
const submit = async (options = {}) => {
// Get the form slug from config
const formSlug = formConfig.value.slug
// Get the URL for form submission
const url = `/forms/${formSlug}/answer`
// Prepare metadata only (form data will be auto-merged by Form.js)
const metadata = _prepareMetadata(options)
// Use the vForm post method, which will automatically merge form data with metadata
const response = await toValue(form).post(url, {
data: metadata
})
// Optionally reset form after successful submission based on strategy
const formModeStrategy = options.formModeStrategy
if (formModeStrategy?.submission?.resetAfterSubmit) {
toValue(form).reset()
}
return response
}
// Expose the main submission function
return {
submit,
}
}

View File

@@ -0,0 +1,115 @@
import { ref } from 'vue'
/**
* @fileoverview Composable for managing form completion time.
* Includes persistence in localStorage via pendingSubmission.
*/
export function useFormTimer(pendingSubmission) {
// Reactive state for timer
const startTime = ref(null)
const completionTime = ref(null)
const isTimerActive = ref(false)
const isInitialized = ref(false)
/**
* Loads timer data from localStorage if available.
* @returns {Boolean} Whether data was loaded successfully
*/
const loadFromLocalStorage = () => {
if (import.meta.server || !pendingSubmission) return false
const savedTimer = pendingSubmission.getTimer()
if (savedTimer) {
startTime.value = parseInt(savedTimer)
return true
}
return false
}
/**
* Saves the current start time to localStorage.
*/
const saveToLocalStorage = () => {
if (import.meta.server || !pendingSubmission) return
if (startTime.value) {
pendingSubmission.setTimer(startTime.value.toString())
} else {
pendingSubmission.removeTimer()
}
}
/**
* Starts the timer if not already active.
* Will load from localStorage on first call if available.
*/
const start = () => {
if (isTimerActive.value) {
return
}
// If this is the first time starting, try to load from localStorage
if (!isInitialized.value) {
isInitialized.value = true
loadFromLocalStorage()
}
// Only set a new start time if one doesn't exist already
if (!startTime.value) {
startTime.value = Date.now()
}
isTimerActive.value = true
saveToLocalStorage()
}
/**
* Stops the timer if active and calculates completion time.
*/
const stop = () => {
if (!isTimerActive.value) {
return
}
if (startTime.value) {
completionTime.value = Math.round((Date.now() - startTime.value) / 1000) // Time in seconds
} else {
completionTime.value = null
}
isTimerActive.value = false
// Don't clear local storage on stop - only on reset or explicit removal
}
/**
* Resets the timer state and clears localStorage.
*/
const reset = () => {
startTime.value = null
completionTime.value = null
isTimerActive.value = false
if (pendingSubmission) {
pendingSubmission.removeTimer()
}
}
/**
* Returns the calculated completion time.
* @returns {Number|null} Completion time in seconds, or null if not available.
*/
const getCompletionTime = () => {
return completionTime.value
}
// Expose reactive state and methods
return {
isTimerActive, // Expose reactive status
completionTime, // Expose reactive completion time
start,
stop,
reset,
getCompletionTime,
}
}

View File

@@ -0,0 +1,135 @@
import { computed, toValue } from 'vue'
/**
* @fileoverview Composable for handling form validation logic.
*/
export function useFormValidation(formConfig, form, managerState) {
const formRef = computed(() => toValue(form)) // Ensure reactivity with the form instance
const configRef = computed(() => toValue(formConfig)) // Ensure reactivity with config
/**
* Validates specific fields using the vForm instance's validate method.
* @param {Array<String>} fieldIds - Array of field IDs to validate.
* @param {String} [httpMethod='POST'] - HTTP method for the validation request.
* @returns {Promise<boolean>} Resolves true if validation passes, rejects with errors if fails.
*/
const validateFields = async (fieldIds, httpMethod = 'POST') => {
if (!fieldIds || fieldIds.length === 0) {
return true // Nothing to validate
}
const config = configRef.value
const validationUrl = `/forms/${config.slug}/answer` // Use reactive config
// Use the reactive formRef
await formRef.value.validate(httpMethod, validationUrl, {}, fieldIds)
return true // Validation passed
}
/**
* Validates fields on the current page based on the form mode strategy.
* Excludes payment fields.
* @param {Array<Object>} currentPageFields - Array of field objects for the current page.
* @param {Object} formModeStrategy - The strategy object for the current mode.
* @returns {Promise<boolean>} Resolves true if validation passes or isn't required, rejects otherwise.
*/
const validateCurrentPage = async (currentPageFields, formModeStrategy) => {
if (!formModeStrategy?.validation?.validateOnNextPage) {
return true
}
const fieldIdsToValidate = currentPageFields
.filter(field => field && field.id && field.type !== 'payment')
.map(field => field.id)
if (fieldIdsToValidate.length === 0) {
return true
}
await validateFields(fieldIdsToValidate)
return true
}
/**
* Validates all form fields before final submission, *unless* currently on the last page.
* @param {Array<Object>} allFields - Array of all field objects in the form.
* @param {Object} formModeStrategy - The strategy object for the current mode.
* @param {boolean} isCurrentlyLastPage - Boolean indicating if the *current* state is the last page.
* @returns {Promise<boolean>} Resolves true if validation passes or isn't required/skipped, rejects otherwise.
*/
const validateSubmissionIfNotLastPage = async (allFields, formModeStrategy, isCurrentlyLastPage) => {
// Skip validation if we are already determined to be on the last page
if (isCurrentlyLastPage) {
return true
}
// Skip validation if strategy doesn't require it
if (!formModeStrategy?.validation?.validateOnSubmit) {
return true
}
const fieldIdsToValidate = allFields
.filter(field => field && field.id && field.type !== 'payment')
.map(field => field.id)
if (fieldIdsToValidate.length === 0) {
return true
}
await validateFields(fieldIdsToValidate)
return true
}
/**
* Finds the index of the first page containing validation errors.
* @param {Array<Array<Object>>} fieldGroups - Nested array of fields per page (from useFormStructure).
* @returns {number} Index of the first page with errors, or -1 if no errors found.
*/
const findFirstPageWithError = (fieldGroups) => {
const errors = formRef.value.errors
if (!errors || !errors.any()) {
return -1 // No errors exist
}
if (!fieldGroups) return -1 // No groups to check
for (let i = 0; i < fieldGroups.length; i++) {
const pageHasError = fieldGroups[i]?.some(field => field && field.id && errors.has(field.id))
if (pageHasError) {
return i
}
}
return -1
}
/**
* Actions to perform on validation failure (e.g., during submit or page change).
* @param {Object} context - Object containing { fieldGroups, timerService, setPageIndexCallback }.
*/
const onValidationFailure = (context) => {
const { fieldGroups, timerService, setPageIndexCallback } = context
// Restart timer using the timer composable instance
if (timerService && typeof timerService.start === 'function') {
timerService.start()
}
// Find and navigate to the first page with an error
if (fieldGroups && fieldGroups.length > 1 && typeof setPageIndexCallback === 'function') {
const errorPageIndex = findFirstPageWithError(fieldGroups)
if (errorPageIndex !== -1 && errorPageIndex !== managerState?.currentPage) {
setPageIndexCallback(errorPageIndex)
}
}
}
// --- Exposed API ---
return {
// Methods
validateFields,
validateCurrentPage,
validateSubmissionIfNotLastPage,
findFirstPageWithError,
onValidationFailure,
}
}

View File

@@ -0,0 +1,124 @@
import { hash } from "~/lib/utils.js"
import { useStorage, watchThrottled } from "@vueuse/core"
import { computed, toValue } from 'vue'
/**
* Composable for managing pending form submission data and timer in localStorage.
* Includes throttled auto-saving of form data.
*
* @param {import('vue').Ref<Object>} formConfig - Reactive reference to the form configuration object.
* @param {import('vue').ComputedRef<Object>} formDataRef - Computed reference to the reactive form data object.
*/
export function usePendingSubmission(formConfig, formDataRef) {
const config = computed(() => toValue(formConfig)) // Ensure reactivity to config changes
const formPendingSubmissionKey = computed(() => {
const currentConfig = config.value
return currentConfig && typeof window !== 'undefined'
? currentConfig.form_pending_submission_key + "-" + hash(window.location.href)
: ""
})
const formPendingSubmissionTimerKey = computed(() => {
return formPendingSubmissionKey.value ? formPendingSubmissionKey.value + "-timer" : ""
})
const enabled = computed(() => {
// Auto-save is enabled if the feature is turned on in the config
return config.value?.auto_save ?? false
})
// Internal function to save data to localStorage
const saveData = (value) => {
if (import.meta.server || !enabled.value || !formPendingSubmissionKey.value) return
try {
useStorage(formPendingSubmissionKey.value).value =
value === null ? null : JSON.stringify(value)
} catch (e) {
console.error("Error saving pending submission to localStorage:", e)
}
}
// Internal function to retrieve data from localStorage
const retrieveData = (defaultValue = {}) => {
if (import.meta.server || !enabled.value || !formPendingSubmissionKey.value) return defaultValue
try {
const storageValue = useStorage(formPendingSubmissionKey.value).value
return storageValue ? JSON.parse(storageValue) : defaultValue
} catch (e) {
console.error("Error reading pending submission from localStorage:", e)
// Attempt to clear corrupted data
remove()
return defaultValue
}
}
// Watch formDataRef with throttling
watchThrottled(
formDataRef,
(newData) => {
// Only save if enabled and on client
if (import.meta.client && enabled.value) {
saveData(newData)
}
},
{ deep: true, throttle: 1000 } // Throttle saving to once per second
)
// --- Exposed Methods ---
const remove = () => {
// Clear the data from storage
saveData(null)
}
const get = (defaultValue = {}) => {
// Retrieve the currently stored data
return retrieveData(defaultValue)
}
const setSubmissionHash = (hash) => {
if (!enabled.value) return
const currentData = retrieveData()
saveData({
...currentData,
submission_hash: hash
})
}
const getSubmissionHash = () => {
return retrieveData()?.submission_hash ?? null
}
const setTimer = (value) => {
if (import.meta.server || !formPendingSubmissionTimerKey.value) return
useStorage(formPendingSubmissionTimerKey.value).value = value
}
const removeTimer = () => {
setTimer(null)
}
const getTimer = (defaultValue = null) => {
if (import.meta.server || !formPendingSubmissionTimerKey.value) return defaultValue
return useStorage(formPendingSubmissionTimerKey.value, defaultValue).value
}
const clear = () => {
remove()
removeTimer()
}
return {
formPendingSubmissionKey, // Keep for potential external use (e.g., partial submission hash map key)
enabled,
get, // Method to retrieve stored data
remove, // Method to clear stored data
setSubmissionHash, // Method to specifically set the submission hash
getSubmissionHash, // Method to specifically get the submission hash
setTimer, // Method to set the timer value
removeTimer, // Method to clear the timer value
getTimer, // Method to get the timer value
clear, // Method to clear both data and timer
}
}