The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(marketing): reusable MarketingForm with HubSpot/Customer.io/Notion fan-out (#45605)
Alan Daniel701f1602c6e5
diff --git a/apps/www/_go/lead-gen/aws-activate-offer.tsx b/apps/www/_go/lead-gen/aws-activate-offer.tsxindex e00782d7494..1c141c56909 100644--- a/apps/www/_go/lead-gen/aws-activate-offer.tsx+++ b/apps/www/_go/lead-gen/aws-activate-offer.tsx@@ -1,7 +1,6 @@+import { HubSpotFormEmbed } from 'marketing'import type { GoPageInput } from 'marketing'-import HubSpotFormEmbed from './components/HubSpotFormEmbed'-const page: GoPageInput = {template: 'lead-gen',slug: 'aws-activate-offer',@@ -110,7 +109,7 @@ const page: GoPageInput = {id: 'form',title: 'Apply for your credits',children: (- <div className="mx-auto w-full max-w-2xl border border-muted rounded-2xl p-6 sm:p-8">+ <div className="mx-auto w-full max-w-2xl border border-muted rounded-2xl overflow-hidden"><HubSpotFormEmbed portalId="19953346" formId="db2718f8-1f23-4fe1-aaab-b4924dc4ca54" /></div>),diff --git a/apps/www/_go/lead-gen/components/HubSpotFormEmbed.tsx b/apps/www/_go/lead-gen/components/HubSpotFormEmbed.tsxdeleted file mode 100644index 159cb31ebc2..00000000000--- a/apps/www/_go/lead-gen/components/HubSpotFormEmbed.tsx+++ /dev/null@@ -1,92 +0,0 @@-'use client'--import { useEffect, useId } from 'react'--declare global {- interface Window {- hbspt?: {- forms: {- create: (config: { portalId: string; formId: string; target: string }) => void- }- }- }-}--const HUBSPOT_SCRIPT_SRC = 'https://js.hsforms.net/forms/embed/v2.js'--function loadHubSpotScript(): Promise<void> {- return new Promise((resolve, reject) => {- if (window.hbspt) {- resolve()- return- }-- const existing = document.querySelector<HTMLScriptElement>(- `script[src="${HUBSPOT_SCRIPT_SRC}"]`- )- if (existing) {- existing.addEventListener('load', () => resolve(), { once: true })- existing.addEventListener(- 'error',- () => reject(new Error('Failed to load HubSpot form script')),- {- once: true,- }- )- return- }-- const script = document.createElement('script')- script.src = HUBSPOT_SCRIPT_SRC- script.async = true- script.defer = true- script.onload = () => resolve()- script.onerror = () => reject(new Error('Failed to load HubSpot form script'))- document.body.appendChild(script)- })-}--export default function HubSpotFormEmbed({- portalId,- formId,-}: {- portalId: string- formId: string-}) {- const targetId = `hubspot-form-${useId().replace(/:/g, '-')}`-- useEffect(() => {- let cancelled = false-- const mountForm = async () => {- try {- await loadHubSpotScript()- if (cancelled || !window.hbspt) return-- const target = document.getElementById(targetId)- if (!target) return-- // Reset target to avoid duplicate forms on remounts.- while (target.firstChild) {- target.removeChild(target.firstChild)- }-- window.hbspt.forms.create({- portalId,- formId,- target: `#${targetId}`,- })- } catch (error) {- console.error('[go/hubspot] Failed to initialize HubSpot form embed', error)- }- }-- mountForm()-- return () => {- cancelled = true- }- }, [formId, portalId, targetId])-- return <div id={targetId} />-}diff --git a/packages/marketing/index.ts b/packages/marketing/index.tsindex 8f286a47185..7d1cd84017d 100644--- a/packages/marketing/index.ts+++ b/packages/marketing/index.ts@@ -1 +1,2 @@export * from './src/go'+export * from './src/forms'diff --git a/packages/marketing/src/forms/HubSpotFormEmbed.tsx b/packages/marketing/src/forms/HubSpotFormEmbed.tsxnew file mode 100644index 00000000000..d6fd62eec76--- /dev/null+++ b/packages/marketing/src/forms/HubSpotFormEmbed.tsx@@ -0,0 +1,164 @@+'use client'++import { useEffect, useId, useRef, useState } from 'react'++interface HubSpotFormCreateConfig {+ portalId: string+ formId: string+ region?: string+ target: string+ cssClass?: string+}++declare global {+ interface Window {+ hbspt?: {+ forms: {+ create: (config: HubSpotFormCreateConfig) => void+ }+ }+ }+}++const HUBSPOT_SCRIPT_SRC = 'https://js.hsforms.net/forms/embed/v2.js'++let scriptPromise: Promise<void> | null = null++function loadHubSpotScript(): Promise<void> {+ if (typeof window === 'undefined') {+ return Promise.reject(new Error('HubSpot script can only load in the browser'))+ }+ if (window.hbspt) return Promise.resolve()+ if (scriptPromise) return scriptPromise++ scriptPromise = new Promise<void>((resolve, reject) => {+ const existing = document.querySelector<HTMLScriptElement>(+ `script[src="${HUBSPOT_SCRIPT_SRC}"]`+ )+ if (existing) {+ existing.addEventListener('load', () => resolve(), { once: true })+ existing.addEventListener('error', () => reject(new Error('HubSpot script failed to load')), {+ once: true,+ })+ return+ }++ const script = document.createElement('script')+ script.src = HUBSPOT_SCRIPT_SRC+ script.async = true+ script.defer = true+ script.onload = () => resolve()+ script.onerror = () => reject(new Error('HubSpot script failed to load'))+ document.body.appendChild(script)+ })++ // Reset the cached promise on failure so a retry can re-attempt the load.+ scriptPromise.catch(() => {+ scriptPromise = null+ })++ return scriptPromise+}++export interface HubSpotFormEmbedProps {+ /** HubSpot portal (hub) ID. */+ portalId: string+ /** HubSpot form GUID. */+ formId: string+ /**+ * HubSpot region — required for EU-hosted portals (e.g. `'eu1'`). Omit for+ * the default North America region.+ */+ region?: string+ /** Class name applied to the wrapper element. */+ className?: string+}++type LoadState = 'loading' | 'ready' | 'error'++/**+ * Embeds a HubSpot-hosted form by loading their `forms/embed/v2.js` script+ * and mounting the form into a container managed by this component. Use this+ * when the form is managed in HubSpot (e.g. with conditional fields, GDPR+ * notices, or workflow integrations) and you don't want to re-implement that+ * logic natively.+ *+ * Note: HubSpot renders the form inside a same-origin iframe styled by their+ * own stylesheet. The iframe's appearance is driven by the form's settings in+ * HubSpot — adjust visual styling there.+ *+ * For native-rendered forms with multi-channel fan-out (HubSpot + Customer.io+ * + Notion), use `MarketingForm` instead.+ */+export default function HubSpotFormEmbed({+ portalId,+ formId,+ region,+ className,+}: HubSpotFormEmbedProps) {+ const targetId = `hubspot-form-${useId().replace(/:/g, '-')}`+ const containerRef = useRef<HTMLDivElement | null>(null)+ const [state, setState] = useState<LoadState>('loading')++ useEffect(() => {+ let cancelled = false+ setState('loading')++ loadHubSpotScript()+ .then(() => {+ if (cancelled) return+ if (!window.hbspt || !containerRef.current) {+ setState('error')+ return+ }++ // Clear any previously rendered form (e.g. on prop change or remount).+ while (containerRef.current.firstChild) {+ containerRef.current.removeChild(containerRef.current.firstChild)+ }++ window.hbspt.forms.create({+ portalId,+ formId,+ ...(region ? { region } : {}),+ target: `#${targetId}`,+ })+ setState('ready')+ })+ .catch((error) => {+ if (cancelled) return+ console.error('[marketing/hubspot] Failed to initialize HubSpot form embed', error)+ setState('error')+ })++ return () => {+ cancelled = true+ }+ }, [portalId, formId, region, targetId])++ return (+ <div className={className}>+ <div id={targetId} ref={containerRef} aria-busy={state === 'loading'} />++ {state === 'loading' && (+ <div+ className="flex flex-col gap-3 animate-pulse p-6 sm:p-8"+ role="status"+ aria-label="Loading form"+ >+ <div className="h-10 rounded-md bg-surface-200" />+ <div className="h-10 rounded-md bg-surface-200" />+ <div className="h-10 rounded-md bg-surface-200" />+ <div className="h-24 rounded-md bg-surface-200" />+ <div className="h-10 rounded-md bg-surface-200 w-1/3" />+ </div>+ )}++ {state === 'error' && (+ <p className="text-sm text-foreground-light p-6 sm:p-8" role="alert">+ We couldn't load the form. Please refresh the page or try again later.+ </p>+ )}+ </div>+ )+}diff --git a/packages/marketing/src/forms/MarketingForm.tsx b/packages/marketing/src/forms/MarketingForm.tsxnew file mode 100644index 00000000000..f91327e3ea7--- /dev/null+++ b/packages/marketing/src/forms/MarketingForm.tsx@@ -0,0 +1,355 @@+'use client'++import { useState } from 'react'+import ReactMarkdown from 'react-markdown'+import {+ Button,+ Checkbox,+ Input_Shadcn_,+ Select_Shadcn_,+ SelectContent_Shadcn_,+ SelectItem_Shadcn_,+ SelectTrigger_Shadcn_,+ SelectValue_Shadcn_,+ TextArea_Shadcn_,+} from 'ui'+import type { z } from 'zod'++import { submitFormAction } from '../go/actions/submitForm'+import { formCrmConfigSchema, formFieldSchema, type GoFormFieldShowWhen } from '../go/schemas'++/** Input-shape field type — fields with Zod defaults (`half`, `required`) are optional here. */+export type MarketingFormField = z.input<typeof formFieldSchema>+export type MarketingFormCrmConfig = z.input<typeof formCrmConfigSchema>++/**+ * Evaluate a `showWhen` rule against the current form values. All supplied+ * criteria must pass (AND). Missing values are treated as the empty string.+ */+function evaluateShowWhen(showWhen: GoFormFieldShowWhen, values: Record<string, string>): boolean {+ const value = values[showWhen.field] ?? ''+ if (showWhen.equals !== undefined && value !== showWhen.equals) return false+ if (showWhen.notEquals !== undefined && value === showWhen.notEquals) return false+ if (showWhen.in !== undefined && !showWhen.in.includes(value)) return false+ if (showWhen.notIn !== undefined && showWhen.notIn.includes(value)) return false+ if (showWhen.truthy === true && value === '') return false+ if (showWhen.truthy === false && value !== '') return false+ return true+}++export interface MarketingFormProps {+ /** Form fields. The submit handler builds the payload from these by `name`. */+ fields: MarketingFormField[]+ /** Submit button label. */+ submitLabel: string+ /** Optional title shown above the form. */+ title?: string+ /** Optional description shown above the form. */+ description?: string+ /** Optional markdown disclaimer shown beneath the submit button. */+ disclaimer?: string+ /** Message shown after a successful submission. Ignored when `successRedirect` is set. */+ successMessage?: string+ /** URL to redirect the user to after a successful submission. Overrides `successMessage`. */+ successRedirect?: string+ /** CRM fan-out config — submits to HubSpot, Customer.io, and/or Notion in parallel. */+ crm?: MarketingFormCrmConfig+ /** Wraps the form in a styled card (border + padding). Defaults to `true`. */+ card?: boolean+ /** Extra class names applied to the outer wrapper. */+ className?: string+}++type SubmitState = 'idle' | 'loading' | 'success' | 'error'++function FieldInput({+ field,+ value,+ onChange,+}: {+ field: MarketingFormField+ value: string+ onChange: (value: string) => void+}) {+ switch (field.type) {+ case 'text':+ case 'email':+ case 'url':+ return (+ <Input_Shadcn_+ type={field.type}+ placeholder={field.placeholder}+ required={field.required}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ />+ )+ case 'textarea':+ return (+ <TextArea_Shadcn_+ placeholder={field.placeholder}+ required={field.required}+ rows={field.rows}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ />+ )+ case 'select':+ return (+ <Select_Shadcn_ value={value} onValueChange={onChange} required={field.required}>+ <SelectTrigger_Shadcn_>+ <SelectValue_Shadcn_ placeholder={field.placeholder} />+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ {field.options.map((opt) => (+ <SelectItem_Shadcn_ key={opt.value} value={opt.value}>+ {opt.label}+ </SelectItem_Shadcn_>+ ))}+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ )+ case 'checkbox':+ return null+ default: {+ const _exhaustive: never = field+ return null+ }+ }+}++function Field({+ field,+ value,+ onChange,+}: {+ field: MarketingFormField+ value: string+ onChange: (value: string) => void+}) {+ if (field.type === 'checkbox') {+ return (+ <label className="flex items-start gap-3 cursor-pointer text-sm text-foreground-light leading-relaxed">+ <Checkbox+ className="mt-0.5"+ checked={value === 'true'}+ onCheckedChange={(checked) => onChange(checked === true ? 'true' : 'false')}+ />+ <span>{field.label}</span>+ </label>+ )+ }++ return (+ <div className="flex flex-col gap-2">+ <label className="text-sm text-foreground font-medium">{field.label}</label>+ <FieldInput field={field} value={value} onChange={onChange} />+ {field.description && (+ <p className="text-xs text-foreground-lighter leading-relaxed">{field.description}</p>+ )}+ </div>+ )+}++export default function MarketingForm({+ fields,+ submitLabel,+ title,+ description,+ disclaimer,+ successMessage,+ successRedirect,+ crm,+ card = true,+ className,+}: MarketingFormProps) {+ const [values, setValues] = useState<Record<string, string>>(() =>+ Object.fromEntries(fields.map((f) => [f.name, '']))+ )+ const [submitState, setSubmitState] = useState<SubmitState>('idle')+ const [errorMessages, setErrorMessages] = useState<string[]>([])++ const handleChange = (name: string, value: string) => {+ setValues((prev) => ({ ...prev, [name]: value }))+ }++ // Only fields whose `showWhen` (if any) currently passes are rendered or submitted.+ const visibleFields = fields.filter((f) => !f.showWhen || evaluateShowWhen(f.showWhen, values))+ const visibleFieldNames = new Set(visibleFields.map((f) => f.name))++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault()++ // Required checkboxes aren't covered by HTML5 validation; check them manually.+ const uncheckedRequired = visibleFields.filter(+ (f) => f.type === 'checkbox' && f.required && values[f.name] !== 'true'+ )+ if (uncheckedRequired.length > 0) {+ setSubmitState('error')+ setErrorMessages(+ uncheckedRequired.map((f) => `Please confirm: ${f.label.replace(/\*$/, '').trim()}`)+ )+ return+ }++ // Strip values for fields that are currently hidden so stale data doesn't leak.+ const submittedValues = Object.fromEntries(+ Object.entries(values).filter(([name]) => visibleFieldNames.has(name))+ )++ if (!crm) {+ if (process.env.NODE_ENV === 'development') {+ console.log('[marketing/form] No CRM configured — form values:', submittedValues)+ }+ return+ }++ setSubmitState('loading')+ setErrorMessages([])++ const pageUri = typeof window !== 'undefined' ? window.location.href : undefined+ const pageName = typeof document !== 'undefined' ? document.title : undefined++ try {+ const result = await submitFormAction(crm, submittedValues, { pageUri, pageName })++ if (result.success) {+ if (successRedirect) {+ window.location.href = successRedirect+ } else {+ setSubmitState('success')+ }+ } else {+ setSubmitState('error')+ setErrorMessages(result.errors)+ }+ } catch (err: any) {+ console.error('[marketing/form] Form submission failed:', err)+ setSubmitState('error')+ setErrorMessages(['Something went wrong. Please try again.'])+ }+ }++ // Group fields into rows: half-width fields pair up, full-width fields get their own row.+ // Checkbox fields always take a full row regardless of their `half` flag.+ const rows: MarketingFormField[][] = []+ let pendingHalf: MarketingFormField | null = null++ for (const field of visibleFields) {+ const isHalf = field.half && field.type !== 'checkbox'+ if (isHalf) {+ if (pendingHalf) {+ rows.push([pendingHalf, field])+ pendingHalf = null+ } else {+ pendingHalf = field+ }+ } else {+ if (pendingHalf) {+ rows.push([pendingHalf])+ pendingHalf = null+ }+ rows.push([field])+ }+ }+ if (pendingHalf) {+ rows.push([pendingHalf])+ }++ if (submitState === 'success') {+ return (+ <div className={className}>+ <div+ className={+ card+ ? 'border border-muted rounded-2xl p-6 sm:p-8 flex flex-col items-center gap-4 text-center'+ : 'flex flex-col items-center gap-4 text-center'+ }+ >+ <p className="text-lg font-medium">Thank you!</p>+ <p className="text-foreground-light">+ {successMessage ?? "We've received your submission and will be in touch soon."}+ </p>+ </div>+ </div>+ )+ }++ return (+ <div className={className}>+ {(title || description) && (+ <div className="flex flex-col items-center gap-4 text-center text-balance mb-10">+ {title && (+ <h2 className="text-2xl md:text-3xl lg:text-4xl leading-tight tracking-tight">+ {title}+ </h2>+ )}+ {description && <p className="text-foreground-light text-lg max-w-xl">{description}</p>}+ </div>+ )}+ <form+ onSubmit={handleSubmit}+ className={+ card+ ? 'border border-muted rounded-2xl p-6 sm:p-8 flex flex-col gap-6'+ : 'flex flex-col gap-6'+ }+ >+ {rows.map((row, rowIndex) => (+ <div+ key={rowIndex}+ className={row.length > 1 ? 'grid grid-cols-1 sm:grid-cols-2 gap-4' : undefined}+ >+ {row.map((field) => (+ <Field+ key={field.name}+ field={field}+ value={values[field.name] ?? ''}+ onChange={(v) => handleChange(field.name, v)}+ />+ ))}+ </div>+ ))}++ {submitState === 'error' && errorMessages.length > 0 && (+ <div className="flex flex-col gap-1">+ {errorMessages.map((msg, i) => (+ <p key={i} className="text-sm text-destructive">+ {msg}+ </p>+ ))}+ </div>+ )}++ <hr className="border-muted" />++ <Button+ htmlType="submit"+ type="primary"+ size="large"+ block+ loading={submitState === 'loading'}+ >+ {submitLabel}+ </Button>++ {disclaimer && (+ <div className="text-xs text-foreground-lighter leading-relaxed [&_a]:text-brand-link [&_a]:decoration-brand-link">+ <ReactMarkdown+ components={{+ p: ({ children }) => <p>{children}</p>,+ a: ({ href, children }) => (+ <a href={href} target="_blank" rel="noopener noreferrer">+ {children}+ </a>+ ),+ }}+ >+ {disclaimer}+ </ReactMarkdown>+ </div>+ )}+ </form>+ </div>+ )+}diff --git a/packages/marketing/src/forms/index.ts b/packages/marketing/src/forms/index.tsnew file mode 100644index 00000000000..974e7091b4b--- /dev/null+++ b/packages/marketing/src/forms/index.ts@@ -0,0 +1,9 @@+export { default as MarketingForm } from './MarketingForm'+export type {+ MarketingFormCrmConfig,+ MarketingFormField,+ MarketingFormProps,+} from './MarketingForm'++export { default as HubSpotFormEmbed } from './HubSpotFormEmbed'+export type { HubSpotFormEmbedProps } from './HubSpotFormEmbed'diff --git a/packages/marketing/src/go/schemas.ts b/packages/marketing/src/go/schemas.tsindex d0b73469e26..d9bec8effed 100644--- a/packages/marketing/src/go/schemas.ts+++ b/packages/marketing/src/go/schemas.ts@@ -101,18 +101,55 @@ export const threeColumnSectionSchema = z.object({// ----- Form field schemas -----+/**+ * Conditional visibility rule: a field is visible only when the referenced+ * field's current value satisfies all of the supplied criteria.+ *+ * - `equals` / `notEquals` — strict string compare against the live value.+ * - `in` / `notIn` — membership check against a list of values.+ * - `truthy` — when `true`, requires a non-empty value; when `false`, requires empty.+ *+ * Multiple criteria within the same `showWhen` are combined with AND. Hidden+ * fields are excluded from the submitted payload.+ */+export const showWhenSchema = z+ .object({+ field: z.string().min(1),+ equals: z.string().optional(),+ notEquals: z.string().optional(),+ in: z.array(z.string()).optional(),+ notIn: z.array(z.string()).optional(),+ truthy: z.boolean().optional(),+ })+ .refine(+ (v) =>+ v.equals !== undefined ||+ v.notEquals !== undefined ||+ v.in !== undefined ||+ v.notIn !== undefined ||+ v.truthy !== undefined,+ { message: 'showWhen must include at least one of: equals, notEquals, in, notIn, truthy' }+ )+const formFieldBase = z.object({name: z.string().min(1),label: z.string().min(1),+ /** Helper text rendered beneath the input. */+ description: z.string().optional(),placeholder: z.string().optional(),required: z.boolean().optional().default(false),half: z.boolean().optional().default(false),+ showWhen: showWhenSchema.optional(),})export const textFieldSchema = formFieldBase.extend({type: z.literal('text'),})+export const urlFieldSchema = formFieldBase.extend({+ type: z.literal('url'),+})+export const emailFieldSchema = formFieldBase.extend({type: z.literal('email'),})@@ -127,11 +164,17 @@ export const selectFieldSchema = formFieldBase.extend({options: z.array(z.object({ label: z.string(), value: z.string() })).min(1),})+export const checkboxFieldSchema = formFieldBase.extend({+ type: z.literal('checkbox'),+})+export const formFieldSchema = z.discriminatedUnion('type', [textFieldSchema,+ urlFieldSchema,emailFieldSchema,textareaFieldSchema,selectFieldSchema,+ checkboxFieldSchema,])// ----- Form CRM config schemas -----@@ -401,6 +444,7 @@ export type GoSingleColumnSection = z.infer<typeof singleColumnSectionSchema>export type GoTwoColumnSection = z.infer<typeof twoColumnSectionSchema>export type GoThreeColumnSection = z.infer<typeof threeColumnSectionSchema>export type GoFormField = z.infer<typeof formFieldSchema>+export type GoFormFieldShowWhen = z.infer<typeof showWhenSchema>export type GoFormSection = z.infer<typeof formSectionSchema>export type GoHubSpotFormConfig = z.infer<typeof hubspotFormConfigSchema>export type GoCustomerIOFormConfig = z.infer<typeof customerioFormConfigSchema>diff --git a/packages/marketing/src/go/sections/FormSection.tsx b/packages/marketing/src/go/sections/FormSection.tsxindex 0939d15e861..c4147eb1251 100644--- a/packages/marketing/src/go/sections/FormSection.tsx+++ b/packages/marketing/src/go/sections/FormSection.tsx@@ -1,240 +1,22 @@'use client'-import { useState } from 'react'-import ReactMarkdown from 'react-markdown'-import {- Button,- Input_Shadcn_,- Select_Shadcn_,- SelectContent_Shadcn_,- SelectItem_Shadcn_,- SelectTrigger_Shadcn_,- SelectValue_Shadcn_,- TextArea_Shadcn_,-} from 'ui'--import { submitFormAction } from '../actions/submitForm'-import type { GoFormField, GoFormSection } from '../schemas'--function FormField({- field,- value,- onChange,-}: {- field: GoFormField- value: string- onChange: (value: string) => void-}) {- switch (field.type) {- case 'text':- case 'email':- return (- <Input_Shadcn_- type={field.type}- placeholder={field.placeholder}- required={field.required}- value={value}- onChange={(e) => onChange(e.target.value)}- />- )- case 'textarea':- return (- <TextArea_Shadcn_- placeholder={field.placeholder}- required={field.required}- rows={field.rows}- value={value}- onChange={(e) => onChange(e.target.value)}- />- )- case 'select':- return (- <Select_Shadcn_ value={value} onValueChange={onChange} required={field.required}>- <SelectTrigger_Shadcn_>- <SelectValue_Shadcn_ placeholder={field.placeholder} />- </SelectTrigger_Shadcn_>- <SelectContent_Shadcn_>- {field.options.map((opt) => (- <SelectItem_Shadcn_ key={opt.value} value={opt.value}>- {opt.label}- </SelectItem_Shadcn_>- ))}- </SelectContent_Shadcn_>- </Select_Shadcn_>- )- default: {- const _exhaustive: never = field- return null- }- }-}--type SubmitState = 'idle' | 'loading' | 'success' | 'error'+import MarketingForm from '../../forms/MarketingForm'+import type { GoFormSection } from '../schemas'export default function FormSection({ section }: { section: GoFormSection }) {- const [values, setValues] = useState<Record<string, string>>(() =>- Object.fromEntries(section.fields.map((f) => [f.name, '']))- )- const [submitState, setSubmitState] = useState<SubmitState>('idle')- const [errorMessages, setErrorMessages] = useState<string[]>([])-- const handleChange = (name: string, value: string) => {- setValues((prev) => ({ ...prev, [name]: value }))- }-- const handleSubmit = async (e: React.FormEvent) => {- e.preventDefault()-- if (!section.crm) {- if (process.env.NODE_ENV === 'development') {- console.log('[go/form] No CRM configured — form values:', values)- }- return- }-- setSubmitState('loading')- setErrorMessages([])-- const pageUri = typeof window !== 'undefined' ? window.location.href : undefined- const pageName = typeof document !== 'undefined' ? document.title : undefined-- try {- const result = await submitFormAction(section.crm, values, { pageUri, pageName })-- if (result.success) {- if (section.successRedirect) {- window.location.href = section.successRedirect- } else {- setSubmitState('success')- }- } else {- setSubmitState('error')- setErrorMessages(result.errors)- }- } catch (err: any) {- // Unexpected client-side error (network failure, server action crash, etc.)- console.error('[go/form] Form submission failed:', err)- setSubmitState('error')- setErrorMessages(['Something went wrong. Please try again.'])- }- }-- // Group fields into rows: half-width fields pair up, full-width fields get their own row- const rows: GoFormField[][] = []- let pendingHalf: GoFormField | null = null-- for (const field of section.fields) {- if (field.half) {- if (pendingHalf) {- rows.push([pendingHalf, field])- pendingHalf = null- } else {- pendingHalf = field- }- } else {- if (pendingHalf) {- rows.push([pendingHalf])- pendingHalf = null- }- rows.push([field])- }- }- if (pendingHalf) {- rows.push([pendingHalf])- }-- if (submitState === 'success') {- return (- <section>- <div className="max-w-2xl mx-auto px-8">- <div className="border border-muted rounded-2xl p-6 sm:p-8 flex flex-col items-center gap-4 text-center">- <p className="text-lg font-medium">Thank you!</p>- <p className="text-foreground-light">- {section.successMessage ??- "We've received your submission and will be in touch soon."}- </p>- </div>- </div>- </section>- )- }-return (<section><div className="max-w-2xl mx-auto px-8">- {(section.title || section.description) && (- <div className="flex flex-col items-center gap-4 text-center text-balance mb-10">- {section.title && (- <h2 className="text-2xl md:text-3xl lg:text-4xl leading-tight tracking-tight">- {section.title}- </h2>- )}- {section.description && (- <p className="text-foreground-light text-lg max-w-xl">{section.description}</p>- )}- </div>- )}- <form- onSubmit={handleSubmit}- className="border border-muted rounded-2xl p-6 sm:p-8 flex flex-col gap-6"- >- {rows.map((row, rowIndex) => (- <div- key={rowIndex}- className={row.length > 1 ? 'grid grid-cols-1 sm:grid-cols-2 gap-4' : undefined}- >- {row.map((field) => (- <div key={field.name} className="flex flex-col gap-2">- <label className="text-sm text-foreground font-medium">{field.label}</label>- <FormField- field={field}- value={values[field.name] ?? ''}- onChange={(v) => handleChange(field.name, v)}- />- </div>- ))}- </div>- ))}-- {submitState === 'error' && errorMessages.length > 0 && (- <div className="flex flex-col gap-1">- {errorMessages.map((msg, i) => (- <p key={i} className="text-sm text-destructive">- {msg}- </p>- ))}- </div>- )}-- <hr className="border-muted" />-- <Button- htmlType="submit"- type="primary"- size="large"- block- loading={submitState === 'loading'}- >- {section.submitLabel}- </Button>-- {section.disclaimer && (- <div className="text-xs text-foreground-lighter leading-relaxed [&_a]:text-brand-link [&_a]:decoration-brand-link">- <ReactMarkdown- components={{- p: ({ children }) => <p>{children}</p>,- a: ({ href, children }) => (- <a href={href} target="_blank" rel="noopener noreferrer">- {children}- </a>- ),- }}- >- {section.disclaimer}- </ReactMarkdown>- </div>- )}- </form>+ <MarketingForm+ fields={section.fields}+ submitLabel={section.submitLabel}+ title={section.title}+ description={section.description}+ disclaimer={section.disclaimer}+ successMessage={section.successMessage}+ successRedirect={section.successRedirect}+ crm={section.crm}+ /></div></section>)