Skip to content

Beautiful Open-Source Form Builder

60.6 KB
Raw Blame
import { expect, test, type APIRequestContext, type Page } from "@playwright/test"
import { createServer } from "node:http"
import { waitForAnonymousApiBudget, waitForAuthenticatedApiBudget } from "./api-budget"
import { hash } from "../../lib/utils.js"

test.setTimeout(240_000)

const API_BASE_URL = process.env.PLAYWRIGHT_API_BASE_URL || "http://127.0.0.1:8089"
const seededUser = {
  email: "[email protected]",
  password: "Abcd@1234",
}
const browserLogsByTest = new Map<string, string[]>()

function uniqueEmail(prefix = "playwright") {
  return `${prefix}+${Date.now()}${Math.random().toString(36).slice(2, 8)}@gmail.com`
}

function uniqueTitle(prefix = "Playwright Form") {
  return `${prefix} ${Date.now()} ${Math.random().toString(36).slice(2, 6)}`
}

function buildFormPayload(workspaceId: number, title: string, presentationStyle: "classic" | "focused" = "classic") {
  return {
    title,
    visibility: "public",
    workspace_id: workspaceId,
    properties: [
      {
        type: "nf-text",
        content: `<h1>${title}</h1><p>Please fill out this form.</p>`,
        name: "Title",
        id: "default_title",
      },
      {
        name: "Name",
        type: "text",
        hidden: false,
        required: true,
        placeholder: "Enter your full name",
        id: "default_name",
      },
      {
        name: "Email",
        type: "email",
        hidden: false,
        placeholder: "Enter your email address",
        id: "default_email",
      },
      {
        name: "Message",
        type: "text",
        hidden: false,
        multi_lines: true,
        placeholder: "Type your message here",
        id: "default_message",
      },
    ],
    language: "en",
    font_family: null,
    theme: "default",
    presentation_style: presentationStyle,
    width: "centered",
    size: presentationStyle === "focused" ? "lg" : "md",
    layout_rtl: false,
    border_radius: "small",
    dark_mode: "light",
    color: "#3B82F6",
    uppercase_labels: false,
    no_branding: false,
    transparent_background: false,
    submit_button_text: null,
    re_fillable: false,
    re_fill_button_text: "Fill Again",
    pdf_download_enabled: false,
    pdf_download_button_text: null,
    submitted_text: "Amazing, we saved your answers. Thank you for your time and have a great day!",
    redirect_url: null,
    max_submissions_count: null,
    max_submissions_reached_text: "This form has reached the maximum number of submissions.",
    editable_submissions: false,
    editable_submissions_button_text: "Edit submission",
    confetti_on_submission: false,
    show_progress_bar: false,
    auto_save: true,
    auto_focus: true,
    enable_partial_submissions: false,
    enable_ip_tracking: false,
    can_be_indexed: true,
    password: null,
    use_captcha: false,
    captcha_provider: "recaptcha",
    seo_meta: {},
    settings: presentationStyle === "focused" ? { navigation_arrows: true, auto_next: true } : {},
    analytics: [],
    tags: [],
    computed_variables: [],
  }
}

function buildOptionList(optionNames: string[]) {
  return optionNames.map((name) => ({ id: name, name }))
}

function buildTextField(id: string, name: string, overrides: Record<string, unknown> = {}) {
  return {
    id,
    name,
    type: "text",
    hidden: false,
    required: false,
    ...overrides,
  }
}

function buildEmailField(id: string, name: string, overrides: Record<string, unknown> = {}) {
  return {
    id,
    name,
    type: "email",
    hidden: false,
    required: false,
    ...overrides,
  }
}

function buildCheckboxField(id: string, name: string, overrides: Record<string, unknown> = {}) {
  return {
    id,
    name,
    type: "checkbox",
    hidden: false,
    required: false,
    ...overrides,
  }
}

function buildSelectField(id: string, name: string, options: string[], overrides: Record<string, unknown> = {}) {
  return {
    id,
    name,
    type: "select",
    hidden: false,
    required: false,
    allow_creation: false,
    without_dropdown: true,
    use_focused_selector: false,
    select: {
      options: buildOptionList(options),
    },
    ...overrides,
  }
}

function buildMultiSelectField(id: string, name: string, options: string[], overrides: Record<string, unknown> = {}) {
  return {
    id,
    name,
    type: "multi_select",
    hidden: false,
    required: false,
    allow_creation: false,
    without_dropdown: true,
    use_focused_selector: false,
    multi_select: {
      options: buildOptionList(options),
    },
    ...overrides,
  }
}

function buildPageBreak(id: string, nextText: string, previousText: string) {
  return {
    id,
    name: "Page Break",
    type: "nf-page-break",
    next_btn_text: nextText,
    previous_btn_text: previousText,
  }
}

async function gotoPageWithRetry(page: Page, path: string, readyCheck: () => Promise<void>, attempts = 8) {
  let lastError: unknown

  for (let attempt = 1; attempt <= attempts; attempt += 1) {
    try {
      const response = await page.goto(path, { waitUntil: "commit", timeout: 10_000 })
      expect(response?.status(), `unexpected status for ${path} on attempt ${attempt}`).toBeLessThan(500)
      await readyCheck()
      // SSR inputs are actionable before Vue attaches their event handlers.
      await page.waitForFunction(() => {
        const root = document.querySelector('#__nuxt') as Element & {
          __vue_app__?: { $nuxt?: { isHydrating: boolean } }
        }
        return root?.__vue_app__?.$nuxt?.isHydrating === false
      })
      if (process.env.PLAYWRIGHT_DEV_SERVER === "1") {
        await page.waitForTimeout(5000)
      }
      return
    } catch (error) {
      lastError = error
      if (attempt === attempts) {
        break
      }

      await page.waitForTimeout(1500 + attempt * 500)
    }
  }

  throw lastError
}

async function openLogin(page: Page) {
  await gotoPageWithRetry(page, "/login", async () => {
    await expect(page.getByTestId("login-page")).toBeVisible({ timeout: 15_000 })
    await expect(page.locator('input[name="email"]')).toBeEnabled({ timeout: 15_000 })
    await expect(page.locator('input[name="password"]')).toBeEnabled({ timeout: 15_000 })
  })
}

async function openRegister(page: Page) {
  await gotoPageWithRetry(page, "/register", async () => {
    await expect(page.getByTestId("register-page")).toBeVisible({ timeout: 15_000 })
    await expect(page.locator('input[name="name"]')).toBeEnabled({ timeout: 15_000 })
    await expect(page.locator('input[name="email"]')).toBeEnabled({ timeout: 15_000 })
    await expect(page.locator('input[name="password"]')).toBeEnabled({ timeout: 15_000 })
  })
}

async function selectHearAboutUs(page: Page) {
  const select = page.getByRole("button", { name: "How did you hear about us?", exact: true })

  await expect(async () => {
    await select.click()
    await expect(select).toHaveAttribute("aria-expanded", "true")
  }).toPass({ timeout: 15_000 })

  await page.getByRole("option", { name: "Friend or Colleague", exact: true }).click()
}

