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.
"use client"
import * as React from "react"
import {
AiKitStyles,
AiStyle,
cx,
Face,
toneColor,
type AiShape,
type AiTone,
} from "@/lib/ai-kit"
const CSS = `
.aik-sg-hand{position:relative;width:min(100%,560px);height:244px;container-type:inline-size}
.aik-sg-fan{position:absolute;inset:0;--w:168px;--step:94px}
@container (max-width:500px){.aik-sg-fan{--w:136px;--step:60px}}
@container (max-width:360px){.aik-sg-fan{--w:124px;--step:46px}}
.aik-sg-card{position:absolute;left:50%;top:26px;width:var(--w);height:204px;margin-left:calc(var(--w)/-2);padding:8px 8px 12px;border-radius:18px;background:var(--aik-card);box-shadow:var(--aik-sh-pop);text-align:left;
transform:translateX(calc(var(--o)*var(--step))) translateY(calc(var(--a)*var(--a)*7px)) rotate(calc(var(--o)*5.5deg));transform-origin:50% 120%;
transition:transform 420ms var(--aik-ease-move),opacity var(--aik-d-panel) var(--aik-ease-out);animation:aik-sg-deal 520ms var(--aik-ease-move) both;animation-delay:calc(var(--i)*60ms)}
@keyframes aik-sg-deal{from{opacity:0;transform:translateY(120px) rotate(0deg) scale(.9)}}
.aik-sg-hand:not([data-gone]) .aik-sg-card:hover,.aik-sg-hand:not([data-gone]) .aik-sg-card:focus-visible,.aik-sg-hand:not([data-gone]) .aik-sg-card[data-lift]{z-index:30!important;transform:translateX(calc(var(--o)*var(--step))) translateY(-18px) rotate(0deg) scale(1.05)}
.aik-sg-hand[data-gone] .aik-sg-card{opacity:0;transform:translateX(calc(var(--o)*var(--step)*2.4 + var(--side)*60px)) translateY(70px) rotate(calc(var(--o)*13deg + var(--side)*8deg));transition:transform 520ms var(--aik-ease-move),opacity 320ms var(--aik-ease-in) 120ms}
.aik-sg-hand[data-gone] .aik-sg-card[data-picked]{z-index:30!important;opacity:0;transform:translateX(0) translateY(calc(var(--fly)*-1)) rotate(0deg) scale(.36);transition:transform 560ms var(--aik-ease-move),opacity 220ms var(--aik-ease-in) 340ms}
.aik-sg-art{position:relative;display:grid;place-items:center;height:86px;border-radius:12px;overflow:hidden;color:#fff;
background:radial-gradient(95% 110% at 12% 8%,color-mix(in oklab,var(--t) 58%,#fff),transparent 62%),radial-gradient(90% 100% at 92% 96%,color-mix(in oklab,var(--t) 68%,#000),transparent 60%),var(--t)}
.aik-sg-tile{position:absolute;left:16px;top:78px;display:grid;place-items:center;width:32px;height:32px;border-radius:10px;background:var(--aik-card);color:var(--aik-text);box-shadow:0 0 0 1px var(--aik-line-2),0 2px 6px rgb(12 12 24 / 10%)}
.aik-sg-card b{display:block;margin:24px 8px 0;font-size:14.5px;line-height:19px;font-weight:600;letter-spacing:-.01em}
.aik-sg-card span.aik-sg-sample{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;margin:4px 8px 0;font-size:12.5px;line-height:17px;color:var(--aik-text-2)}
@container (max-width:500px){.aik-sg-card b{font-size:13px;margin-inline:4px}.aik-sg-card span.aik-sg-sample{-webkit-line-clamp:2;margin-inline:4px;font-size:12px}}
@media (prefers-reduced-motion: reduce){.aik-sg-card{animation:none;transition:opacity var(--aik-d-state)}}
.aik-sg-mq{width:min(100%,580px);display:grid;gap:10px;overflow:hidden;padding:34px 0 8px;-webkit-mask:linear-gradient(90deg,transparent,#000 12%,#000 88%,transparent);mask:linear-gradient(90deg,transparent,#000 12%,#000 88%,transparent)}
.aik-sg-row{display:flex;gap:10px;width:max-content;animation:aik-sg-drift var(--dur,38s) linear infinite}
.aik-sg-row[data-rev]{animation-direction:reverse}
.aik-sg-mq:hover .aik-sg-row,.aik-sg-mq:focus-within .aik-sg-row,.aik-sg-mq[data-paused] .aik-sg-row{animation-play-state:paused}
@keyframes aik-sg-drift{to{transform:translateX(calc(-50% - 5px))}}
.aik-sg-pb{display:inline-flex;align-items:center;gap:8px;height:44px;padding:0 18px 0 14px;border-radius:22px;background:var(--aik-card);box-shadow:inset 0 0 0 1px var(--aik-line-2);font-size:14px;font-weight:500;white-space:nowrap;
transition:transform var(--aik-d-state) var(--aik-ease-out),background var(--aik-d-state),box-shadow var(--aik-d-state),opacity var(--aik-d-state)}
.aik-sg-pb svg{color:var(--aik-text-3);transition:color var(--aik-d-state)}
.aik-sg-pb:hover,.aik-sg-pb:focus-visible{transform:translateY(-2px);box-shadow:inset 0 0 0 1px var(--aik-line-3)}
.aik-sg-pb:hover svg,.aik-sg-pb:focus-visible svg{color:var(--aik-blue)}
.aik-sg-pb[data-picked]{background:var(--aik-pri);color:var(--aik-pri-ink);box-shadow:none;opacity:0;transform:translateY(-30px) scale(1.08);transition:transform 480ms var(--aik-ease-move),opacity 200ms var(--aik-ease-in) 300ms,background var(--aik-d-press),color var(--aik-d-press)}
.aik-sg-pb[data-picked] svg{color:currentColor}
@media (prefers-reduced-motion: reduce){.aik-sg-mq{-webkit-mask:none;mask:none}.aik-sg-row{animation:none;width:auto;flex-wrap:wrap;justify-content:center}.aik-sg-pb[data-dup]{display:none}}
.aik-sg-nw{--aik-r-shell:26px;--aik-rim:6px;width:min(100%,560px)}
.aik-sg-nwcard{overflow:hidden}
.aik-sg-line{position:relative;display:flex;align-items:center;height:118px;padding:0 44px 0 22px;-webkit-mask:linear-gradient(transparent 2%,#000 34%,#000 66%,transparent 98%);mask:linear-gradient(transparent 2%,#000 34%,#000 66%,transparent 98%)}
.aik-sg-mirror{position:absolute;left:22px;right:44px;top:50%;height:28px;margin-top:-14px;font-size:17px;line-height:28px;white-space:pre;pointer-events:none}
.aik-sg-mirror > span:first-child{visibility:hidden}
.aik-sg-wheel{position:relative;display:inline-block;vertical-align:top;height:28px}
.aik-sg-wlist{position:absolute;left:0;top:0;display:grid;transform:translateY(calc(var(--n,0)*-28px));transition:transform 280ms var(--aik-ease-move)}
.aik-sg-wlist span{height:28px;white-space:pre;color:var(--aik-text-3);opacity:.34;transition:opacity var(--aik-d-state)}
.aik-sg-wlist span[data-cur]{opacity:1}
.aik-sg-input{position:relative;width:100%;height:28px;padding:0;border:0;outline:0;background:none;font-size:17px;line-height:28px}
.aik .aik-sg-input:focus-visible{outline:none}
.aik-sg-input::placeholder{color:var(--aik-text-3);opacity:1}
.aik-sg-rail{position:absolute;right:20px;top:50%;display:grid;gap:5px;transform:translateY(-50%)}
.aik-sg-rail i{width:5px;height:5px;border-radius:50%;background:var(--aik-line-3);transition:background var(--aik-d-state),transform var(--aik-d-state) var(--aik-ease-out)}
.aik-sg-rail i[data-cur]{background:var(--aik-blue);transform:scale(1.5)}
.aik-sg-foot{display:flex;align-items:center;gap:14px;height:38px;padding:0 12px 0 10px;color:var(--aik-text-3);font-size:12px}
.aik-sg-foot span{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}
.aik-sg-foot span:last-child{margin-left:auto}
@container (max-width:420px){.aik-sg-foot span.aik-sg-opt{display:none}}
`
export interface AiSuggestion {
id: string
/** The short name shown on a card or pill. */
title: string
/** The full prompt this suggestion puts in the field. */
prompt: string
icon?: React.ReactNode
/** A small illustration for the card's art strip, drawn in white on the tone. */
art?: React.ReactNode
/** Colour of the art strip: a named tone or any CSS colour. */
tone?: AiTone | (string & {})
}
export interface AiSuggestionHandProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"onSelect"
> {
/** Four or five work best. */
items: AiSuggestion[]
/** The id of the card that was just picked. It flies up and the rest fold away. */
picked?: string | null
/** The id of a card to hold lifted, as hover does. */
lifted?: string | null
onPick?: (item: AiSuggestion) => void
/** How far, in pixels, the picked card flies up toward the field above. */
fly?: number
}
/**
* Suggestions as a hand of cards fanned in an arc. A card lifts and straightens
* under the pointer; the picked one flies up into the field above while the
* others fold away to the sides.
*/
export function AiSuggestionHand({
items,
picked = null,
lifted = null,
onPick,
fly = 180,
className,
...rest
}: AiSuggestionHandProps) {
const cards = React.useRef<Array<HTMLButtonElement | null>>([])
const middle = (items.length - 1) / 2
return (
<div
{...rest}
className={cx("aik aik-sg-hand", className)}
data-gone={picked ? "" : undefined}
role="group"
aria-label="Suggestions"
>
<AiKitStyles />
<AiStyle id="ai-suggestions" css={CSS} />
<div className="aik-sg-fan">
{items.map((item, index) => {
const offset = index - middle
return (
<button
key={item.id}
ref={(node) => {
cards.current[index] = node
}}
type="button"
className="aik-sg-card"
data-picked={item.id === picked ? "" : undefined}
data-lift={item.id === lifted ? "" : undefined}
tabIndex={picked ? -1 : 0}
style={
{
"--o": offset,
"--a": Math.abs(offset),
"--side": offset < 0 ? -1 : 1,
"--i": index,
"--fly": `${fly}px`,
"--t": toneColor(item.tone ?? "blue"),
zIndex: 10 - Math.round(Math.abs(offset) * 2),
} as React.CSSProperties
}
onClick={() => onPick?.(item)}
onKeyDown={(event) => {
const delta =
event.key === "ArrowRight"
? 1
: event.key === "ArrowLeft"
? -1
: 0
if (!delta) return
event.preventDefault()
cards.current[
(index + delta + items.length) % items.length
]?.focus()
}}
>
<span className="aik-sg-art">{item.art}</span>
<span className="aik-sg-tile">{item.icon}</span>
<b>{item.title}</b>
<span className="aik-sg-sample">{item.prompt}</span>
</button>
)
})}
</div>
</div>
)
}
export interface AiSuggestionMarqueeProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"onSelect"
> {
/** One array per row. Rows drift in alternating directions. */
rows: AiSuggestion[][]
/** The id of the pill that was just picked. It lifts out toward the field above. */
picked?: string | null
onPick?: (item: AiSuggestion) => void
/** Holds the rows still, as hover and focus do. */
paused?: boolean
/** Seconds for one full loop of a row. */
duration?: number
}
/**
* Suggestions as rows of pills drifting in opposite directions behind soft
* edges. They hold still under the pointer or focus, and the picked pill lifts
* out. With reduced motion the rows wrap and stay put.
*/
export function AiSuggestionMarquee({
rows,
picked = null,
onPick,
paused = false,
duration = 38,
className,
...rest
}: AiSuggestionMarqueeProps) {
return (
<div
{...rest}
className={cx("aik aik-sg-mq", className)}
data-paused={paused || picked ? "" : undefined}
role="group"
aria-label="Suggestions"
>
<AiKitStyles />
<AiStyle id="ai-suggestions" css={CSS} />
{rows.map((row, at) => (
<div
key={at}
className="aik-sg-row"
data-rev={at % 2 === 1 ? "" : undefined}
style={{ "--dur": `${duration + at * 6}s` } as React.CSSProperties}
>
{[0, 1].map((copy) =>
row.map((item) => (
<button
key={`${copy}-${item.id}`}
type="button"
className="aik-sg-pb"
data-dup={copy ? "" : undefined}
data-picked={item.id === picked && !copy ? "" : undefined}
aria-hidden={copy ? true : undefined}
tabIndex={copy ? -1 : 0}
onClick={() => onPick?.(item)}
>
{item.icon}
{item.title}
</button>
))
)}
</div>
))}
</div>
)
}
export interface AiNextWordsProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"onChange" | "onSubmit"
> {
value: string
onValueChange: (value: string) => void
/** Possible endings for what has been typed. The first is the ghost; the rest wait on the wheel. */
endings: string[]
/** Which ending is on the line. Leave undefined to let the arrow keys manage it. */
active?: number
onActiveChange?: (index: number) => void
/** Called on Tab with the typed text plus the chosen ending. */
onAccept?: (value: string) => void
/** Called on Escape. Clear `endings` to hide the ghost. */
onDismiss?: () => void
/** Called on Enter with the typed text. */
onSubmit?: (value: string) => void
placeholder?: string
agent?: { tone?: AiTone | (string & {}); shape?: AiShape }
}
/**
* A field that finishes your sentence. A grey ending follows the caret, and it
* sits on a wheel of alternatives: the arrow keys roll the wheel, Tab accepts.
*/
export function AiNextWords({
value,
onValueChange,
endings,
active,
onActiveChange,
onAccept,
onDismiss,
onSubmit,
placeholder = "Start typing",
agent,
className,
...rest
}: AiNextWordsProps) {
const [own, setOwn] = React.useState(0)
const count = endings.length
const row = count ? Math.min(active ?? own, count - 1) : 0
const roll = (delta: number) => {
if (!count) return
const next = (row + delta + count) % count
if (active === undefined) setOwn(next)
onActiveChange?.(next)
}
const showing = count > 0 && value.length > 0
return (
<div
{...rest}
className={cx("aik aik-sg-nw", className)}
style={{ containerType: "inline-size", ...rest.style }}
>
<AiKitStyles />
<AiStyle id="ai-suggestions" css={CSS} />
<div className="aik-shell">
<div className="aik-surface aik-sg-nwcard">
<div className="aik-sg-line">
<div className="aik-sg-mirror" aria-hidden="true">
<span>{value}</span>
{showing ? (
<span className="aik-sg-wheel">
<span
className="aik-sg-wlist"
style={{ "--n": row } as React.CSSProperties}
>
{endings.map((ending, at) => (
<span key={ending} data-cur={at === row ? "" : undefined}>
{ending}
</span>
))}
</span>
</span>
) : null}
</div>
<input
className="aik-sg-input"
value={value}
placeholder={placeholder}
aria-label={placeholder}
aria-autocomplete="inline"
autoComplete="off"
spellCheck={false}
onChange={(event) => {
if (active === undefined) setOwn(0)
onValueChange(event.target.value)
}}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault()
if (value.trim()) onSubmit?.(value.trim())
return
}
if (!showing) return
if (event.key === "Tab") {
event.preventDefault()
onAccept?.(value + (endings[row] ?? ""))
} else if (event.key === "ArrowDown") {
event.preventDefault()
roll(1)
} else if (event.key === "ArrowUp") {
event.preventDefault()
roll(-1)
} else if (event.key === "Escape") {
onDismiss?.()
}
}}
/>
{showing && count > 1 ? (
<span className="aik-sg-rail" aria-hidden="true">
{endings.map((ending, at) => (
<i key={ending} data-cur={at === row ? "" : undefined} />
))}
</span>
) : null}
</div>
</div>
<div className="aik-sg-foot">
<Face
size={20}
shape={agent?.shape ?? "orb"}
tone={agent?.tone ?? "blue"}
mood={showing ? "think" : value ? "listen" : "idle"}
/>
<span>
<kbd className="aik-kbd">Tab</kbd>accept
</span>
<span className="aik-sg-opt">
<kbd className="aik-kbd">↑</kbd>
<kbd className="aik-kbd">↓</kbd>other endings
</span>
<span className="aik-sg-opt">
<kbd className="aik-kbd">Esc</kbd>dismiss
</span>
<span>{showing ? `${row + 1} of ${count}` : "Enter sends"}</span>
</div>
</div>
</div>
)
}
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
"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
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
AiSuggestionHandfans four or five cards in an arc. A card lifts and straightens under the pointer or focus. The picked card flies upflypixels and shrinks while the rest fold away to the sides. Arrow keys move between cards.AiSuggestionMarqueedrifts 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.AiNextWordsis 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
| Field | Type | Description |
|---|---|---|
id | string | Matched against picked. |
title | string | The short name on a card or pill. |
prompt | string | The full prompt, shown as the card's sample line. |
icon | ReactNode | A 16px icon. |
art | ReactNode | A small illustration for the card's art strip. |
tone | string | Art strip colour: a named tone or any CSS colour. |
AiSuggestionHand
| Prop | Type | Default | Description |
|---|---|---|---|
items | AiSuggestion[] | Four or five work best. | |
picked | string | null | null | The id of the card that flies up. |
lifted | string | null | null | Holds a card lifted, as hover does. |
onPick | (item: AiSuggestion) => void | Called on click or Enter. | |
fly | number | 180 | How far the picked card travels, in pixels. |
AiSuggestionMarquee
| Prop | Type | Default | Description |
|---|---|---|---|
rows | AiSuggestion[][] | One array per row. | |
picked | string | null | null | The id of the pill that lifts out. |
onPick | (item: AiSuggestion) => void | Called on click or Enter. | |
paused | boolean | false | Holds the rows still. |
duration | number | 38 | Seconds for one loop of the first row. |
AiNextWords
| Prop | Type | Default | Description |
|---|---|---|---|
value | string | The typed text. | |
onValueChange | (value: string) => void | Called on every edit. | |
endings | string[] | Possible endings. Pass an empty array to hide the ghost. | |
active | number | The ending on the line. Omit to let the keys manage it. | |
onActiveChange | (index: number) => void | Called when the wheel rolls. | |
onAccept | (value: string) => void | Called on Tab with the text plus the ending. | |
onDismiss | () => void | Called on Escape. | |
onSubmit | (value: string) => void | Called on Enter. |