AI Suggestions

First-prompt helpers for an empty chat: a fanned hand of suggestion cards that fly into the field, two drifting marquee rows of prompts, and a ghost completion with a wheel of alternative endings.

Installation

Installation

One command adds ai-suggestions and the shared AI Kit layer it is built on (tokens, faces, marks and brand icons). No animation library, light and dark built in.

$npx shadcn@latest add https://tweenui.dev/r/ai-suggestions.json
ai-suggestions-demo
components/ui/ai-suggestions-demo.tsx
"use client"

import * as React from "react"
import {
  ArrowUp,
  BookOpen,
  Bug,
  ChartLine,
  Image as ImageIcon,
  Languages,
  LayoutGrid,
  ListChecks,
  Rocket,
  Search,
  Sparkles,
  Type,
  WandSparkles,
} from "lucide-react"

import { AiDemo } from "@/lib/ai-demo"
import {
  AiStyle,
  Face,
  Roll,
  typeInto,
  useAiLoop,
  useIdleHands,
  type AiMood,
} from "@/lib/ai-kit"
import {
  AiNextWords,
  AiSuggestionHand,
  AiSuggestionMarquee,
  type AiSuggestion,
} from "@/registry/tween/ai-suggestions"

const CSS = `
.aik-sgd-scene{display:grid;grid-template-columns:minmax(0,1fr);gap:10px;justify-items:center;width:min(100%,580px)}
.aik-sgd-scene > *{min-width:0;max-width:100%}
.aik-sgd-field{--aik-r-shell:24px;--aik-rim:5px;position:relative;z-index:40;width:min(100%,470px)}
.aik-sgd-box{display:flex;align-items:center;gap:10px;height:54px;padding:0 9px 0 13px;font-size:15px}
.aik-sgd-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.aik-sgd-text[data-ph]{color:var(--aik-text-3)}
.aik-sgd-text[data-land]{animation:aik-sgd-land 440ms var(--aik-ease-move) both}
@keyframes aik-sgd-land{from{opacity:0;transform:translateY(16px) scale(.94)}}
.aik-sgd-send{display:grid;place-items:center;width:36px;height:36px;flex:none;border-radius:11px;color:var(--aik-pri-ink);background:color-mix(in oklab,var(--aik-raised) 78%,var(--aik-text) 22%);transition:background var(--aik-d-state) var(--aik-ease-out)}
.aik-sgd-send[data-ready]{background:var(--aik-pri)}
.aik-sgd-note{height:20px;font-size:13px;line-height:20px;color:var(--aik-text-2)}
.aik-sgd-bot{display:grid;grid-template-columns:28px minmax(0,1fr);gap:10px;align-items:start;width:min(100%,560px);min-height:54px;padding:0 8px;font-size:15px;line-height:24px}
.aik-sgd-bot p{padding-top:2px;animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
.aik-sgd-bot[data-off]{visibility:hidden}
@media (prefers-reduced-motion: reduce){.aik-sgd-text[data-land]{animation:none}}
`

const wait = (ms: number) =>
  new Promise<void>((resolve) => window.setTimeout(resolve, ms))

function Art({ kind }: { kind: "bars" | "lines" | "wave" | "page" | "grid" }) {
  const stroke = {
    fill: "none",
    stroke: "currentColor",
    strokeWidth: 3,
    strokeLinecap: "round" as const,
    strokeLinejoin: "round" as const,
  }
  return (
    <svg width="92" height="48" viewBox="0 0 92 48" aria-hidden="true">
      {kind === "bars" ? (
        <g fill="currentColor">
          <rect x="6" y="14" width="22" height="30" rx="5" opacity=".55" />
          <rect x="35" y="4" width="22" height="40" rx="5" />
          <rect x="64" y="20" width="22" height="24" rx="5" opacity=".55" />
        </g>
      ) : null}
      {kind === "lines" ? (
        <g {...stroke}>
          <path d="M8 12h76" />
          <path d="M8 24h52" opacity=".7" />
          <path d="M8 36h30" opacity=".45" />
        </g>
      ) : null}
      {kind === "wave" ? (
        <g {...stroke}>
          <path d="M6 30c10 0 10-16 20-16s10 22 20 22 10-26 20-26 10 12 20 12" />
          <circle cx="46" cy="36" r="4" fill="currentColor" stroke="none" />
        </g>
      ) : null}
      {kind === "page" ? (
        <g {...stroke}>
          <rect x="22" y="4" width="48" height="40" rx="6" opacity=".6" />
          <path d="M32 16h28M32 25h28M32 34h16" />
        </g>
      ) : null}
      {kind === "grid" ? (
        <g fill="currentColor">
          <rect x="10" y="6" width="32" height="16" rx="5" />
          <rect x="48" y="6" width="34" height="16" rx="5" opacity=".55" />
          <rect x="10" y="27" width="20" height="16" rx="5" opacity=".55" />
          <rect x="36" y="27" width="46" height="16" rx="5" opacity=".8" />
        </g>
      ) : null}
    </svg>
  )
}