async function registerUi(page: Page, email: string) {
  await openRegister(page)
  await selectHearAboutUs(page)
  await page.locator('input[name="name"]').fill("Playwright User")
  await page.locator('input[name="email"]').fill(email)
  await page.locator('input[name="password"]').fill("Abcd@1234")
  await page.locator('input[name="password_confirmation"]').fill("Abcd@1234")
  await page.locator('input[name="agree_terms"]').check({ force: true })

  // The preceding public SSR cases can exhaust the shared anonymous API bucket.
  // Honor the real server limit rather than disabling it for browser tests.
  for (let attempt = 0; attempt < 2; attempt += 1) {
    const [response] = await Promise.all([
      page.waitForResponse(response => response.url() === `${API_BASE_URL}/register` && response.request().method() === 'POST'),
      page.getByRole("button", { name: "Create account", exact: true }).click(),
    ])
    if (response.status() !== 429 || attempt === 1) {
      expect(response.ok()).toBeTruthy()
      break
    }
    const retryAfter = Number(response.headers()['retry-after'])
    expect(retryAfter).toBeGreaterThan(0)
    expect(retryAfter).toBeLessThanOrEqual(60)
    await new Promise(resolve => setTimeout(resolve, retryAfter * 1000 + 250))
  }
  await expect(page).toHaveURL(/\/forms\/create$/, { timeout: 30_000 })
}

async function dismissBlockingModals(page: Page) {
  const noThanksButton = page.getByRole("button", { name: "No thanks", exact: true })
  if (await noThanksButton.isVisible().catch(() => false)) {
    await noThanksButton.click()
  }
}

async function loginUi(page: Page, email = seededUser.email, password = seededUser.password) {
  await openLogin(page)
  await page.locator('input[name="email"]').fill(email)
  await page.locator('input[name="password"]').fill(password)

  await page.getByRole("button", { name: /log in to continue/i }).click()
  await expect(page).toHaveURL(/\/home$/, { timeout: 20_000 })
  await dismissBlockingModals(page)
  await expect(page.getByTestId("home-page")).toBeVisible()
}

async function logoutUi(page: Page) {
  await page.getByRole("button", { name: "User menu" }).click()
  await page.getByText("Logout", { exact: true }).click()
  await expect(page).toHaveURL(/\/login$/, { timeout: 20_000 })
}

async function renameEditorTitle(page: Page, title: string) {
  const titleWrapper = page.locator("#form-editor-title")
  await titleWrapper.click()
  const input = titleWrapper.locator("input")
  await expect(input).toBeVisible()
  await input.fill(title)
  await input.blur()
}

async function createFormThroughUi(page: Page, options: { title: string, style: "classic" | "focused" }) {
  await page.goto("/forms/create")
  await expect(page.getByText("Choose a form style")).toBeVisible()

  await page.getByTestId(options.style === "classic" ? "form-style-classic" : "form-style-focused").click()
  await expect(page.getByText("How do you want to start?")).toBeVisible()
  await page.getByTestId("form-base-simple-contact").click()

  await expect(page.locator("#form-editor")).toBeVisible()
  await renameEditorTitle(page, options.title)

  await page.getByTestId("save-form-button").click()
  await expect(page).toHaveURL(/\/forms\/.+\/show\/share/, { timeout: 30_000 })
  await dismissBlockingModals(page)
  await expect(page.getByRole("heading", { name: options.title, exact: true })).toBeVisible()
}

async function apiLogin(request: APIRequestContext) {
  const response = await request.post(`${API_BASE_URL}/login`, {
    data: {
      email: seededUser.email,
      password: seededUser.password,
      remember: false,
    },
    headers: {
      Accept: "application/json",
    },
  })

  expect(response.ok()).toBeTruthy()
  const data = await response.json()
  return data.token as string
}

async function apiWorkspaceId(request: APIRequestContext, token: string) {
  const response = await request.get(`${API_BASE_URL}/open/workspaces`, {
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`,
    },
  })

  expect(response.ok()).toBeTruthy()
  const data = await response.json()
  return data[0].id as number
}

async function apiCreateForm(request: APIRequestContext, options: {
  title?: string,
  presentationStyle?: "classic" | "focused",
  payloadOverrides?: Record<string, unknown>,
} = {}) {
  const token = await apiLogin(request)
  const workspaceId = await apiWorkspaceId(request, token)
  const title = options.title || uniqueTitle()
  let lastFailure: { status: number, body: string } | null = null

  for (let attempt = 1; attempt <= 3; attempt += 1) {
    const response = await request.post(`${API_BASE_URL}/open/forms`, {
      headers: {
        Accept: "application/json",
        Authorization: `Bearer ${token}`,
      },
      data: {
        ...buildFormPayload(workspaceId, title, options.presentationStyle || "classic"),
        ...(options.payloadOverrides || {}),
      },
    })

    if (response.ok()) {
      const data = await response.json()
      return data.form as { id: number, slug: string, share_url: string, title: string }
    }

    lastFailure = {
      status: response.status(),
      body: await response.text(),
    }

    if (attempt < 3) {
      await new Promise((resolve) => setTimeout(resolve, attempt * 500))
    }
  }

  throw new Error(`Failed to create form via API (${lastFailure?.status}): ${lastFailure?.body}`)
}

async function apiListSubmissions(request: APIRequestContext, token: string, slug: string) {
  const response = await request.get(`${API_BASE_URL}/open/forms/${slug}/submissions`, {
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`,
    },
  })

  expect(response.ok()).toBeTruthy()
  return response.json()
}

async function submitPublicForm(page: Page, slug: string, visitorName = "Playwright Visitor") {
  const visitorEmail = uniqueEmail("visitor")

  await openPublicForm(page, slug)
  await fillFieldInput(page, "default_name", visitorName)
  await fillFieldInput(page, "default_email", visitorEmail)
  await fillFieldInput(page, "default_message", "Playwright public submission")

  await page.getByRole("button", { name: /submit/i }).click()
  await expect(page.getByText("Amazing, we saved your answers. Thank you for your time and have a great day!")).toBeVisible()
  return { visitorName, visitorEmail }
}

async function openPublicForm(page: Page, slug: string) {
  await gotoPageWithRetry(page, `/forms/${slug}`, async () => {
    await expect(page.getByTestId("public-form-page")).toBeVisible()
  })
  await page.waitForLoadState("networkidle")
}

async function expectSubmissionSuccess(page: Page) {
  await expect(page.getByText("Amazing, we saved your answers. Thank you for your time and have a great day!")).toBeVisible()
}

function getOpenFormField(page: Page, fieldId: string) {
  return page.getByTestId(`open-form-field-${fieldId}`)
}

async function expectFieldError(page: Page, fieldId: string, message: string | RegExp) {
  const exact = typeof message === "string"
  const fieldMessage = getOpenFormField(page, fieldId).getByText(message, { exact })
  if (await fieldMessage.count()) {
    await expect(fieldMessage.first()).toBeVisible()
    return
  }

  await expect(page.locator("li").filter({ hasText: message }).first()).toBeVisible()
}

async function fillFieldInput(page: Page, fieldId: string, value: string) {
  const input = getOpenFormField(page, fieldId).locator("input, textarea").first()
  await input.click()
  await input.fill("")
  if (value) {
    await input.pressSequentially(value)
  }
  await input.blur()
}

async function fillLabeledInput(page: Page, label: string, value: string) {
  const input = page.getByLabel(label).first()
  await input.click()
  await input.fill("")
  if (value) {
    await input.pressSequentially(value)
  }
  await input.blur()
}

async function checkFieldCheckbox(page: Page, fieldId: string) {
  await getOpenFormField(page, fieldId).locator('input[type="checkbox"]').check({ force: true })
}

async function selectFlatOption(page: Page, fieldId: string, optionName: string, role: "radio" | "checkbox") {
  await getOpenFormField(page, fieldId).getByRole(role, { name: optionName, exact: true }).click()
}

