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

@@ -204,14 +204,14 @@ const formattedDate = (value) => {
if (props.withTime) {
try {
return format(new Date(value), props.dateFormat + (props.timeFormat == 12 ? ' p':' HH:mm'))
} catch (e) {
console.error('Error formatting date', e)
} catch {
console.error('Error formatting date')
return ''
}
}
try {
return format(new Date(value), props.dateFormat)
} catch (e) {
} catch {
return ''
}
}

View File

@@ -24,6 +24,24 @@
<template
v-if="options && options.length"
>
<div v-if="multiple && compVal && compVal.length" class="px-3 py-2">
<slot
name="selected"
:option="selectedOptions"
:option-name="multiple ? getSelectedOptionsNames().join(', ') : getOptionName(selectedOptions)"
>
<div class="flex items-center truncate">
<span
class="truncate"
:class="[
theme.FlatSelectInput.fontSize,
]"
>
{{ getSelectedOptionsNames().join(', ') }}
</span>
</div>
</slot>
</div>
<div
v-for="(option) in options"
:key="option[optionKey]"
@@ -58,9 +76,15 @@
:prevent="!disableOptions.includes(option[optionKey])"
class="w-full"
>
<p class="flex-grow">
{{ option[displayKey] }}
</p>
<slot
name="option"
:option="option"
:selected="isSelected(option[optionKey])"
>
<p class="flex-grow">
{{ option[displayKey] }}
</p>
</slot>
</UTooltip>
</div>
</template>
@@ -120,7 +144,17 @@ export default {
data() {
return {}
},
computed: {},
computed: {
selectedOptions() {
if (!this.compVal) return []
if (this.multiple) {
return this.options.filter(option => this.compVal.includes(option[this.optionKey]))
}
return this.options.find(option => option[this.optionKey] === this.compVal) || null
},
},
methods: {
onSelect(value) {
if (this.disabled || this.disableOptions.includes(value)) {
@@ -156,6 +190,18 @@ export default {
}
return this.compVal === value
},
getOptionName(option) {
return option ? option[this.displayKey] : ''
},
getSelectedOptionsNames() {
if (!this.compVal) return []
if (this.multiple) {
return this.selectedOptions.map(option => option[this.displayKey])
}
return [this.getOptionName(this.selectedOptions)]
},
},
}
</script>

View File

@@ -44,10 +44,17 @@
</div>
<template v-else>
<div
v-if="shouldShowPreviewMessage"
v-if="shouldShowPreviewMessage || (props.isAdminPreview && (!stripeState.stripeAccountId || !publishableKey || !isStripeJsLoaded))"
class="my-4 p-4 text-center text-sm text-blue-700 bg-blue-100 dark:bg-blue-900/50 dark:text-blue-300 rounded-md"
>
<p>Please save the form to activate the payment preview.</p>
<p v-if="shouldShowPreviewMessage">Please save the form to activate the payment preview.</p>
<p v-else>
Payment component configuration incomplete.
{{ !stripeState?.stripeAccountId ? 'Stripe account not connected': 'Stripe account connected' }}.
{{ !publishableKey ? 'Missing Stripe publishable key.' : '' }}
{{ !isStripeJsLoaded ? 'Stripe.js not loaded.' : '' }}
</p>
<p class="mt-2">The complete payment form will be visible to users when viewing the published form.</p>
</div>
<div
v-else-if="stripeState && stripeState.isLoadingAccount"
@@ -80,8 +87,8 @@
<StripeElements
ref="stripeElementsRef"
:stripe-key="publishableKey"
:stripe-account="stripeState.stripeAccountId"
:instance-options="{ stripeAccount: stripeState.stripeAccountId }"
:stripe-account="String(stripeState.stripeAccountId)"
:instance-options="{ stripeAccount: String(stripeState.stripeAccountId) }"
:elements-options="{ locale: props.locale }"
@ready="onStripeReady"
@error="onStripeError"
@@ -135,7 +142,16 @@
</StripeElements>
</div>
<div v-else>
<Loader class="mx-auto h-6 w-6" />
<div v-if="props.isAdminPreview" class="my-4 p-4 text-center text-sm text-blue-700 bg-blue-100 dark:bg-blue-900/50 dark:text-blue-300 rounded-md">
<p>Payment component initializing. {{ !!stripeState?.stripeAccountId ? 'Stripe account connected': 'No Stripe account connected' }}.</p>
<p class="mt-2">The payment form will be visible to users when viewing the published form.</p>
<p v-if="!publishableKey" class="mt-2 text-red-500">Missing Stripe publishable key in configuration.</p>
<p v-if="!stripeState?.stripeAccountId" class="mt-2 text-red-500">Missing Stripe account connection. ID: {{ props.oauthProviderId }}</p>
</div>
<div v-else class="flex flex-col items-center justify-center py-4">
<Loader class="mx-auto h-6 w-6" />
<p class="text-sm text-gray-500 mt-2">Initializing payment system...</p>
</div>
</div>
</template>
</div>
@@ -144,7 +160,12 @@
<slot name="help" />
</template>
<template #error>
<slot name="error" />
<!-- If we have a specific error for this block, show it -->
<div v-if="props.error" class="text-sm text-red-500 mt-1">
{{ props.error }}
</div>
<!-- Otherwise, show the default error slot -->
<slot v-else name="error" />
</template>
</InputWrapper>
</template>
@@ -156,7 +177,6 @@ import InputWrapper from './components/InputWrapper.vue'
import { loadStripe } from '@stripe/stripe-js'
import { StripeElements, StripeElement } from 'vue-stripe-js'
import stripeCurrencies from "~/data/stripe_currencies.json"
import { useStripeElements } from '~/composables/useStripeElements'
import { useAlert } from '~/composables/useAlert'
import { useFeatureFlag } from '~/composables/useFeatureFlag'
@@ -168,20 +188,12 @@ const props = defineProps({
oauthProviderId: { type: [String, Number], default: null },
isAdminPreview: { type: Boolean, default: false },
color: { type: String, default: '#000000' },
isDark: { type: Boolean, default: false }
isDark: { type: Boolean, default: false },
paymentData: { type: Object, default: null }
})
const emit = defineEmits([])
const { compVal, hasError, inputWrapperProps } = useFormInput(props, { emit })
const stripeElements = useStripeElements()
const {
state: stripeState,
prepareStripeState,
setStripeInstance,
setElementsInstance,
setCardElement,
setBillingDetails
} = stripeElements || {}
const route = useRoute()
const alert = useAlert()
@@ -189,23 +201,31 @@ const alert = useAlert()
const publishableKey = computed(() => {
return useFeatureFlag('billing.stripe_publishable_key', '')
})
const card = ref(null)
const stripeElementsRef = ref(null)
const cardHolderName = ref('')
const cardHolderEmail = ref('')
const isCardFocused = ref(false)
// Keep the flag for Stripe.js loading but remove manual instance creation
const isStripeJsLoaded = ref(false)
// Get Stripe elements from paymentData
const stripeElements = computed(() => props.paymentData?.stripeElements)
const stripeState = computed(() => stripeElements.value?.state || {})
const setStripeInstance = computed(() => stripeElements.value?.setStripeInstance)
const setElementsInstance = computed(() => stripeElements.value?.setElementsInstance)
const setCardElement = computed(() => stripeElements.value?.setCardElement)
const setBillingDetails = computed(() => stripeElements.value?.setBillingDetails)
const prepareStripeState = computed(() => stripeElements.value?.prepareStripeState)
// Computed to determine if we should show success state
const showSuccessState = computed(() => {
return stripeState?.intentId || (compVal.value && isPaymentIntentId(compVal.value))
return stripeState.value?.intentId || (compVal.value && isPaymentIntentId(compVal.value))
})
// Computed to determine if we should always show preview message in editor
const shouldShowPreviewMessage = computed(() => {
return props.isAdminPreview && (!formSlug.value || !stripeState || !stripeElements)
return props.isAdminPreview && stripeState.value?.showPreviewMessage
})
// Helper function to check if a string looks like a Stripe payment intent ID
@@ -216,87 +236,120 @@ const isPaymentIntentId = (value) => {
// Initialize Stripe.js if needed
onMounted(async () => {
try {
// Validate publishable key
if (!publishableKey.value || typeof publishableKey.value !== 'string' || publishableKey.value.trim() === '') {
if (stripeState) {
stripeState.isLoadingAccount = false
stripeState.hasAccountLoadingError = true
stripeState.errorMessage = 'Missing Stripe configuration. Please check your settings.'
}
return
}
console.debug('[PaymentInput] Mounting with:', {
oauthProviderId: props.oauthProviderId,
hasPaymentData: !!props.paymentData,
publishableKey: publishableKey.value,
stripeElementsInstance: !!stripeElements.value
})
// We'll check if Stripe is already available globally
if (typeof window !== 'undefined' && !window.Stripe) {
// Initialize Stripe.js globally first if needed
if (typeof window !== 'undefined' && !window.Stripe && publishableKey.value) {
console.debug('[PaymentInput] Loading Stripe.js with key:', publishableKey.value)
await loadStripe(publishableKey.value)
isStripeJsLoaded.value = true
} else {
} else if (typeof window !== 'undefined' && window.Stripe) {
isStripeJsLoaded.value = true
}
console.debug('[PaymentInput] Stripe.js loaded status:', isStripeJsLoaded.value)
// If stripeElements or stripeState is not available, we need to handle that
if (!stripeElements || !stripeState) {
console.warn('Stripe elements provider not found or not properly initialized.')
// Skip initialization if missing essential data
if (!props.oauthProviderId || !props.paymentData || !publishableKey.value) {
console.debug('[PaymentInput] Skipping initialization - missing requirements:', {
oauthProviderId: props.oauthProviderId,
paymentData: !!props.paymentData,
publishableKey: !!publishableKey.value
})
// Set error state if publishable key is missing
if (!publishableKey.value && stripeState.value) {
stripeState.value.hasAccountLoadingError = true
stripeState.value.errorMessage = 'Missing Stripe configuration. Please check your settings.'
}
return
}
// If compVal already contains a payment intent ID, sync it to stripeState
if (compVal.value && isPaymentIntentId(compVal.value) && stripeState) {
stripeState.intentId = compVal.value
if (compVal.value && isPaymentIntentId(compVal.value) && stripeState.value) {
console.debug('[PaymentInput] Syncing existing payment intent:', compVal.value)
stripeState.value.intentId = compVal.value
}
// For unsaved forms in admin preview, show the preview message
if (props.isAdminPreview && !formSlug.value && stripeState) {
stripeState.isLoadingAccount = false
stripeState.showPreviewMessage = true
return
}
// Fetch account but don't manually create Stripe instance
// Fetch account details from the API, even in preview mode
const slug = formSlug.value
if (slug && props.oauthProviderId && prepareStripeState) {
const result = await prepareStripeState(slug, props.oauthProviderId, props.isAdminPreview)
if (slug && props.oauthProviderId && prepareStripeState.value) {
console.debug('[PaymentInput] Preparing Stripe state with:', {
slug,
oauthProviderId: props.oauthProviderId,
isAdminPreview: props.isAdminPreview
})
const result = await prepareStripeState.value(slug, props.oauthProviderId, props.isAdminPreview)
console.debug('[PaymentInput] Stripe state preparation result:', result)
if (!result.success && result.message && !result.requiresSave) {
// Show error only if it's not the "Save the form" message
alert.error(result.message)
}
} else if (props.isAdminPreview && stripeState) {
// If we're in admin preview and any required parameter is missing, show preview message
stripeState.isLoadingAccount = false
stripeState.showPreviewMessage = true
}
} catch (error) {
console.error('[PaymentInput] Stripe initialization error:', error)
if (stripeState.value) {
stripeState.value.hasAccountLoadingError = true
stripeState.value.errorMessage = 'Failed to initialize Stripe. Please refresh and try again.'
}
alert.error('Failed to initialize Stripe. Please refresh and try again.')
}
})
// Watch for provider ID changes
watch(() => props.oauthProviderId, async (newVal, oldVal) => {
if (newVal && newVal !== oldVal && prepareStripeState) {
if (newVal && newVal !== oldVal && prepareStripeState.value) {
const slug = formSlug.value
if (slug) {
await prepareStripeState(slug, newVal, props.isAdminPreview)
await prepareStripeState.value(slug, newVal, props.isAdminPreview)
}
}
})
// Update onStripeReady to always use the stripe instance from the component
// Update onStripeReady to use the computed methods
const onStripeReady = ({ stripe, elements }) => {
console.debug('[PaymentInput] onStripeReady called with:', {
hasStripe: !!stripe,
hasElements: !!elements,
setStripeInstance: !!setStripeInstance.value,
setElementsInstance: !!setElementsInstance.value
})
if (!stripe) {
console.warn('[PaymentInput] No Stripe instance in onStripeReady')
return
}
if (setStripeInstance) {
setStripeInstance(stripe)
if (setStripeInstance.value) {
console.debug('[PaymentInput] Setting Stripe instance')
setStripeInstance.value(stripe)
} else {
console.warn('[PaymentInput] No setStripeInstance method available')
}
if (elements && setElementsInstance) {
setElementsInstance(elements)
if (elements && setElementsInstance.value) {
console.debug('[PaymentInput] Setting Elements instance')
setElementsInstance.value(elements)
} else {
console.warn('[PaymentInput] Missing elements or setElementsInstance')
}
}
const onStripeError = (_error) => {
alert.error('Failed to load payment component. Please check configuration or refresh.')
const onStripeError = (error) => {
console.error('[PaymentInput] Stripe initialization error:', error)
const errorMessage = error?.message || 'Failed to load payment component'
alert.error('Failed to load payment component. ' + errorMessage)
if (stripeState.value) {
stripeState.value.hasAccountLoadingError = true
stripeState.value.errorMessage = errorMessage + '. Please check configuration or refresh.'
}
}
// Card focus/blur event handlers
@@ -309,30 +362,41 @@ const onCardBlur = () => {
}
const onCardReady = (_element) => {
if (card.value?.stripeElement) {
if (setCardElement) {
setCardElement(card.value.stripeElement)
}
console.debug('[PaymentInput] Card ready:', {
hasCardRef: !!card.value,
hasStripeElement: !!card.value?.stripeElement,
hasSetCardElement: !!setCardElement.value
})
if (card.value?.stripeElement && setCardElement.value) {
console.debug('[PaymentInput] Setting card element')
setCardElement.value(card.value.stripeElement)
} else {
console.warn('[PaymentInput] Cannot set card element - missing dependencies')
}
}
// Billing details
watch(cardHolderName, (newValue) => {
setBillingDetails({ name: newValue })
if (setBillingDetails.value) {
setBillingDetails.value({ name: newValue })
}
})
watch(cardHolderEmail, (newValue) => {
setBillingDetails({ email: newValue })
if (setBillingDetails.value) {
setBillingDetails.value({ email: newValue })
}
})
// Payment intent sync
watch(() => stripeState?.intentId, (newValue) => {
watch(() => stripeState.value?.intentId, (newValue) => {
if (newValue) compVal.value = newValue
})
watch(compVal, (newValue) => {
if (newValue && stripeState && newValue !== stripeState.intentId) {
stripeState.intentId = newValue
if (newValue && stripeState.value && newValue !== stripeState.value.intentId) {
stripeState.value.intentId = newValue
}
}, { immediate: true })
@@ -351,7 +415,6 @@ const currencySymbol = computed(() => {
})
const cardOptions = computed(() => {
// Extract placeholder color from theme
const darkPlaceholderColor = props.theme.default?.input?.includes('dark:placeholder-gray-500') ? '#6B7280' : '#9CA3AF'
const lightPlaceholderColor = props.theme.default?.input?.includes('placeholder-gray-400') ? '#9CA3AF' : '#A0AEC0'
@@ -378,7 +441,6 @@ const cardOptions = computed(() => {
})
const formSlug = computed(() => {
// Return the slug from route params regardless of route name
if (route.params && route.params.slug) {
return route.params.slug
}
@@ -393,7 +455,9 @@ const resetCard = async () => {
if (stripeElementsRef.value?.elements) {
card.value.stripeElement.mount(stripeElementsRef.value.elements)
setCardElement(card.value.stripeElement)
if (setCardElement.value) {
setCardElement.value(card.value.stripeElement)
}
} else {
console.error('Cannot remount card, Stripe Elements instance not found.')
}
@@ -403,14 +467,21 @@ const resetCard = async () => {
// Add watcher to check when stripeElementsRef becomes available for fallback access
watch(() => stripeElementsRef.value, async (newRef) => {
if (newRef) {
console.debug('[PaymentInput] StripeElementsRef updated:', {
hasInstance: !!newRef.instance,
hasElements: !!newRef.elements
})
// If @ready event hasn't fired, try accessing the instance directly
if (newRef.instance && setStripeInstance && !stripeState.isStripeInstanceReady) {
setStripeInstance(newRef.instance)
if (newRef.instance && setStripeInstance.value && !stripeState.value?.isStripeInstanceReady) {
console.debug('[PaymentInput] Setting Stripe instance from ref')
setStripeInstance.value(newRef.instance)
}
if (newRef.elements && setElementsInstance) {
setElementsInstance(newRef.elements)
if (newRef.elements && setElementsInstance.value) {
console.debug('[PaymentInput] Setting Elements instance from ref')
setElementsInstance.value(newRef.elements)
}
}
}, { immediate: true })
</script>
</script>

View File

@@ -84,7 +84,7 @@ export default {
if (props.nativeType !== "file") return
const file = event.target.files[0]
// eslint-disable-next-line vue/no-mutating-props
props.form[props.name] = file
}

View File

@@ -138,7 +138,7 @@ const resizeIframe = (height) => {
try {
window.parentIFrame?.size(height)
} catch (e) {
} catch {
// Silently handle error
}
}

View File

@@ -0,0 +1,83 @@
<template>
<div v-if="isCaptchaRequired" class="mb-3 px-2 mt-4 mx-auto w-max">
<ClientOnly>
<CaptchaInput
ref="captchaInputRef"
:provider="provider"
:form="form"
:language="language"
:dark-mode="darkMode"
/>
<template #fallback>
<USkeleton class="h-[78px] w-[304px]" />
</template>
</ClientOnly>
</div>
</template>
<script setup>
import CaptchaInput from './CaptchaInput.vue'
import { computed, ref, watch } from 'vue'
const props = defineProps({
formManager: {
type: Object,
required: true
}
})
const captchaInputRef = ref(null)
const runtimeConfig = useRuntimeConfig().public
// Get form and config from the formManager
const form = computed(() => props.formManager.form)
const config = computed(() => props.formManager.config.value)
const structure = computed(() => props.formManager.structure)
const isLastPage = computed(() => structure.value?.isLastPage.value ?? true)
const language = computed(() => config.value?.language || 'en')
const provider = computed(() => config.value?.captcha_provider || 'recaptcha')
const darkMode = computed(() => props.formManager.darkMode.value)
// Determine if captcha should be shown
const isCaptchaRequired = computed(() => {
if (!config.value?.use_captcha || !isLastPage.value) {
return false
}
const captchaProvider = config.value.captcha_provider
if (captchaProvider === 'recaptcha') {
return !!runtimeConfig.recaptchaSiteKey
} else if (captchaProvider === 'hcaptcha') {
return !!runtimeConfig.hCaptchaSiteKey
}
return false
})
// Get field name based on provider
const captchaFieldName = computed(() => {
return provider.value === 'recaptcha'
? 'g-recaptcha-response'
: 'h-captcha-response'
})
// Reset captcha when page changes
watch(() => props.formManager.state.currentPage, () => {
if (captchaInputRef.value) {
captchaInputRef.value.reset()
}
})
// Simplified watcher for form submission
watch(() => props.formManager.state.isProcessing, (isProcessing, wasProcessing) => {
// Case 1: Form is starting to process and captcha is required but missing
if (isProcessing && isCaptchaRequired.value && !form.value[captchaFieldName.value]) {
form.value.errors.set(captchaFieldName.value, 'Please complete the captcha verification')
}
// Case 2: Form submission just ended AND there are errors
if (!isProcessing && wasProcessing && form.value.errors.any() && captchaInputRef.value) {
// Reset the captcha when validation fails
captchaInputRef.value.reset()
}
})
</script>

View File

@@ -148,7 +148,7 @@ const renderHcaptcha = async () => {
'open-callback': () => emit('opened'),
'close-callback': () => emit('closed')
})
} catch (error) {
} catch {
scriptLoadPromise = null // Reset promise on error
}
}
@@ -162,7 +162,7 @@ onBeforeUnmount(() => {
if (window.hcaptcha && widgetId !== null) {
try {
window.hcaptcha.remove(widgetId)
} catch (e) {
} catch {
// Silently handle error
}
}
@@ -179,6 +179,17 @@ onBeforeUnmount(() => {
// Expose reset method that properly reloads the captcha
defineExpose({
reset: async () => {
if (window.hcaptcha && widgetId !== null) {
try {
// Use the official API to reset the captcha widget
window.hcaptcha.reset(widgetId)
return true
} catch (error) {
console.error('Error resetting hCaptcha, falling back to re-render', error)
}
}
// Fall back to full re-render if reset fails or hcaptcha isn't available
cleanupHcaptcha()
await renderHcaptcha()
}

View File

@@ -129,7 +129,7 @@ const renderRecaptcha = async () => {
}
}
})
} catch (error) {
} catch {
scriptLoadPromise = null // Reset promise on error
}
}
@@ -143,7 +143,7 @@ onBeforeUnmount(() => {
if (window.grecaptcha && widgetId !== null) {
try {
window.grecaptcha.reset(widgetId)
} catch (e) {
} catch {
// Silently handle error
}
}
@@ -164,16 +164,15 @@ defineExpose({
try {
// Try simple reset first
window.grecaptcha.reset(widgetId)
} catch (e) {
// If simple reset fails, do a full cleanup and reload
cleanupRecaptcha()
await renderRecaptcha()
return true
} catch (error) {
console.error('Error resetting reCAPTCHA, falling back to re-render', error)
}
} else {
// If no widget exists, do a full reload
cleanupRecaptcha()
await renderRecaptcha()
}
// If simple reset fails or no widget exists, do a full reload
cleanupRecaptcha()
await renderRecaptcha()
}
})
</script>