Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

18.6 KB
Raw Blame
'use client'

import { useRef, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import {
  Button,
  Checkbox,
  Input,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  TextArea,
} from 'ui'
import type { z } from 'zod'

import { submitFormAction } from '../go/actions/submitForm'
import { formFieldSchema, type GoFormCrmConfig } from '../go/schemas'
import { evaluateShowWhen } from '../go/showWhen'

/** CRM fan-out config used by components that define their CRM inline (e.g. PartnerIntakeForm).
 *  Once a form's `formRef` is registered on the server, prefer that pattern for security. */
export type MarketingFormCrmConfig = GoFormCrmConfig

/** Input-shape field type — fields with Zod defaults (`half`, `required`) are optional here. */
export type MarketingFormField = z.input<typeof formFieldSchema>

/**
 * Opaque reference the client posts back to the server action. The server
 * resolves this to the trusted CRM config from the page registry; the client
 * never sees or controls the actual CRM target (database id, form GUID, etc.).
 */
export interface MarketingFormRef {
  slug: string
  formId: string
}

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
  /**
   * Server-side form reference. When set, submissions are posted to
   * `submitFormAction` with this ref; the server looks up the trusted CRM
   * config from the page registry. When omitted, the form logs values in dev
   * and does nothing in production (useful for previews).
   */
  formRef?: MarketingFormRef
  /** Wraps the form in a styled card (border + padding). Defaults to `true`. */
  card?: boolean
  /** Extra class names applied to the outer wrapper. */
  className?: string
  /** Pre-populate specific fields by name. Values are applied on first render only. */
  initialValues?: Record<string, string>
  /**
   * Inline CRM config. Accepted for type compatibility; actual fan-out requires
   * a registered `formRef`. Wire up `formRef` once the form GUIDs are confirmed.
   */
  crm?: MarketingFormCrmConfig
}

type SubmitState = 'idle' | 'loading' | 'success' | 'error'

/** Build the sessionStorage key used to block double-submits of the same email to the same form. */
function dedupeKey(formRef: MarketingFormRef | undefined, email: string): string | null {
  if (!formRef || !email) return null
  return `marketing-form-submitted:${formRef.slug}:${formRef.formId}:${email.trim().toLowerCase()}`
}