let apiBudgetToken: string | undefined

test.beforeEach(async ({ page, request }, testInfo) => {
  await waitForAnonymousApiBudget(request, testInfo)
  apiBudgetToken ??= await apiLogin(request)
  await waitForAuthenticatedApiBudget(request, testInfo, { Authorization: `Bearer ${apiBudgetToken}` })
  const browserLogs: string[] = []
  browserLogsByTest.set(testInfo.testId, browserLogs)

  page.on("console", (message) => {
    browserLogs.push(`[console:${message.type()}] ${message.text()}`)
  })

  page.on("pageerror", (error) => {
    browserLogs.push(`[pageerror] ${error.stack || error.message}`)
  })

  page.on("requestfailed", (request) => {
    browserLogs.push(
      `[requestfailed] ${request.method()} ${request.url()} :: ${request.failure()?.errorText || "unknown"}`,
    )
  })
})

test.afterEach(async ({}, testInfo) => {
  const browserLogs = browserLogsByTest.get(testInfo.testId) || []

  if (testInfo.status !== testInfo.expectedStatus && browserLogs.length > 0) {
    await testInfo.attach("browser-logs", {
      body: browserLogs.join("\n"),
      contentType: "text/plain",
    })
  }

  browserLogsByTest.delete(testInfo.testId)
})

test("register succeeds and lands in the form creation flow", async ({ page }) => {
  await registerUi(page, uniqueEmail("register"))

  await expect(page).toHaveURL(/\/forms\/create$/, { timeout: 20_000 })
  await expect(page.getByText("Choose a form style")).toBeVisible()
})

test("login succeeds for the seeded user", async ({ page }) => {
  await loginUi(page)
  await expect(page.getByTestId("home-page").getByRole("link", { name: "Create Form" }).first()).toBeVisible()
})

test("invalid login stays on the login page", async ({ page }) => {
  await openLogin(page)
  await page.locator('input[name="email"]').fill(seededUser.email)
  await page.locator('input[name="password"]').fill("wrong-password")

  await page.getByRole("button", { name: /log in to continue/i }).click()
  await expect(page).toHaveURL(/\/login$/)
  await expect(page.getByText(/credentials/i)).toBeVisible()
})

test("logout clears auth and protected routes redirect to login", async ({ page }) => {
  await loginUi(page)
  await logoutUi(page)

  await page.goto("/home")
  await expect(page).toHaveURL(/\/login$/, { timeout: 20_000 })
})

test("classic form creation works end to end", async ({ page }) => {
  await loginUi(page)

  const title = uniqueTitle("Classic Form")
  await createFormThroughUi(page, { title, style: "classic" })

  const shareValue = page.getByTestId("copy-content-value").first()
  await expect(shareValue).toContainText("/forms/")
})

test("focused form creation works end to end", async ({ page }) => {
  await loginUi(page)

  const title = uniqueTitle("Focused Form")
  await createFormThroughUi(page, { title, style: "focused" })

  const shareValue = page.getByTestId("copy-content-value").first()
  await expect(shareValue).toContainText("/forms/")
})

test("public form pages render the expected fields", async ({ page, request }) => {
  const form = await apiCreateForm(request, { title: uniqueTitle("Public Fields") })

  await page.goto(`/forms/${form.slug}`)
  await expect(page.getByTestId("public-form-page")).toBeVisible()
  await expect(page.getByLabel("Name")).toBeVisible()
  await expect(page.getByLabel("Email")).toBeVisible()
  await expect(page.getByLabel("Message")).toBeVisible()
})

test("share page displays the public form URL", async ({ page, request }) => {
  const form = await apiCreateForm(request, { title: uniqueTitle("Share URL") })

  await loginUi(page)
  await page.goto(`/forms/${form.slug}/show/share`)

  const shareValue = page.getByTestId("copy-content-value").first()
  await expect(shareValue).toContainText(form.slug)
  await expect(page.getByTestId("copy-content-button").first()).toBeVisible()
})

test("editing an existing form title persists after save", async ({ page, request }) => {
  const form = await apiCreateForm(request, { title: uniqueTitle("Editable Form") })
  const updatedTitle = uniqueTitle("Updated Form")

  await loginUi(page)
  await page.goto(`/forms/${form.slug}/edit`)
  await expect(page.locator("#form-editor")).toBeVisible()

  await renameEditorTitle(page, updatedTitle)

  await page.getByTestId("save-form-button").click()
  await expect(page).toHaveURL(new RegExp(`/forms/${form.slug}/show/share$`), { timeout: 30_000 })
  await expect(page.getByRole("heading", { name: updatedTitle, exact: true })).toBeVisible()
})

test("editor undo and redo preserve a renamed form through save", async ({ page, request }) => {
  const form = await apiCreateForm(request, { title: uniqueTitle("History Original") })
  const updatedTitle = uniqueTitle("History Edited")
  await loginUi(page)
  await page.goto(`/forms/${form.slug}/edit`)
  await expect(page.locator("#form-editor")).toBeVisible()
  // UndoRedo clears the initial mounted state after 500 ms.
  await page.waitForTimeout(650)
  const undo = page.locator("#form-editor button").filter({ has: page.locator('[class*="undo"]') }).first()
  const redo = page.locator("#form-editor button").filter({ has: page.locator('[class*="redo"]') }).first()
  await expect(undo).toBeDisabled()
  await renameEditorTitle(page, updatedTitle)
  await expect(undo).toBeEnabled()
  await undo.click()
  await expect(page.locator("#form-editor-title")).toHaveText(form.title)
  await expect(redo).toBeEnabled()
  await redo.click()
  await expect(page.locator("#form-editor-title")).toHaveText(updatedTitle)
  await page.getByTestId("save-form-button").click()
  await expect(page).toHaveURL(new RegExp(`/forms/${form.slug}/show/share$`), { timeout: 30_000 })
  await expect(page.getByRole("heading", { name: updatedTitle, exact: true })).toBeVisible()
})

test("calendar selection and clear preserve the submitted day", async ({ page, request }) => {
  const form = await apiCreateForm(request, {
    title: uniqueTitle("Calendar Compatibility"),
    payloadOverrides: { properties: [{ id: "appointment", name: "Appointment", type: "date", required: true, date_format: "yyyy-MM-dd" }] },
  })
  await openPublicForm(page, form.slug)
  await page.getByRole("button", { name: "Select date", exact: true }).click()
  const day = page.locator(".vc-day:not(.is-not-in-month)").filter({ has: page.locator(".vc-day-content").filter({ hasText: /^15$/ }) }).first()
  const selectedDay = (await day.getAttribute("class"))?.match(/(?:^|\s)id-(\d{4}-\d{2}-\d{2})(?:\s|$)/)?.[1]
  expect(selectedDay).toBeTruthy()
  await day.getByRole("button").click()
  await expect(page.getByRole("button", { name: `Selected date: ${selectedDay}`, exact: true })).toBeVisible()
  await page.getByRole("button", { name: "Clear date", exact: true }).click()
  const trigger = page.getByRole("button", { name: "Select date", exact: true })
  await expect(trigger).toHaveAttribute("aria-expanded", "false")
  await expect(page.locator(".vc-container")).toBeHidden()
  await trigger.click()
  await expect(trigger).toHaveAttribute("aria-expanded", "true")
  await day.getByRole("button").click()
  for (const key of ["Enter", "Space"]) {
    await page.getByRole("button", { name: "Clear date", exact: true }).press(key)
    await expect(trigger).toHaveAttribute("aria-expanded", "false")
    await expect(page.locator(".vc-container")).toBeHidden()
    await trigger.click()
    await expect(trigger).toHaveAttribute("aria-expanded", "true")
    await day.getByRole("button").click()
  }
  await page.getByRole("button", { name: /submit/i }).click()
  await expectSubmissionSuccess(page)
  const token = await apiLogin(request)
  const submissions = await apiListSubmissions(request, token, form.slug)
  expect(submissions.data[0].data.appointment.slice(0, 10)).toBe(selectedDay)
})