const CARDS: AiSuggestion[] = [
  {
    id: "pricing",
    title: "Pricing section",
    prompt: "Add a pricing section with a monthly and yearly toggle",
    icon: <LayoutGrid size={16} />,
    art: <Art kind="bars" />,
    tone: "blue",
  },
  {
    id: "reveal",
    title: "Reveal the hero",
    prompt: "Make the hero headline reveal word by word on load",
    icon: <WandSparkles size={16} />,
    art: <Art kind="lines" />,
    tone: "violet",
  },
  {
    id: "bento",
    title: "Feature bento",
    prompt: "Build a bento grid of five features with hover motion",
    icon: <Sparkles size={16} />,
    art: <Art kind="grid" />,
    tone: "teal",
  },
  {
    id: "fix",
    title: "Fix a jump",
    prompt: "Find out why my slider jumps when I start dragging",
    icon: <Bug size={16} />,
    art: <Art kind="wave" />,
    tone: "rose",
  },
  {
    id: "docs",
    title: "Write the docs",
    prompt: "Write a docs page for text-skew-reveal with its props",
    icon: <BookOpen size={16} />,
    art: <Art kind="page" />,
    tone: "amber",
  },
]

function Field({
  text,
  working,
  mood,
  placeholder,
}: {
  text: string
  working: boolean
  mood: AiMood
  placeholder: string
}) {
  return (
    <div className="aik-shell aik-sgd-field">
      <div className="aik-surface aik-sgd-box">
        <Face size={26} shape="orb" mood={mood} />
        {text ? (
          <span key={text} className="aik-sgd-text" data-land="">
            {text}
          </span>
        ) : (
          <span className="aik-sgd-text" data-ph="">
            {placeholder}
          </span>
        )}
        <span className="aik-sgd-send" data-ready={text ? "" : undefined}>
          <ArrowUp size={18} />
        </span>
        <i className="aik-beam" data-on={working ? "" : undefined} />
      </div>
    </div>
  )
}

/** The shared response to a pick: the prompt lands in the field, the agent works, then reports. */
function usePick(restNote: string) {
  const [picked, setPicked] = React.useState<string | null>(null)
  const [text, setText] = React.useState("")
  const [working, setWorking] = React.useState(false)
  const [note, setNote] = React.useState(restNote)
  const [deal, setDeal] = React.useState(0)
  const run = React.useRef(0)
  const reset = React.useCallback(() => {
    setPicked(null)
    setText("")
    setWorking(false)
    setNote(restNote)
    setDeal((count) => count + 1)
  }, [restNote])
  const play = React.useCallback(
    async (item: AiSuggestion, sleep: (ms: number) => Promise<void>) => {
      const mine = ++run.current
      const alive = () => run.current === mine
      setPicked(item.id)
      await sleep(430)
      if (!alive()) return
      setText(item.prompt)
      await sleep(500)
      if (!alive()) return
      setWorking(true)
      setNote("Mira is on it")
      await sleep(1000)
      if (!alive()) return
      setWorking(false)
      setNote("Done. Ready for you to review.")
      await sleep(700)
      if (!alive()) return
      reset()
    },
    [reset]
  )
  const mood: AiMood = working ? "work" : text ? "listen" : "idle"
  return { picked, text, working, note, deal, play, reset, run, mood }
}

function Hand() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const [lifted, setLifted] = React.useState<string | null>(null)
  const pick = usePick("Pick a card to start")
  const { play, reset, run } = pick

  useAiLoop(
    root,
    async ({ sleep }) => {
      run.current++
      reset()
      setLifted(null)
      await sleep(1500)
      for (const id of ["reveal", "fix", "bento"]) {
        setLifted(id)
        await sleep(720)
      }
      setLifted(null)
      const item = CARDS[2]
      if (item) await play(item, sleep)
      await sleep(500)
    },
    { gap: 300, enabled: !hands }
  )

  return (
    <div
      ref={root}
      className="aik-sgd-scene"
      onPointerDown={touch}
      onKeyDown={touch}
    >
      <Field
        text={pick.text}
        working={pick.working}
        mood={pick.mood}
        placeholder="Ask Mira to build something"
      />
      <div className="aik-sgd-note">
        <Roll>{pick.note}</Roll>
      </div>
      <AiSuggestionHand
        key={pick.deal}
        items={CARDS}
        picked={pick.picked}
        lifted={lifted}
        fly={150}
        onPick={(item) => void play(item, wait)}
      />
    </div>
  )
}