function FieldInput({
  field,
  value,
  onChange,
}: {
  field: MarketingFormField
  value: string
  onChange: (value: string) => void
}) {
  switch (field.type) {
    case 'text':
    case 'email':
    case 'url':
      return (
        <Input
          type={field.type}
          placeholder={field.placeholder}
          required={field.required}
          value={value}
          onChange={(e) => onChange(e.target.value)}
        />
      )
    case 'textarea':
      return (
        <TextArea
          placeholder={field.placeholder}
          required={field.required}
          rows={field.rows}
          value={value}
          onChange={(e) => onChange(e.target.value)}
        />
      )
    case 'select':
      return (
        <Select value={value} onValueChange={onChange} required={field.required}>
          <SelectTrigger>
            <SelectValue placeholder={field.placeholder} />
          </SelectTrigger>
          <SelectContent>
            {field.options.map((opt) => (
              <SelectItem key={opt.value} value={opt.value}>
                {opt.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      )
    case 'checkbox':
    case 'checkbox-group':
      return null
    default: {
      const _exhaustive: never = field
      return null
    }
  }
}

/** Selected `checkbox-group` values are stored as a semicolon-separated string. */
const CHECKBOX_GROUP_DELIMITER = ';'

function parseCheckboxGroup(value: string): string[] {
  return value ? value.split(CHECKBOX_GROUP_DELIMITER).filter(Boolean) : []
}

function serializeCheckboxGroup(selected: string[]): string {
  return selected.join(CHECKBOX_GROUP_DELIMITER)
}

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 rounded-lg border border-muted bg-surface-100 p-4 text-sm text-foreground-light leading-relaxed transition-colors hover:bg-surface-200">
        <Checkbox
          className="mt-0.5"
          checked={value === 'true'}
          onCheckedChange={(checked) => onChange(checked === true ? 'true' : 'false')}
        />
        <span className="flex flex-col gap-1">
          <span className="font-medium text-foreground">{field.label}</span>
          {field.description && (
            <span className="text-xs text-foreground-lighter leading-relaxed">
              {field.description}
            </span>
          )}
        </span>
      </label>
    )
  }

  if (field.type === 'checkbox-group') {
    const selected = parseCheckboxGroup(value)
    const toggle = (optValue: string, checked: boolean) => {
      const next = checked ? [...selected, optValue] : selected.filter((v) => v !== optValue)
      // Preserve option order so submitted values are deterministic.
      const ordered = field.options.map((o) => o.value).filter((v) => next.includes(v))
      onChange(serializeCheckboxGroup(ordered))
    }
    return (
      <div className="flex flex-col gap-2">
        <label className="text-sm text-foreground font-medium">{field.label}</label>
        <div className="flex flex-col gap-2">
          {field.options.map((opt) => (
            <label
              key={opt.value}
              className="flex items-start gap-3 cursor-pointer text-sm text-foreground-light leading-relaxed"
            >
              <Checkbox
                className="mt-0.5"
                checked={selected.includes(opt.value)}
                onCheckedChange={(checked) => toggle(opt.value, checked === true)}
              />
              <span>{opt.label}</span>
            </label>
          ))}
        </div>
        {field.description && (
          <p className="text-xs text-foreground-lighter leading-relaxed">{field.description}</p>
        )}
      </div>
    )
  }

  return (
    <div className="flex flex-col gap-2">
      <div className="flex flex-col gap-0.5">
        <label className="text-sm text-foreground font-medium">{field.label}</label>
        {field.hint && <p className="text-xs text-foreground-lighter italic">{field.hint}</p>}
      </div>
      <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,
  formRef,
  card = true,
  className,
  initialValues,
}: MarketingFormProps) {
  const [values, setValues] = useState<Record<string, string>>(() =>
    Object.fromEntries(fields.map((f) => [f.name, initialValues?.[f.name] ?? '']))
  )
  const [submitState, setSubmitState] = useState<SubmitState>('idle')
  const [errorMessages, setErrorMessages] = useState<string[]>([])
  // Anti-spam: tracks when the form was first rendered. Submissions that come
  // back faster than MIN_FORM_RENDER_MS on the server are rejected as bot-like.
  const formMountedAtRef = useRef<number>(Date.now())
  // Anti-spam: honeypot. Real users never see or focus this field. The value
  // is kept out of `values` so it never reaches the CRM payload.
  const honeypotRef = useRef<HTMLInputElement>(null)

  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 / checkbox-groups aren't covered by HTML5 validation;
    // check them manually.
    const validationErrors: string[] = []
    for (const f of visibleFields) {
      if (!f.required) continue
      if (f.type === 'checkbox' && values[f.name] !== 'true') {
        validationErrors.push(`Please confirm: ${f.label.replace(/\*$/, '').trim()}`)
      } else if (
        f.type === 'checkbox-group' &&
        parseCheckboxGroup(values[f.name] ?? '').length === 0
      ) {
        validationErrors.push(`Please select at least one: ${f.label.replace(/\*$/, '').trim()}`)
      }
    }
    if (validationErrors.length > 0) {
      setSubmitState('error')
      setErrorMessages(validationErrors)
      return
    }

    // Required checkboxes aren't covered by HTML5 validation; check them manually.
    const uncheckedRequired = visibleFields.filter(
      (f) => f.type === 'checkbox' && f.required && !f.group && values[f.name] !== 'true'
    )
    if (uncheckedRequired.length > 0) {
      setSubmitState('error')
      setErrorMessages(validationErrors)
      return
    }

    const requiredCheckboxGroups = new Map<string, MarketingFormField[]>()
    visibleFields.forEach((field) => {
      if (field.type !== 'checkbox' || !field.group || !field.groupRequired) return
      const groupFields = requiredCheckboxGroups.get(field.group) ?? []
      groupFields.push(field)
      requiredCheckboxGroups.set(field.group, groupFields)
    })

    const missingRequiredGroups = Array.from(requiredCheckboxGroups.values()).filter((group) =>
      group.every((field) => values[field.name] !== 'true')
    )
    if (missingRequiredGroups.length > 0) {
      setSubmitState('error')
      setErrorMessages(
        missingRequiredGroups.map((group) => {
          const labels = group.map((field) => field.label).join(', ')
          return `Please select at least one option: ${labels}`
        })
      )
      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 (!formRef) {
      if (process.env.NODE_ENV === 'development') {
        console.log('[marketing/form] No formRef configured — form values:', submittedValues)
      }
      // Generic message: don't hint at *why* submission didn't happen (e.g. a
      // missing formRef), since that's an internal config detail.
      setSubmitState('error')
      setErrorMessages(['Something went wrong. Please try again.'])
      return
    }

    // Block repeat submissions of the same email to the same form within this
    // browser session, without re-hitting the CRM. `successRedirect` forms
    // still redirect (the destination page already reads as a confirmation);
    // others surface a distinguishable message rather than silently replaying
    // the success screen, so a second attempt (e.g. after fixing a mistake)
    // doesn't look like it worked when nothing was actually resubmitted.
    const emailValue =
      submittedValues['email'] ??
      submittedValues['workEmail'] ??
      submittedValues['work_email'] ??
      submittedValues['emailAddress'] ??
      submittedValues['email_address'] ??
      ''
    const sessionKey = dedupeKey(formRef, emailValue)
    if (sessionKey && typeof window !== 'undefined') {
      try {
        if (window.sessionStorage.getItem(sessionKey)) {
          if (successRedirect) {
            window.location.href = successRedirect
          } else {
            setSubmitState('error')
            setErrorMessages(['You’ve already submitted this form.'])
          }
          return
        }
      } catch {
        // sessionStorage can throw in private mode / disabled storage — ignore.
      }
    }

    setSubmitState('loading')
    setErrorMessages([])

    const pageUri = typeof window !== 'undefined' ? window.location.href : undefined
    const pageName = typeof document !== 'undefined' ? document.title : undefined
    const honeypot = honeypotRef.current?.value ?? ''

    try {
      const result = await submitFormAction(formRef, submittedValues, {
        pageUri,
        pageName,
        honeypot,
        formMountedAt: formMountedAtRef.current,
      })

      if (result.success) {
        if (sessionKey && typeof window !== 'undefined') {
          try {
            window.sessionStorage.setItem(sessionKey, '1')
          } catch {
            // Storage write can fail in private mode — non-fatal.
          }
        }
        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 + checkbox-group 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' && field.type !== 'checkbox-group'
    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])
  }

  // Rendered first in both the form and success views so React keeps the same
  // live region mounted across the swap — screen readers only announce changes
  // to a region that already exists.
  const statusRegion = (
    <p role="status" className="sr-only">
      {submitState === 'success' ? 'Thank you! We’ve received your submission.' : ''}
    </p>
  )

  if (submitState === 'success') {
    return (
      <div className={className}>
        {statusRegion}
        <div
          className={
            card
              ? 'border bg-surface-75 rounded-2xl shadow-xl 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="h3">Thank you!</p>
          <div className="text-foreground-light [&_a]:text-primary [&_a]:decoration-brand">
            <ReactMarkdown
              components={{
                p: ({ children }) => <p>{children}</p>,
                a: ({ href, children }) => (
                  <a href={href} target="_blank" rel="noopener noreferrer">
                    {children}
                  </a>
                ),
              }}
            >
              {successMessage ?? "We've received your submission and will be in touch soon."}
            </ReactMarkdown>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className={className}>
      {statusRegion}
      {(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 bg-surface-75 rounded-2xl shadow-xl p-6 sm:p-8 flex flex-col gap-6'
            : 'flex flex-col gap-6'
        }
      >
        {/*
          Honeypot: positioned off-screen rather than display:none so that
          headless bots scraping the form still see and (often) fill it.
          aria-hidden + tabIndex=-1 keep it out of the user journey.
        */}
        <div
          aria-hidden="true"
          className="absolute left-[-9999px] top-auto h-px w-px overflow-hidden"
        >
          <label>
            Website
            <input
              ref={honeypotRef}
              type="text"
              name="website"
              tabIndex={-1}
              autoComplete="off"
              defaultValue=""
            />
          </label>
        </div>
        {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
          type="submit"
          variant="primary"
          size="large"
          block
          loading={submitState === 'loading'}
        >
          {submitLabel}
        </Button>

        {disclaimer && (
          <div className="text-xs text-foreground-lighter leading-relaxed [&_a]:text-primary [&_a]:decoration-brand">
            <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>
  )
}