for (const deferredFonts of [false, true]) {
  test(`font picker opens from Design and applies a font${deferredFonts ? " after a delayed response" : ""}`, async ({ page, request }) => {
    const form = await apiCreateForm(request, { title: uniqueTitle("Font Picker") })
    let releaseFonts = () => {}
    let fontsRequested = false
    const pendingFonts = new Promise<void>(resolve => { releaseFonts = resolve })
    await page.route("**/fonts", async route => {
      fontsRequested = true
      if (deferredFonts) await pendingFonts
      return route.fulfill({ json: ["Roboto", "Open Sans"] })
    })
    // The test covers the picker and applied font style without requiring a CDN connection.
    await page.route("https://fonts.googleapis.com/**", route => route.fulfill({ contentType: 'text/css', body: '' }))

    const token = await apiLogin(request)
    const baseURL = test.info().project.use.baseURL
    if (!baseURL) throw new Error("Playwright baseURL is required")
    await page.context().addCookies([{ name: "opnform_token", value: token, url: baseURL }])
    await page.goto(`/forms/${form.slug}/edit`)
    await expect(page.locator("#form-editor")).toBeVisible()

    // Exercise the enabled UI without requiring a Google Fonts API key in CI.
    await page.evaluate(() => {
      // Nuxt 4 keeps the hydrated payload on the app rather than window.__NUXT__.
      const root = document.querySelector('#__nuxt') as Element & {
        __vue_app__: { $nuxt: { payload: { state: Record<string, { services: { google: { fonts: boolean } } }> } } }
      }
      root.__vue_app__.$nuxt.payload.state["$sfeatureFlags"].services.google.fonts = true
    })

    const pageErrors: string[] = []
    page.on("pageerror", error => pageErrors.push(error.message))
    page.on("console", message => { if (message.type() === 'error') pageErrors.push(message.text()) })

    await page.getByText("Design", { exact: true }).click()
    const fontFamily = page.getByText("Font Family", { exact: true }).locator("..")
    await fontFamily.getByRole("button").click()
    if (deferredFonts) {
      await expect.poll(() => fontsRequested).toBe(true)
      await expect(page.getByText("The quick brown fox jumped over the lazy dog")).toHaveCount(0)
      releaseFonts()
    }
    await expect(page.getByText("The quick brown fox jumped over the lazy dog").first()).toBeVisible()
    await page.getByText("Roboto", { exact: true }).last().click()
    await page.getByRole("button", { name: "Apply", exact: true }).click()

    await expect(fontFamily.getByRole("button")).toContainText("Roboto")
    await expect(fontFamily.getByRole("button").getByText("Roboto", { exact: true })).toHaveCSS('font-family', 'Roboto')
    await expect(page.locator(".form-editor-preview .open-complete-form")).toHaveCSS("--font-family", "Roboto")
    await fontFamily.getByRole("button").click()
    await expect(page.getByText("The quick brown fox jumped over the lazy dog").first()).toBeVisible()
    expect(pageErrors).toEqual([])
  })
}

test("form save errors open the invalid field section and computed variable", async ({ page, request }) => {
  const form = await apiCreateForm(request, {
    title: uniqueTitle("Save Error Form"),
    payloadOverrides: {
      properties: [
        {
          type: "nf-text",
          content: "<h1>Save error form</h1>",
          name: "Title",
          id: "save_error_title",
        },
        buildTextField("contact_name", "Contact name"),
        buildSelectField("problematic-dropdown", "Problematic dropdown", ["Temporary option"]),
      ],
      computed_variables: [{
        id: "cv_order_total",
        name: "Order total",
        formula: "1 + 1",
        result_type: "number",
      }],
    },
  })

  await loginUi(page)
  let saveAttempt = 0
  await page.route("**/open/forms/*", async (route) => {
    if (route.request().method() !== "PUT") {
      await route.continue()
      return
    }

    saveAttempt += 1

    const responseBody = saveAttempt === 1
      ? {
          message: "At least one option is required. (and 1 more error)",
          errors: {
            "properties.2.select.options": ["At least one option is required."],
            properties: ["One or more properties have validation errors."],
          },
        }
      : saveAttempt === 2
        ? {
            message: "The logic actions for Problematic dropdown are not valid. (and 1 more error)",
            errors: {
              "properties.2.logic": ["The logic actions for Problematic dropdown are not valid."],
              properties: ["One or more properties have validation errors."],
            },
          }
        : {
            message: "The formula is required. (and 1 more error)",
            errors: {
              "computed_variables.0.formula": ["The formula is required."],
              computed_variables: ["One or more computed variables have validation errors."],
            },
          }

    await route.fulfill({
      status: 422,
      contentType: "application/json",
      body: JSON.stringify(responseBody),
    })
  })

  await page.goto(`/forms/${form.slug}/edit`)
  await expect(page.locator("#form-editor")).toBeVisible()
  await page.getByTestId("save-form-button").click()

  const errorModal = page.getByTestId("form-save-error-modal")
  await expect(errorModal).toBeVisible()
  await expect(page.getByText("Fix 1 field before saving", { exact: true })).toBeVisible()
  await expect(errorModal).toContainText("Problematic dropdown")
  await expect(errorModal).toContainText("At least one option is required.")
  await expect(errorModal).not.toContainText("One or more properties have validation errors.")
  await expect(errorModal).not.toContainText("and 1 more error")

  await page.getByTestId("edit-form-field-problematic-dropdown").click()

  await expect(errorModal).toBeHidden()
  const fieldSettings = page.getByTestId("form-field-settings")
  await expect(fieldSettings).toBeVisible()
  await expect(fieldSettings).toBeFocused()
  await expect(fieldSettings).toContainText("Select Options")

  await page.getByTestId("save-form-button").click()
  await expect(errorModal).toBeVisible()
  await expect(errorModal).toContainText("The logic actions for Problematic dropdown are not valid.")
  await page.getByTestId("edit-form-field-problematic-dropdown").click()

  await expect(errorModal).toBeHidden()
  await expect(fieldSettings).toContainText("When following condition(s) are true")

  await page.getByTestId("save-form-button").click()
  await expect(errorModal).toBeVisible()
  await expect(page.getByText("Fix 1 variable before saving", { exact: true })).toBeVisible()
  await expect(errorModal).toContainText("Order total")
  await expect(errorModal).toContainText("The formula is required.")
  await page.getByTestId("edit-computed-variable-cv_order_total").click()

  const variableModal = page.getByTestId("computed-variable-modal")
  await expect(variableModal).toBeVisible()
  await expect(variableModal.getByText("Edit Variable", { exact: true })).toBeVisible()
  await expect(variableModal.getByPlaceholder("e.g., Total Price, Dog Age")).toHaveValue("Order total")
})