const ROWS: AiSuggestion[][] = [
  [
    {
      id: "m-pricing",
      title: "Add a pricing section",
      prompt: "Add a pricing section with a monthly and yearly toggle",
      icon: <LayoutGrid size={16} />,
    },
    {
      id: "m-reveal",
      title: "Reveal the hero word by word",
      prompt: "Make the hero headline reveal word by word on load",
      icon: <Type size={16} />,
    },
    {
      id: "m-fix",
      title: "Fix my slider",
      prompt: "Find out why my slider jumps when I start dragging",
      icon: <Bug size={16} />,
    },
    {
      id: "m-chart",
      title: "Chart last week's signups",
      prompt: "Draw a line chart of last week's signups by day",
      icon: <ChartLine size={16} />,
    },
    {
      id: "m-ship",
      title: "Ship it",
      prompt: "Run the checks and open a pull request",
      icon: <Rocket size={16} />,
    },
  ],
  [
    {
      id: "m-docs",
      title: "Write the docs page",
      prompt: "Write a docs page for text-skew-reveal with its props",
      icon: <BookOpen size={16} />,
    },
    {
      id: "m-image",
      title: "Make a hero image",
      prompt: "Generate a hero image in three sizes",
      icon: <ImageIcon size={16} />,
    },
    {
      id: "m-find",
      title: "Find unused components",
      prompt: "Find components in the registry that nothing imports",
      icon: <Search size={16} />,
    },
    {
      id: "m-translate",
      title: "Translate to Arabic",
      prompt: "Translate the landing page copy to Arabic",
      icon: <Languages size={16} />,
    },
    {
      id: "m-plan",
      title: "Plan the launch",
      prompt: "Write a launch checklist for the new registry",
      icon: <ListChecks size={16} />,
    },
  ],
]

function Marquee() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const pick = usePick("Pick one as it passes")
  const { play, reset, run } = pick

  useAiLoop(
    root,
    async ({ sleep }) => {
      run.current++
      reset()
      await sleep(3200)
      const item = ROWS[0]?.[1]
      if (item) await play(item, sleep)
      await sleep(400)
    },
    { gap: 300, enabled: !hands }
  )

  return (
    <div
      ref={root}
      className="aik-sgd-scene"
      onPointerDown={touch}
      onKeyDown={touch}
    >
      <Field
        text={pick.text}
        working={pick.working}
        mood={pick.mood}
        placeholder="Ask Mira to build something"
      />
      <div className="aik-sgd-note">
        <Roll>{pick.note}</Roll>
      </div>
      <AiSuggestionMarquee
        rows={[
          ...ROWS,
          [...(ROWS[0] ?? []).slice(2), ...(ROWS[1] ?? []).slice(0, 3)].map(
            (item) => ({ ...item, id: `${item.id}-b` })
          ),
        ]}
        picked={pick.picked}
        onPick={(item) => void play(item, wait)}
      />
    </div>
  )
}

const ENDINGS: Array<[string, string[]]> = [
  [
    "add a testimonial",
    [
      " carousel that pauses on hover",
      " grid with star ratings",
      " section under the pricing",
    ],
  ],
  [
    "add",
    [
      " a pricing section with a toggle",
      " a hero that reveals word by word",
      " a footer with a sitemap",
    ],
  ],
  [
    "fix",
    [
      " the lint errors in this file",
      " the slider that jumps on drag",
      " the contrast in dark mode",
    ],
  ],
]
const GENERIC = [
  " with a hover state",
  " that works on a phone",
  " using what is in the registry",
]

function endingsFor(value: string) {
  const text = value.trim().toLowerCase()
  if (text.length < 3) return []
  return ENDINGS.find(([start]) => text.startsWith(start))?.[1] ?? GENERIC
}

