Aadi

Form Widget

AI chats

About

A form an agent asks you to fill before it acts: fields stream in, validate, send and fold into a summary.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Form Widget to your project and fits it to your theme.

Code

How Form Widget is used: the demo's code. The component's own source comes with a free account.

Usage.tsx

"use client"

import * as React from "react"
import { FormField, FormValues, FormWidget, FormWidgetStatus } from "@/components/ui/form-widget"

const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches

/** What a coding agent asks for before it provisions a staging database. */
const FIELDS: FormField[] = [
  {
    name: "project",
    label: "Project name",
    required: true,
    placeholder: "lowercase-with-hyphens",
    pattern: "[a-z0-9-]{3,40}",
    patternMessage: "Use 3 to 40 lowercase letters, numbers or hyphens.",
    width: "half",
  },
  {
    name: "region",
    label: "Region",
    type: "select",
    required: true,
    width: "half",
    options: [
      { value: "us-east-1", label: "US East (N. Virginia)" },
      { value: "eu-central-1", label: "EU (Frankfurt)" },
      { value: "ap-southeast-1", label: "Asia Pacific (Singapore)" },
    ],
  },
  {
    name: "owner",
    label: "Owner email",
    type: "email",
    required: true,
    placeholder: "[email protected]",
    autoComplete: "email",
  },
  {
    name: "size",
    label: "Compute size",
    type: "radio",
    required: true,
    defaultValue: "small",
    options: [
      { value: "small", label: "Small", description: "0.25 vCPU, 1 GB RAM. Fine for preview traffic." },
      { value: "medium", label: "Medium", description: "1 vCPU, 4 GB RAM. Load tests and demos." },
    ],
  },
  {
    name: "seed",
    label: "Copy anonymized production data",
    type: "checkbox",
    hint: "Adds about 6 minutes to setup.",
  },
]

/** The answers the tour fills in, one field at a time. */
const ANSWERS: [string, FormValues[string]][] = [
  ["project", "tallyline-staging"],
  ["region", "eu-central-1"],
  ["owner", "[email protected]"],
  ["size", "medium"],
  ["seed", true],
]

type Step =
  | { kind: "stream"; fields: number }
  | { kind: "fill"; answers: number }
  | { kind: "sending" }
  | { kind: "sent" }

const STEPS: { step: Step; ms: number }[] = [
  ...FIELDS.map((_, i) => ({ step: { kind: "stream", fields: i + 1 } as Step, ms: i === 0 ? 700 : 320 })),
  ...ANSWERS.map((_, i) => ({ step: { kind: "fill", answers: i + 1 } as Step, ms: i === 0 ? 900 : 480 })),
  { step: { kind: "sending" }, ms: 1100 },
  { step: { kind: "sent" }, ms: 900 },
]

const SENT_HOLD_MS = 2600

const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"

/**
 * 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
 * phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
 * render white on dark pages. FitFrame fills the frame exactly instead.
 *
 * - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
 * - "crop": the content stays at full size from the top and fades out at the bottom. For text
 *   that streams in, where a changing scale would make the page breathe.
 *
 * `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
 * to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
 * shrinks evenly on both sides.
 *
 * Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
 * shorter than `hideBelow`, so a profile card shows the visual alone.
 */
function FitFrame({
  children,
  mode = "scale",
  hideBelow = 360,
  minWidth,
}: {
  children: React.ReactNode
  mode?: "scale" | "crop"
  hideBelow?: number
  minWidth?: string
}) {
  const content = React.useRef<HTMLDivElement>(null)
  const [cropped, setCropped] = React.useState(false)

  React.useLayoutEffect(() => {
    const el = content.current
    if (!el) return
    const measure = () => {
      const vw = window.innerWidth
      const vh = window.innerHeight
      el.toggleAttribute("data-fit-small", vh < hideBelow)
      // Layout sizes ignore the transform, so measuring never feeds back.
      const w = Math.max(el.offsetWidth, el.scrollWidth)
      const h = Math.max(el.offsetHeight, el.scrollHeight)
      const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
      el.style.transform = scale < 1 ? `scale(${scale})` : ""
      setCropped(mode === "crop" && h > vh + 1)
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(el)
    // Content that changes inside a fixed width box (a headline that cycles words) never resizes
    // the box itself, so changes below it measure again on the next frame.
    let frame = 0
    const mutations = new MutationObserver(() => {
      cancelAnimationFrame(frame)
      frame = requestAnimationFrame(measure)
    })
    mutations.observe(el, { subtree: true, childList: true, characterData: true })
    window.addEventListener("resize", measure)
    return () => {
      observer.disconnect()
      mutations.disconnect()
      cancelAnimationFrame(frame)
      window.removeEventListener("resize", measure)
    }
  }, [mode, hideBelow])

  const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
  return (
    <div
      className="flex w-full justify-center overflow-hidden"
      style={{
        height: "100dvh",
        alignItems: mode === "crop" ? "flex-start" : "center",
        maskImage: cropped ? fade : undefined,
        WebkitMaskImage: cropped ? fade : undefined,
      }}
    >
      <style>{FIT_CSS}</style>
      <div
        ref={content}
        className="w-full shrink-0"
        style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
      >
        {children}
      </div>
    </div>
  )
}

/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
  return (
    <p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
      {children}{" "}
      <a
        href={`https://chatcn.dev/docs/components/${slug}`}
        target="_blank"
        rel="noopener"
        className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
      >
        chatcn.dev
      </a>
    </p>
  )
}