test("public submissions are accepted and visible in the submissions dashboard", async ({ page, request }) => {
  const form = await apiCreateForm(request, { title: uniqueTitle("Submission Form") })
  const { visitorName, visitorEmail } = await submitPublicForm(page, form.slug)

  await loginUi(page)
  await page.goto(`/forms/${form.slug}/show/submissions`)

  await expect(page.getByTestId("form-submissions-page")).toBeVisible()
  await expect(page.getByText(visitorName)).toBeVisible()
  await expect(page.getByText(visitorEmail)).toBeVisible()
})

test("public form URL attribution is stored separately from submitted answers", async ({ page, request }) => {
  const form = await apiCreateForm(request, { title: uniqueTitle("Attributed Submission") })
  const visitorName = `Attributed Visitor ${Date.now()}`
  const visitorEmail = uniqueEmail("attributed")

  await gotoPageWithRetry(
    page,
    `/forms/${form.slug}?utm_source=playwright&utm_campaign=e2e&gclid=browser-click&email=must-not-track`,
    async () => {
      await expect(page.getByTestId("public-form-page")).toBeVisible()
    },
  )
  await fillFieldInput(page, "default_name", visitorName)
  await fillFieldInput(page, "default_email", visitorEmail)
  await fillFieldInput(page, "default_message", "Attribution browser test")
  await page.getByRole("button", { name: /submit/i }).click()
  await expectSubmissionSuccess(page)

  const token = await apiLogin(request)
  const submissionsResponse = await request.get(
    `${API_BASE_URL}/open/forms/${form.slug}/submissions`,
    {
      headers: {
        Accept: "application/json",
        Authorization: `Bearer ${token}`,
      },
    },
  )

  expect(submissionsResponse.ok()).toBeTruthy()
  const submissions = await submissionsResponse.json()
  const submission = submissions.data.find((record: {
    data: Record<string, unknown>,
  }) => record.data.default_name === visitorName)

  expect(submission).toBeTruthy()
  expect(submission.data).not.toHaveProperty("tracking_parameters")
  expect(submission.meta).toEqual({
    attribution: {
      utm_source: "playwright",
      utm_campaign: "e2e",
      gclid: "browser-click",
    },
  })

  await loginUi(page)
  await page.goto(`/forms/${form.slug}/show/submissions`)
  await expect(page.getByTestId("form-submissions-page")).toBeVisible()
  await page.getByRole("button", { name: "Columns", exact: true }).click()

  const columnsDialog = page.getByRole("dialog", { name: "Columns" })
  await expect(columnsDialog.getByText("utm_source", { exact: true })).toHaveCount(0)
  await columnsDialog.getByRole("button", { name: /Attribution & tracking/ }).click()
  await expect(columnsDialog.getByText("utm_source", { exact: true })).toBeVisible()
  await columnsDialog.getByRole("button", { name: "Show detected", exact: true }).click()

  const attributedRow = page.getByRole("row").filter({ hasText: visitorName })
  await expect(attributedRow).toContainText("playwright")
  await expect(attributedRow).toContainText("e2e")
  await expect(attributedRow).toContainText("browser-click")

  await columnsDialog.getByRole("button", { name: "Hide URL parameters", exact: true }).click()
  await expect(page.getByRole("columnheader", { name: "utm_source", exact: true })).toHaveCount(0)
  await expect(page.getByRole("columnheader", { name: "utm_campaign", exact: true })).toHaveCount(0)
  await expect(page.getByRole("columnheader", { name: "gclid", exact: true })).toHaveCount(0)
})

test("SDK parent attribution is captured before an embedded auto-submit", async ({ page, request }) => {
  const form = await apiCreateForm(request, {
    title: uniqueTitle("SDK Auto Submit Attribution"),
    payloadOverrides: {
      properties: [
        {
          type: "nf-text",
          content: "<h1>SDK auto-submit attribution</h1>",
          name: "Title",
          id: "default_title",
        },
        buildTextField("sdk_auto_name", "Name"),
      ],
    },
  })
  const token = await apiLogin(request)
  const iframeUrl = `/forms/${form.slug}?auto_submit=true&sdk_auto_name=Auto%20SDK`

  await page.goto("/?utm_source=sdk-parent&utm_campaign=auto-submit")
  await page.setContent(`
    <!doctype html>
    <html>
      <body>
        <iframe id="${form.slug}" src="${iframeUrl}"></iframe>
        <script>
          setTimeout(() => {
            const sdk = document.createElement('script')
            sdk.src = '/widgets/opnform-sdk.js'
            sdk.onload = () => window.opnform.init({ autoResize: false, preventRedirect: true })
            document.body.appendChild(sdk)
          }, 750)
        </script>
      </body>
    </html>
  `)

  let submission: { meta?: { attribution?: Record<string, string> } } | undefined
  await expect.poll(async () => {
    const submissions = await apiListSubmissions(request, token, form.slug)
    submission = submissions.data.find((record: { data: Record<string, unknown> }) => (
      record.data.sdk_auto_name === "Auto SDK"
    ))
    return submission
  }, { timeout: 20_000 }).toBeTruthy()

  expect(submission?.meta?.attribution).toEqual({
    utm_source: "sdk-parent",
    utm_campaign: "auto-submit",
  })
})

test("popup embed falls back to valid parent attribution when its form URL value is empty", async ({ page, request }) => {
  const form = await apiCreateForm(request, { title: uniqueTitle("Popup Attribution") })
  const formUrl = `/forms/${form.slug}?utm_source=`
  const widgetData = JSON.stringify({ formurl: formUrl }).replaceAll('"', '&quot;')

  await page.goto("/?utm_source=popup-parent&utm_campaign=popup-test")
  await page.setContent(`
    <!doctype html>
    <html>
      <body>
        <script data-nf="${widgetData}" src="/widgets/embed.js"></script>
      </body>
    </html>
  `)
  await page.locator(".nf-emoji").click()

  const popupUrl = new URL(await page.locator(".nf-popup iframe").getAttribute("src") || "", page.url())
  expect(popupUrl.searchParams.get("utm_source")).toBe("popup-parent")
  expect(popupUrl.searchParams.get("utm_campaign")).toBe("popup-test")
})

test("classic public form submits successfully with mixed field components", async ({ page, request }) => {
  const form = await apiCreateForm(request, {
    title: uniqueTitle("Mixed Components"),
    payloadOverrides: {
      properties: [
        {
          type: "nf-text",
          content: "<h1>Mixed components</h1><p>Fill every field.</p>",
          name: "Title",
          id: crypto.randomUUID(),
        },
        buildTextField("full_name", "Full name", { required: true }),
        buildEmailField("contact_email", "Contact email", { required: true }),
        buildCheckboxField("accept_terms", "Accept terms", { required: true }),
        buildSelectField("plan", "Plan", ["Starter", "Growth", "Enterprise"], { required: true }),
        buildMultiSelectField("channels", "Preferred channels", ["Email", "Phone", "Slack"], { required: true }),
      ],
    },
  })

  await openPublicForm(page, form.slug)
  await fillFieldInput(page, "full_name", "Ada Lovelace")
  await fillFieldInput(page, "contact_email", uniqueEmail("mixed"))
  await checkFieldCheckbox(page, "accept_terms")
  await selectFlatOption(page, "plan", "Growth", "radio")
  await selectFlatOption(page, "channels", "Email", "checkbox")
  await selectFlatOption(page, "channels", "Slack", "checkbox")
  await page.getByRole("button", { name: /submit/i }).click()

  await expectSubmissionSuccess(page)
})