function NextWords() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const [value, setValue] = React.useState("")
  const [active, setActive] = React.useState(0)
  const [quiet, setQuiet] = React.useState(false)
  const [reply, setReply] = React.useState("")
  const run = React.useRef(0)

  const answer = React.useCallback(
    async (text: string, sleep: (ms: number) => Promise<void>) => {
      const mine = ++run.current
      setQuiet(true)
      setReply("")
      await sleep(600)
      if (run.current !== mine) return
      setReply(`On it: ${text.charAt(0).toLowerCase()}${text.slice(1)}.`)
      await sleep(2600)
      if (run.current !== mine) return
      setValue("")
      setReply("")
      setQuiet(false)
    },
    []
  )

  useAiLoop(
    root,
    async ({ sleep }) => {
      run.current++
      setValue("")
      setReply("")
      setQuiet(false)
      setActive(0)
      await sleep(900)
      await typeInto(setValue, "Add a testimonial", sleep, 46)
      await sleep(1000)
      for (const row of [1, 2, 1, 0]) {
        setActive(row)
        await sleep(820)
      }
      const full = `Add a testimonial${endingsFor("Add a testimonial")[0] ?? ""}`
      setValue(full)
      setQuiet(true)
      await sleep(900)
      await answer(full, sleep)
      await sleep(300)
    },
    { gap: 300, enabled: !hands }
  )

  const endings = quiet ? [] : endingsFor(value)
  return (
    <div
      ref={root}
      className="aik-sgd-scene"
      onPointerDown={touch}
      onKeyDown={touch}
    >
      <AiNextWords
        value={value}
        onValueChange={(next) => {
          setQuiet(false)
          setActive(0)
          setValue(next)
        }}
        endings={endings}
        active={active}
        onActiveChange={setActive}
        onAccept={(full) => {
          setValue(full)
          setQuiet(true)
        }}
        onDismiss={() => setQuiet(true)}
        onSubmit={(text) => void answer(text, wait)}
        placeholder="Describe what to build"
      />
      <div className="aik-sgd-bot" data-off={reply ? undefined : ""}>
        <Face size={28} shape="orb" mood="talk" />
        {reply ? <p key={reply}>{reply}</p> : <p />}
      </div>
    </div>
  )
}

export function AiSuggestionsDemo({ only }: { only?: string }) {
  return (
    <>
      <AiStyle id="ai-suggestions-demo" css={CSS} />
      <AiDemo
        only={only}
        tabs={[
          { name: "Card hand", node: <Hand /> },
          { name: "Marquee", node: <Marquee /> },
          { name: "Next words", node: <NextWords /> },
        ]}
      />
    </>
  )
}

Installation

pnpm dlx shadcn@latest add https://tweenui.dev/r/ai-suggestions.json

Usage

import {
  AiNextWords,
  AiSuggestionHand,
  AiSuggestionMarquee,
} from "@/components/ui/ai-suggestions"
const [picked, setPicked] = useState<string | null>(null)
 
<AiSuggestionHand
  items={[
    {
      id: "pricing",
      title: "Pricing section",
      prompt: "Add a pricing section with a monthly and yearly toggle",
      icon: <LayoutGrid size={16} />,
      tone: "blue",
    },
    // four or five in total
  ]}
  picked={picked}
  onPick={(item) => {
    setPicked(item.id)
    setPrompt(item.prompt)
  }}
/>

Place the hand or the marquee under your prompt field. Set picked when a suggestion is chosen and it leaves toward the field; clear it to deal the cards again.

Versions

  • AiSuggestionHand fans four or five cards in an arc. A card lifts and straightens under the pointer or focus. The picked card flies up fly pixels and shrinks while the rest fold away to the sides. Arrow keys move between cards.
  • AiSuggestionMarquee drifts rows of pills in opposite directions behind soft edges. Rows hold still on hover and focus, and the picked pill lifts out. With reduced motion the rows wrap and stay put.
  • AiNextWords is a field that finishes your sentence. A grey ending follows the caret on a wheel of alternatives: Arrow Up and Arrow Down roll it, Tab accepts, Escape dismisses, Enter sends.

Props

AiSuggestion

FieldTypeDescription
idstringMatched against picked.
titlestringThe short name on a card or pill.
promptstringThe full prompt, shown as the card's sample line.
iconReactNodeA 16px icon.
artReactNodeA small illustration for the card's art strip.
tonestringArt strip colour: a named tone or any CSS colour.

AiSuggestionHand

PropTypeDefaultDescription
itemsAiSuggestion[]Four or five work best.
pickedstring | nullnullThe id of the card that flies up.
liftedstring | nullnullHolds a card lifted, as hover does.
onPick(item: AiSuggestion) => voidCalled on click or Enter.
flynumber180How far the picked card travels, in pixels.

AiSuggestionMarquee

PropTypeDefaultDescription
rowsAiSuggestion[][]One array per row.
pickedstring | nullnullThe id of the pill that lifts out.
onPick(item: AiSuggestion) => voidCalled on click or Enter.
pausedbooleanfalseHolds the rows still.
durationnumber38Seconds for one loop of the first row.

AiNextWords

PropTypeDefaultDescription
valuestringThe typed text.
onValueChange(value: string) => voidCalled on every edit.
endingsstring[]Possible endings. Pass an empty array to hide the ghost.
activenumberThe ending on the line. Omit to let the keys manage it.
onActiveChange(index: number) => voidCalled when the wheel rolls.
onAccept(value: string) => voidCalled on Tab with the text plus the ending.
onDismiss() => voidCalled on Escape.
onSubmit(value: string) => voidCalled on Enter.