/**
 * An agent asks for what it needs before creating a staging database: the form streams in field
 * by field, gets filled, is sent and folds into a summary of the answers. Loops. Click into the
 * form and the tour stops so you can fill it yourself.
 */
export default function FormWidgetPreview() {
  const [at, setAt] = React.useState(0)
  const [user, setUser] = React.useState(false)

  React.useEffect(() => {
    if (user) return
    if (reducedMotion()) {
      setAt(FIELDS.length + ANSWERS.length - 1)
      return
    }
    const last = at === STEPS.length - 1
    const id = window.setTimeout(
      () => setAt((n) => (n + 1) % STEPS.length),
      last ? SENT_HOLD_MS : STEPS[at + 1]!.ms,
    )
    return () => window.clearTimeout(id)
  }, [at, user])

  const step = STEPS[at]!.step
  const answers = Object.fromEntries(
    ANSWERS.slice(0, step.kind === "fill" ? step.answers : step.kind === "stream" ? 0 : ANSWERS.length),
  ) as FormValues
  const fields = step.kind === "stream" ? FIELDS.slice(0, step.fields) : FIELDS
  const status: FormWidgetStatus = step.kind === "sending" ? "submitting" : step.kind === "sent" ? "submitted" : "idle"

  return (
    <FitFrame minWidth="38rem">
      <div className="flex w-full flex-col items-center justify-center gap-4 p-6">
        {/* As tall as the open form, so the sent summary keeps the same scale. */}
        <div
          className="flex min-h-[31rem] w-full max-w-xl flex-col justify-center"
          onPointerDownCapture={() => setUser(true)}
        >
          {user ? (
            <FormWidget
              key="user"
              title="Details for the staging database"
              description="I need these before I create the project. Nothing is provisioned until you send them."
              fields={FIELDS}
              submitLabel="Create project"
              onSubmit={() => new Promise((r) => setTimeout(r, 900))}
              onCancel={() => {}}
            />
          ) : (
            <FormWidget
              // Prefilled values are read on mount, so each filled answer mounts the form again.
              key={step.kind === "fill" ? `fill-${step.answers}` : step.kind}
              title="Details for the staging database"
              description="I need these before I create the project. Nothing is provisioned until you send them."
              fields={fields}
              streaming={step.kind === "stream" && step.fields < FIELDS.length}
              expectedFields={FIELDS.length}
              status={status}
              values={answers}
              submitLabel="Create project"
              onSubmit={() => {}}
              onCancel={() => {}}
            />
          )}
        </div>
        <MoreOn slug="form-widget">Forms an agent asks you to fill before it acts. On</MoreOn>
      </div>
    </FitFrame>
  )
}

More by Aadi

View all
  • Stat Card

    Stat Card

    46
  • Audio Visualizer

    Audio Visualizer

    32
  • Dither Orb

    Dither Orb

    24
  • Voice Orb

    Voice Orb

    20
  • Weather Card

    Weather Card

    18
  • Waveform

    Waveform

    15
  • Ticker Card

    Ticker Card

    15
  • Message Feedback

    Message Feedback

    13

More in AI chats

View all
  • AI Actions

    AI Actions

    351
  • Aquarium Prompt

    Aquarium Prompt

    113
  • Agent Chat

    Agent Chat

    21
  • Message With Header And Delivery Status

    Message With Header And Delivery Status

    60
  • Research Report

    Research Report

    7
  • Tool Web Fetch

    Tool Web Fetch

    4
  • Color Picker

    Color Picker

    201
  • Suggestions

    Suggestions

    40

Explore more

Part of chatcn — browse the full library on 21st.dev.