test("classic multi-page public form navigates across pages and submits", async ({ page, request }) => {
  const form = await apiCreateForm(request, {
    title: uniqueTitle("Multi Page"),
    payloadOverrides: {
      properties: [
        buildTextField("first_name", "First name", { required: true }),
        buildPageBreak("page_break_1", "Continue", "Back"),
        buildTextField("company_name", "Company name", { required: true }),
        buildPageBreak("page_break_2", "Next step", "Previous step"),
        buildEmailField("work_email", "Work email", { required: true }),
      ],
    },
  })

  await openPublicForm(page, form.slug)
  await expect(page.getByLabel("First name")).toBeVisible()
  await fillFieldInput(page, "first_name", "Grace")
  await page.getByRole("button", { name: "Continue", exact: true }).click()

  await expect(page.getByLabel("Company name")).toBeVisible()
  await fillFieldInput(page, "company_name", "Analytical Engines Inc")
  await page.getByRole("button", { name: "Back", exact: true }).click()
  await expect(page.getByLabel("First name")).toBeVisible()
  await page.getByRole("button", { name: "Continue", exact: true }).click()
  await page.getByRole("button", { name: "Next step", exact: true }).click()

  await expect(page.getByLabel("Work email")).toBeVisible()
  await fillFieldInput(page, "work_email", uniqueEmail("multipage"))
  await page.getByRole("button", { name: /submit/i }).click()

  await expectSubmissionSuccess(page)
})

test("public form surfaces required and invalid email validation errors", async ({ page, request }) => {
  const form = await apiCreateForm(request, {
    title: uniqueTitle("Validation"),
    payloadOverrides: {
      properties: [
        buildTextField("required_name", "Required name", { required: true }),
        buildEmailField("required_email", "Required email", { required: true }),
      ],
    },
  })

  await openPublicForm(page, form.slug)
  await page.getByRole("button", { name: /submit/i }).click()
  await expectFieldError(page, "required_name", "The Required name field is required.")
  await expectFieldError(page, "required_email", "The Required email field is required.")

  await fillFieldInput(page, "required_name", "Validation User")
  await fillFieldInput(page, "required_email", "not-an-email")
  await page.getByRole("button", { name: /submit/i }).click()
  await expectFieldError(page, "required_email", /valid email address/i)
})

for (const toggle of [false, true]) {
  for (const prefill of ["", "true", "false"]) {
    const checked = prefill === "true"
    test(`public form initial visibility with ${toggle ? "toggle" : "checkbox"} and ${prefill || "empty"} prefill`, async ({ page, request, browser }) => {
      const form = await apiCreateForm(request, {
        title: uniqueTitle("Initial Visibility"),
        payloadOverrides: {
          auto_save: false,
          properties: [
            buildCheckboxField("include_files", "Include files", { use_toggle_switch: toggle }),
            {
              id: "attachments",
              name: "Attach files (optional)",
              type: "files",
              hidden: false,
              required: false,
              logic: {
                conditions: {
                  identifier: "include_files",
                  value: {
                    operator: "is_not_checked",
                    property_meta: { id: "include_files", type: "checkbox" },
                  },
                },
                actions: ["hide-block"],
              },
            },
            buildTextField("internal", "Internal field", { hidden: true }),
          ],
        },
      })
      const path = `/forms/${form.slug}${prefill ? `?include_files=${prefill}` : ""}`
      const response = await request.get(path)
      expect(response.ok()).toBeTruthy()
      const html = await response.text()
      expect(html.includes('data-testid="open-form-field-attachments"')).toBe(checked)
      expect(html).not.toContain('data-testid="open-form-field-internal"')

      // Inspect the actual first paint without allowing hydration to hide a wrong SSR field.
      const context = await browser.newContext({ javaScriptEnabled: false })
      try {
        const firstRender = await context.newPage()
        await firstRender.goto(new URL(path, response.url()).href)
        await expect(firstRender.getByLabel("Include files", { exact: true })).toBeVisible()
        await expect(getOpenFormField(firstRender, "attachments")).toHaveCount(checked ? 1 : 0)
        await expect(getOpenFormField(firstRender, "internal")).toHaveCount(0)
      } finally {
        await context.close()
      }

      await openPublicForm(page, `${form.slug}${prefill ? `?include_files=${prefill}` : ""}`)
      await page.waitForLoadState("networkidle")
      const control = page.getByRole(toggle ? "switch" : "checkbox", { name: "Include files", exact: true })
      await expect(control).toBeChecked({ checked })
      await expect(getOpenFormField(page, "attachments")).toHaveCount(checked ? 1 : 0)
      await control.click()
      await expect(getOpenFormField(page, "attachments")).toHaveCount(checked ? 0 : 1)
      await control.click()
      await expect(getOpenFormField(page, "attachments")).toHaveCount(checked ? 1 : 0)
      await expect(getOpenFormField(page, "internal")).toHaveCount(0)
    })
  }
}

for (const toggle of [false, true]) {
  test(`initialized ${toggle ? "toggle" : "checkbox"} preserves required validation and submitted answers`, async ({ page, request }) => {
    const form = await apiCreateForm(request, {
      payloadOverrides: {
        auto_save: false,
        properties: [
          buildCheckboxField("consent", "Consent", { required: true, use_toggle_switch: toggle }),
          buildCheckboxField("optional", "Optional checkbox"),
          buildCheckboxField("internal", "Internal checkbox", { hidden: true, required: true }),
          buildTextField("details", "Details", {
            required: true,
            logic: {
              conditions: { identifier: "consent", value: {
                operator: "is_not_checked", property_meta: { id: "consent", type: "checkbox" },
              } },
              actions: ["hide-block"],
            },
          }),
        ],
      },
    })
    await openPublicForm(page, form.slug)
    await page.waitForLoadState("networkidle")
    await expect(getOpenFormField(page, "details")).toHaveCount(0)
    await page.getByRole("button", { name: /submit/i }).click()
    await expectFieldError(page, "consent", /Consent.*accepted/)

    const control = page.getByRole(toggle ? "switch" : "checkbox", { name: "Consent", exact: true })
    await control.focus()
    await control.press("Space")
    await expect(control).toBeChecked()
    await expect(getOpenFormField(page, "details")).toBeVisible()
    await page.getByRole("button", { name: /submit/i }).click()
    await expectFieldError(page, "details", /Details.*required/)
    await fillFieldInput(page, "details", "Preserved answer")
    await page.getByRole("button", { name: /submit/i }).click()
    await expectSubmissionSuccess(page)

    const submissions = await apiListSubmissions(request, await apiLogin(request), form.slug)
    expect(submissions.data).toHaveLength(1)
    expect(submissions.data[0].data).toMatchObject({ consent: true, optional: false, details: "Preserved answer" })
  })
}

