Beautiful Open-Source Form Builder
<template>
<div
v-if="form"
class="open-complete-form flex flex-col min-h-full"
:inert="isRestoringDraft || undefined"
:aria-busy="isRestoringDraft || undefined"
:dir="form?.layout_rtl ? 'rtl' : 'ltr'"
:style="formStyle"
>
<ClientOnly>
<LazyOpenFormsComponentsSdkBridgeHost
v-if="shouldLoadSdkBridge"
:form="form"
:form-manager="formManager"
:dark-mode="darkMode"
@ready="handleSdkBridgeReady"
/>
</ClientOnly>
<v-transition name="fade" mode="out-in">
<div v-if="isAutoSubmit" key="auto-submit" class="text-center p-6">
<Loader class="h-6 w-6 text-blue-500 mx-auto" />
</div>
<component
v-else-if="form && formManager && form"
:key="'form'+form.presentation_style"
:is="FormComponent"
:form-manager="formManager"
@submit="triggerSubmit"
class="flex flex-col grow"
>
<template #password v-if="isPublicFormPage && form.is_password_protected" >
<div class="w-full">
<div class="form-group flex flex-wrap w-full max-w-sm mx-auto">
<div class="relative w-full px-2">
<text-input :form="passwordForm" name="password" native-type="password" label="Password" :help="t('forms.password_protected')" @keydown.enter.prevent="passwordEntered" />
</div>
</div>
<div class="flex flex-wrap justify-center w-full text-center">
<open-form-button :form="form" class="my-4 px-8" @click="passwordEntered">
{{ t('forms.submit') }}
</open-form-button>
</div>
</div>
</template>
<template
#alerts
v-if="isPublicFormPage && (form.is_closed || form.visibility=='closed' || form.max_number_of_submissions_reached)"
>
<LazyUAlert
v-if="form.is_closed || form.visibility=='closed'"
icon="i-heroicons-lock-closed-20-solid"
color="warning"
variant="subtle"
class="m-2 my-4"
>
<template #description>
<div class="break-words whitespace-break-spaces" v-html="form.closed_text" />
</template>
</LazyUAlert>
<LazyUAlert
v-else
icon="i-heroicons-lock-closed-20-solid"
color="warning"
variant="subtle"
class="m-2 my-4"
>
<template #description>
<div class="break-words whitespace-break-spaces" v-html="form.max_submissions_reached_text" />
</template>
</LazyUAlert>
</template>
<template #cleanings>
<component
:is="FormCleanings"
v-if="shouldShowFormCleanings"
:hideable="true"
class="mb-4 mx-2"
:form="form"
:specify-form-owner="true"
:use-cookie-dismissal="true"
/>
</template>
<!-- Submitted view provided to renderer -->
<template #after-submit>
<TextBlock
v-if="form.submitted_text"
class="form-description text-neutral-700 dark:text-neutral-300 whitespace-pre-wrap"
:content="form.submitted_text"
:mentions-allowed="true"
:form="form"
:form-data="submittedData"
/>
<div class="flex flex-col w-full gap-2 mt-4">
<div class="flex gap-2 items-center">
<open-form-button
v-if="pdfDownloadEnabled"
:form="form"
icon="i-heroicons-document-arrow-down"
native-type="button"
@click="downloadPdf"
>
{{ form.pdf_download_button_text || t('forms.buttons.download_pdf', 'Download PDF') }}
</open-form-button>
<open-form-button
v-if="form.re_fillable"
:form="form"
icon="i-lucide-rotate-ccw"
@click="restart"
>
{{ form.re_fill_button_text || t('forms.buttons.re_fill') }}
</open-form-button>
<open-form-button
v-if="form.editable_submissions && submissionId"
:form="form"
@click="editSubmission"
>
{{ form.editable_submissions_button_text }}
</open-form-button>
</div>
</div>
</template>
</component>
</v-transition>
<template v-if="!isAutoSubmit">
<component
:is="FirstSubmissionModal"
v-if="showFirstSubmissionModal"
:show="true"
:form="form"
@close="showFirstSubmissionModal=false"
/>
</template>
</div>
</template>
<script setup>
import { useFormManager } from '~/lib/forms/composables/useFormManager'
import { FormMode } from "~/lib/forms/FormModeStrategy.js"
import OpenFormButton from './OpenFormButton.vue'
import VTransition from '~/components/global/transitions/VTransition.vue'
import { useForm } from '~/composables/useForm'
import { useAlert } from '~/composables/useAlert'
import { useI18n } from 'vue-i18n'
import { useIsIframe } from '~/composables/useIsIframe'
import Loader from '~/components/global/Loader.vue'
import { tailwindcssPaletteGenerator } from '~/lib/colors.js'
import { useRouter } from 'vue-router'
import { clearFormatterCache } from '~/components/forms/components/FormSubmissionFormatter.js'
import { clearLoadedMentionCache } from '~/lib/forms/mention-parser-loader.js'
const OpenForm = defineAsyncComponent(() => import('./OpenForm.vue'))
const OpenFormFocused = defineAsyncComponent(() => import('./OpenFormFocused.vue'))
const FormCleanings = defineAsyncComponent(() => import('../../pages/forms/show/FormCleanings.vue'))
const FirstSubmissionModal = defineAsyncComponent(() => import('~/components/open/forms/components/FirstSubmissionModal.vue'))
const props = defineProps({
form: { type: Object, required: true },
mode: {
type: String,
default: FormMode.LIVE,
validator: (value) => Object.values(FormMode).includes(value)
},
darkMode: {
type: Boolean,
default: false
}
})
const emit = defineEmits(['submitted', 'password-entered', 'restarted'])
const { t, setLocale } = useI18n()
const route = useRoute()
const router = useRouter()
const nuxtApp = useNuxtApp()
const alert = useAlert()
const workingFormStore = shallowRef(null)
const passwordForm = useForm({ password: null })
// Removed unused hidePasswordDisabledMsg (was always false and unused)
// submission_id is a public UUID identifier
const submissionId = ref(route.query.submission_id || null)
const pdfDownloadUrl = ref(null)
// Match SSR markup while keeping browser-only draft restoration non-interactive.
const isRestoringDraft = ref(!!props.form.auto_save && !submissionId.value)
const submittedData = ref(null)
const showFirstSubmissionModal = ref(false)
const getUrlParams = () => {
const params = new URLSearchParams()
Object.entries(route.query).forEach(([key, value]) => {
const values = Array.isArray(value) ? value : [value]
values.forEach(value => params.append(key, value ?? ''))
})
return params
}
// Check for auto_submit parameter during setup
const isAutoSubmit = ref(getUrlParams().get('auto_submit') === 'true')
// Create a reactive reference directly from the prop
const darkModeRef = toRef(props, 'darkMode')
// Create a reactive reference for the mode prop
const modeRef = toRef(props, 'mode')
// Provide theme context for components outside OpenForm (password input, TextBlock)
provide('formTheme', computed(() => props.form.theme || 'default'))
provide('formSize', computed(() => props.form.size || 'md'))
provide('formBorderRadius', computed(() => props.form.border_radius || 'small'))
provide('formPresentationStyle', computed(() => props.form.presentation_style || 'classic'))
let formManager = null
let restoreDraftAfterHydration = false
let draftRestoration = Promise.resolve()
const sdkBridge = shallowRef(null)
let resolveSdkBridgeReady
const sdkBridgeReady = new Promise((resolve) => {
resolveSdkBridgeReady = resolve
})
if (props.form) {
formManager = useFormManager(props.form, props.mode, {
darkMode: darkModeRef,
mode: modeRef
})
// Hydrate the server's answers first. Browser-only drafts must update mounted
// controls, rather than hydrating a different value into the server's markup.
restoreDraftAfterHydration = import.meta.client && nuxtApp.isHydrating &&
!submissionId.value && formManager.pendingSubmission.enabled.value
if (restoreDraftAfterHydration) {
formManager.pendingSubmission.pauseAutosave()
draftRestoration = new Promise((resolve) => {
const removeHook = nuxtApp.hooks.hookOnce('app:suspense:resolve', () => {
formManager.restorePendingSubmission()
formManager.startBackgroundSync()
restoreDraftAfterHydration = false
isRestoringDraft.value = false
resolve()
})
onBeforeUnmount(removeHook)
})
}
// Await initialization so SSR includes form structure and fields
await formManager.initialize({
submissionId: submissionId.value,
urlParams: getUrlParams(),
skipPendingSubmission: restoreDraftAfterHydration,
deferBackgroundSync: restoreDraftAfterHydration,
})
if (import.meta.client && !restoreDraftAfterHydration) isRestoringDraft.value = false
}
// Watch for changes to the form prop and update formManager
watch(() => props.form, (newForm) => {
// Only update if the form has changed and formManager is initialized
if (formManager && newForm) {
// Update form manager with the new config
formManager.updateConfig(newForm, {
submissionId: submissionId.value,
urlParams: getUrlParams(),
})
}
})
// Keep the builder's structureService in sync whenever admin preview is on and the adapter changes
watch([
() => formManager?.strategy?.value?.admin?.showAdminControls,
() => formManager?.structure?.value
], ([showAdminControls, struct]) => {
if (!showAdminControls || !struct) return
import('~/stores/working_form').then(({ useWorkingFormStore }) => {
workingFormStore.value ||= nuxtApp.runWithContext(() => useWorkingFormStore())
workingFormStore.value.setStructureService(struct)
})
}, { immediate: true })
// Add a watcher to update formManager's darkMode whenever darkModeRef changes
watch(darkModeRef, (newDarkMode) => {
if (formManager) {
formManager.setDarkMode(newDarkMode)
}
})
// If auto_submit is true, trigger submit after component is mounted
onMounted(() => {
if (isAutoSubmit.value && formManager) {
// Using nextTick to ensure form is fully rendered and initialized
nextTick(async () => {
await draftRestoration
const bridge = shouldLoadSdkBridge.value ? await sdkBridgeReady : null
await bridge?.waitForHandshake?.()
triggerSubmit()
})
}
})
const isPublicFormPage = computed(() => {
return route.name === 'forms-slug'
})
const shouldLoadSdkBridge = computed(() => {
if (!isPublicFormPage.value) return false
const workspaceCustomCode = props.form?.workspace?.settings?.custom_code
return useIsIframe() || !!workspaceCustomCode || !!props.form?.custom_code
})
const handleSdkBridgeReady = (bridge) => {
sdkBridge.value = bridge
resolveSdkBridgeReady(bridge)
}
const callSdkBridge = (method, ...args) => {
if (!shouldLoadSdkBridge.value) return Promise.resolve()
if (sdkBridge.value) {
sdkBridge.value[method]?.(...args)
return Promise.resolve()
}
return sdkBridgeReady.then((bridge) => bridge?.[method]?.(...args))
}
const getFontUrl = computed(() => {
if(!props.form?.font_family) return null
const family = props.form.font_family.replace(/ /g, '+')
return `https://fonts.googleapis.com/css?family=${family}:wght@400,500,700,800,900&display=swap`
})
const isFormOwner = computed(() => {
return props.form?.viewer_is_form_creator === true
})
const isProcessing = computed(() => formManager?.state.isProcessing ?? false)
const showFormCleanings = computed(() => formManager?.strategy.value.display.showFormCleanings ?? false)
const shouldShowFormCleanings = computed(() => (
showFormCleanings.value &&
isFormOwner.value &&
Object.keys(props.form?.cleanings || {}).length > 0
))
const showFontLink = computed(() => formManager?.strategy.value.display.showFontLink ?? false)
const formStyle = computed(() => {
const shouldUseContainerHeight = [FormMode.PREVIEW, FormMode.TEST, FormMode.TEMPLATE].includes(props.mode)
const baseStyle = {
'--font-family': props.form.font_family,
'direction': props.form?.layout_rtl ? 'rtl' : 'ltr',
'--form-color': props.form.color,
'--color-form': props.form.color,
'--form-focused-step-height': shouldUseContainerHeight ? '100%' : '100svh'
}
// Generate color palette variants
if (props.form.color) {
const colorPalette = tailwindcssPaletteGenerator(props.form.color).primary
Object.entries(colorPalette).forEach(([shade, colorValue]) => {
baseStyle[`--color-form-${shade}`] = colorValue
})
}
return baseStyle
})
const FormComponent = computed(() => {
return props.form?.presentation_style === 'focused' ? OpenFormFocused : OpenForm
})
// Conditionally add font link to the page head (SSR-friendly)
useHead({
link: computed(() =>
(showFontLink.value && props.form?.font_family && getFontUrl.value) ? [
{
key: `form-font-${props.form.font_family}`,
rel: 'stylesheet',
href: getFontUrl.value,
crossorigin: 'anonymous',
referrerpolicy: 'no-referrer'
}
] : []
)
})
const formLocale = computed(() => {
return typeof props.form?.language === 'string' && props.form.language ? props.form.language : 'en'
})
// Nuxt i18n loads messages asynchronously. Resolve the initial language before
// SSR and hydration render the form, including the matching Nuxt UI locale.
await setLocale(formLocale.value)
watch(formLocale, (language) => setLocale(language))
onBeforeUnmount(() => {
setLocale('en')
// Clear caches for this form to prevent memory leaks
clearFormatterCache(props.form?.slug)
clearLoadedMentionCache()
})
const handleScrollToError = () => {
if (import.meta.server) return
nextTick(() => {
const firstErrorElement = document.querySelector('.form-group [error], .form-group .has-error')
if (firstErrorElement) {
const headerOffset = 60 // Offset for fixed headers, adjust as needed
const elementPosition = firstErrorElement.getBoundingClientRect().top
const offsetPosition = elementPosition + window.scrollY - headerOffset
window.scrollTo({
top: offsetPosition,
behavior: 'smooth'
})
}
})
}
const triggerSubmit = () => {
if (restoreDraftAfterHydration) return draftRestoration.then(triggerSubmit)
if (!formManager || isProcessing.value) return
// Emit SDK submitStart event
callSdkBridge('onSubmitStart')
formManager.submit({
submissionId: submissionId.value
}).then(result => {
if (result) {
submittedData.value = formManager.form.data()
pdfDownloadUrl.value = result.pdf_download_url || null
if (result?.submission_id) {
submissionId.value = result.submission_id
}
// Emit SDK submit success event
callSdkBridge('onSubmitSuccess', {
data: submittedData.value,
submissionId: result?.submission_id,
completionTime: result?.completion_time
})
if (isFormOwner.value && !useIsIframe() && result?.is_first_submission) {
showFirstSubmissionModal.value = true
}
emit('submitted', true)
// Ensure the submitted view starts at the top (parity with page change scroll)
if (import.meta.client) {
window.scrollTo({ top: 0, behavior: 'smooth' })
}
} else {
console.warn('Form submission failed via composable, but no error thrown?')
alert.error(t('forms.submission_error'))
}
})
.catch(error => {
console.error(error)
// Emit SDK submit error event
const errors = error.data?.errors || error.data || { general: error.message }
callSdkBridge('onSubmitError', errors)
if (error.response && error.response.status === 422 && error.data) {
alert.formValidationError(error.data)
} else if (error.message) {
alert.error(error.message)
}
handleScrollToError()
}).finally(() => {
isAutoSubmit.value = false
})
}
const restart = async () => {
if (!formManager) return
submittedData.value = null
submissionId.value = null
pdfDownloadUrl.value = null
const urlParams = getUrlParams()
// Determine if we should clear the form completely for a fresh start
const shouldClearUrl = props.form.editable_submissions
if (shouldClearUrl) {
// Remove submission_id parameter and navigate to clean URL
urlParams.delete('submission_id')
const newQueryString = urlParams.toString()
const newPath = newQueryString ? `${route.path}?${newQueryString}` : route.path
await router.replace(newPath)
}
// Single restart call with conditional options
await formManager.restart({
urlParams: shouldClearUrl ? new URLSearchParams() : urlParams,
submissionId: null,
skipUrlParams: shouldClearUrl
})
// Emit SDK reset event
callSdkBridge('onReset')
emit('restarted', true)
}
// The completed submission response supplies a signed URL for this respondent.
const pdfDownloadEnabled = computed(() => (
!!props.form.pdf_download_enabled && !!pdfDownloadUrl.value
))
const downloadPdf = () => {
if (!pdfDownloadEnabled.value) return
// Keep navigation synchronous with the click to avoid popup blocking.
window.open(pdfDownloadUrl.value, '_blank', 'noopener,noreferrer')
}
const editSubmission = () => {
const editUrl = props.form.share_url + '?submission_id=' + submissionId.value
window.parent.location.href = editUrl
}
const addPasswordError = (msg) => {
passwordForm.errors.set('password', msg)
}
// Inject password error from parent
const passwordError = inject('passwordError', ref(null))
// Watch for password error from parent and display it
watch(passwordError, (errorMsg) => {
if (errorMsg) {
addPasswordError(errorMsg)
}
}, { immediate: true })
const passwordEntered = () => {
if (passwordForm.password) {
emit('password-entered', passwordForm.password)
} else {
addPasswordError(t('forms.password_required'))
}
}
defineExpose({
restart,
formManager
})
</script>
<style lang="scss">
.open-complete-form {
* {
font-family: var(--font-family, Inter, sans-serif) !important;
}
}
</style>