for (const checked of [false, true]) {
  test(`checkbox initialization preserves ${checked ? "a checked" : "an unchecked"} draft, autosave and other answers`, async ({ page, request }, testInfo) => {
    const form = await apiCreateForm(request, {
      payloadOverrides: {
        auto_save: true,
        properties: [
          buildCheckboxField("include_files", "Include files", { prefill: !checked }),
          buildTextField("feedback", "Feedback", { prefill: "Configured answer" }),
          buildTextField("details", "Details", {
            logic: { conditions: { identifier: "include_files", value: {
              operator: "is_not_checked", property_meta: { id: "include_files", type: "checkbox" },
            } }, actions: ["hide-block"] },
          }),
        ],
      },
    })
    const definition = await request.get(`${API_BASE_URL}/forms/${form.slug}`)
    const publicForm = await definition.json()
    const url = new URL(`/forms/${form.slug}`, testInfo.project.use.baseURL as string).href
    const key = `${publicForm.form_pending_submission_key}-${hash(url)}`
    await page.addInitScript(({ key, checked }) => {
      if (localStorage.getItem(key) === null) {
        localStorage.setItem(key, JSON.stringify({ include_files: checked, feedback: "Saved answer" }))
      }
    }, { key, checked })
    await openPublicForm(page, form.slug)
    await page.waitForLoadState("networkidle")
    const control = page.getByRole("checkbox", { name: "Include files", exact: true })
    await expect(control).toBeChecked({ checked })
    await expect(page.getByLabel("Feedback", { exact: true })).toHaveValue("Saved answer")
    await expect(getOpenFormField(page, "details")).toHaveCount(checked ? 1 : 0)
    await fillFieldInput(page, "feedback", "Updated answer")
    await control.click()
    await expect.poll(async () => page.evaluate((key) => JSON.parse(localStorage.getItem(key) || "{}"), key))
      .toMatchObject({ include_files: !checked, feedback: "Updated answer" })
    await page.reload()
    await page.waitForLoadState("networkidle")
    await expect(control).toBeChecked({ checked: !checked })
    await expect(page.getByLabel("Feedback", { exact: true })).toHaveValue("Updated answer")
    await expect(getOpenFormField(page, "details")).toHaveCount(checked ? 0 : 1)
    await page.getByRole("button", { name: /submit/i }).click()
    await expectSubmissionSuccess(page)
    const submissions = await apiListSubmissions(request, await apiLogin(request), form.slug)
    expect(submissions.data[0].data).toMatchObject({ include_files: !checked, feedback: "Updated answer" })
    await expect.poll(async () => page.evaluate((key) => localStorage.getItem(key), key)).toBeNull()
  })
}

for (const required of [false, true]) {
  test(`focused ${required ? "required Yes" : "optional No"} checkbox stays unanswered and submits the selected value`, async ({ page, request }) => {
    const form = await apiCreateForm(request, {
      presentationStyle: "focused",
      payloadOverrides: {
        auto_save: false,
        settings: { navigation_arrows: true, auto_next: false },
        properties: [buildCheckboxField("choice", "Your choice", { required })],
      },
    })
    await openPublicForm(page, form.slug)
    await page.waitForLoadState("networkidle")
    const yes = page.getByRole("option", { name: /Yes/i })
    const no = page.getByRole("option", { name: /No/i })
    await expect(yes).toHaveAttribute("aria-selected", "false")
    await expect(no).toHaveAttribute("aria-selected", "false")
    if (required) {
      const validation = page.waitForResponse((response) => response.url().endsWith(`/forms/${form.slug}/answer`))
      await page.getByRole("button", { name: /submit/i }).click()
      expect((await validation).status()).toBe(422)
      await expect(yes).toHaveAttribute("aria-selected", "false")
      await expect(no).toHaveAttribute("aria-selected", "false")
    }
    await (required ? yes : no).click()
    await expect(required ? yes : no).toHaveAttribute("aria-selected", "true")
    await page.getByRole("button", { name: /submit/i }).click()
    await expectSubmissionSuccess(page)
    const submissions = await apiListSubmissions(request, await apiLogin(request), form.slug)
    expect(submissions.data[0].data.choice).toBe(required)
  })
}

test("checkbox initialization preserves answers when editing a stored submission", async ({ page, request }) => {
  const form = await apiCreateForm(request, {
    payloadOverrides: {
      auto_save: false,
      editable_submissions: true,
      properties: [
        buildCheckboxField("choice", "Your choice"),
        buildTextField("feedback", "Feedback", { required: true }),
      ],
    },
  })
  await openPublicForm(page, form.slug)
  await page.waitForLoadState("networkidle")
  await fillFieldInput(page, "feedback", "Original answer")
  const submitted = page.waitForResponse((response) => response.url().endsWith(`/forms/${form.slug}/answer`))
  await page.getByRole("button", { name: /submit/i }).click()
  await expectSubmissionSuccess(page)
  const { submission_id: submissionId } = await (await submitted).json()
  expect(submissionId).toBeTruthy()

  await openPublicForm(page, `${form.slug}?submission_id=${submissionId}`)
  await page.waitForLoadState("networkidle")
  await expect(page.getByRole("checkbox", { name: "Your choice", exact: true })).not.toBeChecked()
  await expect(page.getByLabel("Feedback", { exact: true })).toHaveValue("Original answer")
  await page.getByRole("checkbox", { name: "Your choice", exact: true }).check()
  await fillFieldInput(page, "feedback", "Edited answer")
  await page.getByRole("button", { name: /submit/i }).click()
  await expectSubmissionSuccess(page)
  const submissions = await apiListSubmissions(request, await apiLogin(request), form.slug)
  expect(submissions.data).toHaveLength(1)
  expect(submissions.data[0].data).toMatchObject({ choice: true, feedback: "Edited answer" })
})

test("public form logic reveals and requires follow-up details conditionally", async ({ page, request }) => {
  const form = await apiCreateForm(request, {
    title: uniqueTitle("Conditional Logic"),
    payloadOverrides: {
      properties: [
        buildMultiSelectField("support_need", "Support need", ["General question", "Need follow-up"], { required: true }),
        buildSelectField("follow_up_details", "Follow-up details", ["Call me", "Email me"], {
          hidden: true,
          required: false,
          logic: {
            conditions: {
              operatorIdentifier: "and",
              children: [
                {
                  identifier: "support_need",
                  value: {
                    operator: "contains",
                    property_meta: {
                      id: "support_need",
                      type: "multi_select",
                    },
                    value: "Need follow-up",
                  },
                },
              ],
            },
            actions: ["require-answer", "show-block"],
          },
        }),
      ],
    },
  })

  await openPublicForm(page, form.slug)
  await expect(page.getByLabel("Follow-up details")).toHaveCount(0)
  await selectFlatOption(page, "support_need", "Need follow-up", "checkbox")
  await expect(page.getByLabel("Follow-up details")).toBeVisible()

  await page.getByRole("button", { name: /submit/i }).click()
  await expectFieldError(page, "follow_up_details", "The Follow-up details field is required.")

  await selectFlatOption(page, "follow_up_details", "Call me", "radio")
  await page.getByRole("button", { name: /submit/i }).click()
  await expectSubmissionSuccess(page)
})

test("public multi-select form enforces minimum selection before allowing submission", async ({ page, request }) => {
  const form = await apiCreateForm(request, {
    title: uniqueTitle("Multi Select Validation"),
    payloadOverrides: {
      properties: [
        buildMultiSelectField("team_tools", "Team tools", ["Notion", "Slack", "Linear", "Figma"], {
          required: true,
          min_selection: 2,
        }),
      ],
    },
  })

  await openPublicForm(page, form.slug)
  await selectFlatOption(page, "team_tools", "Notion", "checkbox")
  await page.getByRole("button", { name: /submit/i }).click()
  await expectFieldError(page, "team_tools", "Please select at least 2 options")

  await selectFlatOption(page, "team_tools", "Slack", "checkbox")
  await page.getByRole("button", { name: /submit/i }).click()
  await expectSubmissionSuccess(page)
})

test("focused public form accepts a complete stepped response flow", async ({ page, request }) => {
  const form = await apiCreateForm(request, {
    title: uniqueTitle("Focused Response"),
    presentationStyle: "focused",
    payloadOverrides: {
      properties: [
        buildTextField("focused_name", "Your name", { required: true }),
        buildEmailField("focused_email", "Your email", { required: true }),
        {
          id: "focused_goal",
          name: "Primary goal",
          type: "select",
          hidden: false,
          required: true,
          allow_creation: false,
          select: {
            options: buildOptionList(["Lead generation", "Feedback"]),
          },
        },
      ],
    },
  })

  await openPublicForm(page, form.slug)
  await fillLabeledInput(page, "Your name", "Focused User")
  const next = page.getByRole("button", { name: /next/i })
  // The outgoing step stays in the DOM until its slide animation completes.
  await expect(next).toHaveCount(1)
  await next.click()
  await fillLabeledInput(page, "Your email", uniqueEmail("focused"))
  await expect(next).toHaveCount(1)
  await next.click()
  await page.getByRole("option", { name: /Lead generation/i }).click()

  await expectSubmissionSuccess(page)
})

for (const shared of [false, true]) {
  test('iframe answer sharing is opt in: ' + shared, async ({ page, request }) => {
    const form = await apiCreateForm(request, { payloadOverrides: { share_submission_data_with_parent: shared } })
    const base = process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:3100'
    const html = '<script>window.received=[];addEventListener("message",e=>{if(e.data?.type==="form-submitted")window.received.push(e.data)})</script><iframe src="' + base + '/forms/' + form.slug + '"></iframe>'
    const host = createServer((_req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(html) })
    await new Promise(resolve => host.listen(0, '127.0.0.1', resolve))
    try {
      const address = host.address()
      if (!address || typeof address === 'string') throw new Error('Missing iframe host address')
      await page.goto('http://127.0.0.1:' + address.port)
      const frame = page.frameLocator('iframe')
      await expect(frame.getByTestId('public-form-page')).toBeVisible()
      await page.waitForLoadState('networkidle')
      for (const [field, value] of [['default_name', 'Private QA answer'], ['default_email', '[email protected]']]) {
        const input = frame.getByTestId('open-form-field-' + field).locator('input').first()
        await input.click()
        await input.fill('')
        await input.pressSequentially(value)
        await input.blur()
      }
      const response = page.waitForResponse(response => response.request().method() === 'POST' && response.url().includes('/' + form.slug + '/answer'))
      await frame.getByRole('button', { name: /submit/i }).click()
      expect((await response).ok()).toBeTruthy()
      await expect.poll(() => page.evaluate<number>('window.received.length')).toBe(1)
      const payload = await page.evaluate<{ submission_data?: unknown }>('window.received[0]')
      if (shared) expect(JSON.stringify(payload.submission_data)).toContain('Private QA answer')
      else {
        expect(payload).not.toHaveProperty('submission_data')
        expect(payload).not.toHaveProperty('meta')
      }
    } finally {
      await new Promise(resolve => host.close(resolve))
    }
  })
}

for (const viewport of [{ name: "desktop", width: 1280 }, { name: "mobile", width: 390 }]) {
  test(`integration retry confirms its submission and refreshes the outcome on ${viewport.name}`, async ({ page, request }) => {
    await page.setViewportSize({ width: viewport.width, height: 844 })
    const form = await apiCreateForm(request, { title: uniqueTitle("Integration Retry") })
    const token = await apiLogin(request)
    const created = await request.post(`${API_BASE_URL}/open/forms/${form.id}/integrations`, {
      headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
      data: { status: "active", integration_id: "webhook", data: { webhook_url: "https://example.com/retry-test" } },
    })
    expect(created.ok()).toBeTruthy()
    const integrationId = (await created.json()).form_integration.id
    const eventsPath = `**/open/forms/${form.id}/integrations/${integrationId}/events`
    const failure = { id: 9001, date: "2026-10-03 14:00", status: "Error", data: { submission_id: 123 }, can_retry: true }
    const reason = "A more recent attempt exists for this submission."
    let retryCount = 0
    await page.route(eventsPath, route => route.fulfill({ json: retryCount
      ? [{ ...failure, can_retry: false, retry_unavailable_reason: reason }, { ...failure, id: 9002, status: "Skipped", can_retry: false }]
      : [failure] }))
    await page.route(`${eventsPath}/9001/retry`, route => {
      expect(route.request().method()).toBe("POST")
      retryCount++
      return route.fulfill({ json: { type: "warning", message: "No request was sent because the integration conditions were not met." } })
    })

    await loginUi(page)
    await page.goto(`/forms/${form.slug}/show/integrations`)
    const card = page.getByText("Webhook Notification", { exact: true }).locator("..").locator("..")
    await card.locator('button[aria-haspopup="menu"]').click()
    await page.getByRole("menuitem", { name: "Past Events" }).click()
    const history = page.getByRole("dialog", { name: "Integration events", exact: true })
    const retryButton = history.getByRole("button", { name: "Retry event 9001 for submission 123" })
    await expect(retryButton).toBeVisible()
    if (viewport.name === "mobile") {
      const table = history.getByLabel("Integration event history")
      expect(await table.evaluate(element => element.scrollWidth > element.clientWidth)).toBe(true)
    }

    await retryButton.click()
    const confirmation = page.getByRole("dialog", { name: "Retry submission #123?", exact: true })
    await expect(confirmation).toContainText("Retry submission #123?")
    await expect(confirmation).toContainText("latest saved answers")
    await expect(confirmation).toContainText("may create duplicates")
    await confirmation.getByRole("button", { name: "Cancel", exact: true }).click()
    await expect(confirmation).not.toBeVisible()
    expect(retryCount).toBe(0)

    await retryButton.click()
    await confirmation.getByRole("button", { name: "Retry integration", exact: true }).click()
    await expect(history.getByText("Skipped", { exact: true })).toBeVisible()
    await expect(history.getByText(reason, { exact: true })).toBeVisible()
    await expect(retryButton).toHaveCount(0)
    expect(retryCount).toBe(1)
  })
}

for (const style of ["classic", "focused"] as const) {
  for (const enabled of [true, false]) {
    test(`${style} submission confetti enabled=${enabled}`, async ({ page, request }, testInfo) => {
      const errors: string[] = []
      page.on("pageerror", error => errors.push(error.message))
      const form = await apiCreateForm(request, {
        presentationStyle: style,
        payloadOverrides: {
          confetti_on_submission: enabled,
          properties: [buildTextField("confetti_name", "Your name", { required: true })],
        },
      })
      await openPublicForm(page, form.slug)
      await expect(page.locator("#confetti-canvas")).toHaveCount(0)
      await fillLabeledInput(page, "Your name", "Confetti Visitor")
      await page.getByRole("button", { name: /submit/i }).click()
      await expectSubmissionSuccess(page)

      if (enabled) {
        await expect(page.locator("#confetti-canvas")).toBeVisible()
        // Check real painted particles, not just an empty canvas element.
        await expect.poll(() => page.locator("#confetti-canvas").evaluate((canvas: HTMLCanvasElement) => {
          const pixels = canvas.getContext("2d")!.getImageData(0, 0, canvas.width, canvas.height).data
          return pixels.some((value, index) => index % 4 === 3 && value > 0)
        })).toBe(true)
        await testInfo.attach("confetti-after-submission", { body: await page.screenshot(), contentType: "image/png" })
      } else {
        await expect(page.locator("#confetti-canvas")).toHaveCount(0)
      }
      const token = await apiLogin(request)
      const submissions = await apiListSubmissions(request, token, form.slug)
      expect(JSON.stringify(submissions)).toContain("Confetti Visitor")
      expect(errors).toEqual([])
    })
  }
}