{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"pixel-assistant","type":"registry:component","title":"Pixel Assistant","description":"An AI chat with a pixel-art character that feels alive: it blinks, watches you type, thinks, talks while replies stream in, and naps when things go quiet. Close it to leave just the character. Bring your own AI.","dependencies":[],"files":[{"path":"registry/dot/pixel-assistant.tsx","type":"registry:component","target":"components/dot/pixel-assistant.tsx","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState, type CSSProperties, type FormEvent } from \"react\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface ChatMessage {\n  role: \"user\" | \"assistant\";\n  content: string;\n}\n\n/** A quick question, optionally with a ready answer */\nexport interface QuickReply {\n  question: string;\n  answer?: string;\n}\n\n/** Reply with a string, or stream it as text chunks (an async iterable) */\nexport type AssistantReply = string | AsyncIterable<string>;\n\nexport interface PixelAssistantProps {\n  /** Connect your AI here. Return a string, or an async iterable of text chunks to stream the reply. */\n  onMessage?: (text: string, history: ChatMessage[]) => AssistantReply | Promise<AssistantReply>;\n  /** The assistant's name, shown in the header */\n  name?: string;\n  /** First message from the assistant */\n  greeting?: string;\n  placeholder?: string;\n  /**\n   * Quick questions shown before the first message. Give one an answer and the assistant replies\n   * with it straight away (no AI call) whenever that question is tapped or typed.\n   */\n  suggestions?: (string | QuickReply)[];\n  /** Milliseconds without activity before the character falls asleep */\n  sleepAfter?: number;\n  /** Start with the chat open (true) or as just the character (false) */\n  defaultOpen?: boolean;\n  /** Control open/closed yourself; pair with onOpenChange */\n  open?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  /** Milliseconds between blinks */\n  blinkEvery?: number;\n  /** Character body colour */\n  bodyColor?: string;\n  /** Antenna light, send button and your message bubbles */\n  accentColor?: string;\n  background?: string;\n  textColor?: string;\n  /** Height of the whole chat in px */\n  height?: number;\n  className?: string;\n  style?: CSSProperties;\n}\n\ntype Mood = \"idle\" | \"listening\" | \"thinking\" | \"talking\" | \"sleeping\";\n\n// ─── Pixel character ─────────────────────────────────────────────────────────\n\n// 16 × 16. O outline · W body · C cheek · A antenna light. Eyes and mouth are drawn per mood.\nconst BODY = [\n  \".......AA.......\",\n  \".......OO.......\",\n  \"....OOOOOOOO....\",\n  \"...OWWWWWWWWO...\",\n  \"..OWWWWWWWWWWO..\",\n  \"..OWWWWWWWWWWO..\",\n  \"..OWWWWWWWWWWO..\",\n  \"..OWWWWWWWWWWO..\",\n  \"..OWWWWWWWWWWO..\",\n  \"..OWCWWWWWWCWO..\",\n  \"..OWWWWWWWWWWO..\",\n  \"..OWWWWWWWWWWO..\",\n  \"...OWWWWWWWWO...\",\n  \"....OOOOOOOO....\",\n  \".....O....O.....\",\n  \"....OO....OO....\",\n];\n\ntype Px = [number, number]; // [column, row]\nconst block = (x: number, y: number, w: number, h: number): Px[] =>\n  Array.from({ length: w * h }, (_, i) => [x + (i % w), y + Math.floor(i / w)] as Px);\n\n/** Eye pixels for each look; open eyes also get a one-pixel shine */\nfunction eyes(mood: Mood, blink: boolean): { dark: Px[]; shine: Px[] } {\n  if (mood === \"sleeping\" || blink) return { dark: [...block(5, 8, 2, 1), ...block(10, 8, 2, 1)], shine: [] };\n  if (mood === \"thinking\") return { dark: [...block(6, 5, 2, 3), ...block(11, 5, 2, 3)], shine: [] }; // looking up and aside\n  if (mood === \"listening\") return { dark: [...block(5, 7, 2, 3), ...block(10, 7, 2, 3)], shine: [[5, 7], [10, 7]] }; // looking down at what you type\n  return { dark: [...block(5, 6, 2, 3), ...block(10, 6, 2, 3)], shine: [[5, 6], [10, 6]] };\n}\n\nfunction mouth(mood: Mood, open: boolean): Px[] {\n  if (mood === \"sleeping\") return [[8, 11]];\n  if (mood === \"talking\" && open) return block(7, 10, 2, 2);\n  if (mood === \"thinking\") return [[8, 11]];\n  return block(7, 11, 2, 1);\n}\n\nfunction PixelCharacter({ mood, blink, mouthOpen, body, accent, size }: { mood: Mood; blink: boolean; mouthOpen: boolean; body: string; accent: string; size: number }) {\n  const ink = \"#16161A\";\n  const cheek = \"#F2A3B3\";\n  const rects: { x: number; y: number; fill: string }[] = [];\n  BODY.forEach((row, y) =>\n    [...row].forEach((c, x) => {\n      if (c === \".\") return;\n      rects.push({ x, y, fill: c === \"O\" ? ink : c === \"C\" ? cheek : c === \"A\" ? accent : body });\n    })\n  );\n  const { dark, shine } = eyes(mood, blink);\n  for (const [x, y] of dark) rects.push({ x, y, fill: ink });\n  for (const [x, y] of shine) rects.push({ x, y, fill: \"#FFFFFF\" });\n  for (const [x, y] of mouth(mood, mouthOpen)) rects.push({ x, y, fill: ink });\n  return (\n    <svg width={size} height={size} viewBox=\"0 0 16 16\" shapeRendering=\"crispEdges\" aria-hidden style={{ display: \"block\", overflow: \"visible\" }}>\n      {rects.map((r, i) => (\n        <rect key={i} x={r.x} y={r.y} width={1.02} height={1.02} fill={r.fill} />\n      ))}\n    </svg>\n  );\n}\n\n// ─── Demo replies (used when no onMessage is given) ─────────────────────────\n\n/** Plays a ready answer like a live reply: a short pause to think, then word by word */\nasync function* typeOut(reply: string): AsyncIterable<string> {\n  await new Promise((r) => setTimeout(r, 700));\n  for (const word of reply.split(/(\\s+)/)) {\n    yield word;\n    await new Promise((r) => setTimeout(r, word.trim() ? 35 + Math.random() * 45 : 0));\n  }\n}\n\nconst DEFAULT_QUICK_REPLIES: QuickReply[] = [\n  { question: \"What does it cost?\", answer: \"Good news: every component here is free. Pick one, copy the code or install it with the CLI, and it's yours.\" },\n  {\n    question: \"How do I install a component?\",\n    answer: \"Run `npx shadcn@latest add` with the component's name, or copy the code from its page. It drops straight into a React or Next.js app.\",\n  },\n  { question: \"Do you ever sleep?\", answer: \"If nobody talks to me for a few seconds I take a little nap. Say anything and I'll wake right up.\" },\n];\n\nasync function* demoReply(text: string): AsyncIterable<string> {\n  const t = text.toLowerCase();\n  const reply = /\\b(hi|hello|hey)\\b/.test(t)\n    ? \"Hey there! I'm a little pixel assistant. Ask me anything, or tap one of the suggestions.\"\n    : /price|cost|free/.test(t)\n      ? \"Good news: every component here is free. Pick one, copy the code or install it with the CLI, and it's yours.\"\n      : /how|install|use/.test(t)\n        ? \"Run `npx shadcn@latest add` with the component's name, or copy the code from its page. It drops straight into a React or Next.js app.\"\n        : /sleep|tired/.test(t)\n          ? \"If nobody talks to me for a few seconds I take a little nap. Say anything and I'll wake right up.\"\n          : \"That's a great question! I'm running in demo mode, so connect me to your AI with the onMessage prop and I'll give real answers.\";\n  yield* typeOut(reply);\n}\n\nconst isIterable = (value: unknown): value is AsyncIterable<string> =>\n  typeof value === \"object\" && value !== null && Symbol.asyncIterator in value;\n\n// ─── Component ───────────────────────────────────────────────────────────────\n\nconst PIXEL_FONT = '\"Silkscreen\", ui-monospace, monospace';\n// Inter: the site's next/font Inter when it has one (--font-inter), else Inter from Google Fonts\nconst FONT = 'var(--font-inter, \"Inter\"), system-ui, sans-serif';\n\n/** True when the site already ships Inter through next/font, so only Silkscreen needs downloading */\nconst siteHasInter = () =>\n  [document.documentElement, document.body].some((el) => getComputedStyle(el).getPropertyValue(\"--font-inter\").trim() !== \"\");\n\nfunction loadFonts() {\n  const id = \"dot-google-font-pixel-assistant\";\n  if (document.getElementById(id)) return;\n  const link = document.createElement(\"link\");\n  link.id = id;\n  link.rel = \"stylesheet\";\n  link.href = siteHasInter()\n    ? \"https://fonts.googleapis.com/css2?family=Silkscreen&display=swap\"\n    : \"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=Silkscreen&display=swap\";\n  document.head.appendChild(link);\n}\n\n/**\n * A chat assistant with a pixel-art character: it blinks every couple of seconds, watches you type,\n * looks up while thinking, talks while the reply streams in, and falls asleep (with floating Zs)\n * after a few seconds of quiet; any activity wakes it. Close the chat to leave just the character,\n * still blinking and napping; tap it to open the chat again. Bring your own AI through `onMessage`.\n */\nexport function PixelAssistant({\n  onMessage,\n  name = \"Dot\",\n  greeting = \"Hi! I'm Dot, your pixel assistant. What can I help you with?\",\n  placeholder = \"Ask me anything…\",\n  suggestions = DEFAULT_QUICK_REPLIES,\n  sleepAfter = 5_000,\n  defaultOpen = true,\n  open: openProp,\n  onOpenChange,\n  blinkEvery = 2_000,\n  bodyColor = \"#F3F3F0\",\n  accentColor = \"#FFFFFF\",\n  background = \"#0B0B0D\",\n  textColor = \"#FFFFFF\",\n  height = 560,\n  className,\n  style,\n}: PixelAssistantProps) {\n  const uid = useId().replace(/:/g, \"\");\n  const [messages, setMessages] = useState<ChatMessage[]>(() => (greeting ? [{ role: \"assistant\", content: greeting }] : []));\n  const [input, setInput] = useState(\"\");\n  const [busy, setBusy] = useState<\"no\" | \"thinking\" | \"talking\">(\"no\");\n  const [asleep, setAsleep] = useState(false);\n  const [blink, setBlink] = useState(false);\n  const [mouthOpen, setMouthOpen] = useState(false);\n  const [typing, setTyping] = useState(false);\n  const [error, setError] = useState(\"\");\n  const [openState, setOpenState] = useState(defaultOpen);\n  const isOpen = openProp ?? openState;\n  const setOpen = (next: boolean) => {\n    setOpenState(next);\n    onOpenChange?.(next);\n    touched.current = true;\n    if (asleep) setAsleep(false);\n  };\n  // Activity is flagged here and timestamped by the sleep timer\n  const touched = useRef(true);\n  const listRef = useRef<HTMLDivElement | null>(null);\n  const inputRef = useRef<HTMLInputElement | null>(null);\n\n  const mood: Mood = asleep ? \"sleeping\" : busy === \"talking\" ? \"talking\" : busy === \"thinking\" ? \"thinking\" : typing ? \"listening\" : \"idle\";\n  const muted = `color-mix(in srgb, ${textColor} 55%, transparent)`;\n  const line = `color-mix(in srgb, ${textColor} 10%, transparent)`;\n\n  useEffect(loadFonts, []);\n\n  // Any activity counts as being awake; it also wakes the character up\n  const poke = () => {\n    touched.current = true;\n    if (asleep) setAsleep(false);\n  };\n\n  // Fall asleep after `sleepAfter` of no activity (never mid-reply)\n  useEffect(() => {\n    let lastActive = 0; // stamped on the first tick\n    const timer = setInterval(() => {\n      const now = Date.now();\n      if (!lastActive || touched.current || busy !== \"no\") {\n        touched.current = false;\n        lastActive = now;\n      } else if (now - lastActive > sleepAfter) setAsleep(true);\n    }, 500);\n    return () => clearInterval(timer);\n  }, [busy, sleepAfter]);\n\n  // Blink every `blinkEvery` while awake: eyes shut for a moment, sometimes a double blink\n  useEffect(() => {\n    if (asleep) return;\n    const timers: ReturnType<typeof setTimeout>[] = [];\n    const interval = setInterval(() => {\n      setBlink(true);\n      timers.push(setTimeout(() => setBlink(false), 140));\n      if (Math.random() < 0.2) {\n        timers.push(setTimeout(() => setBlink(true), 280));\n        timers.push(setTimeout(() => setBlink(false), 400));\n      }\n    }, Math.max(600, blinkEvery));\n    return () => {\n      clearInterval(interval);\n      timers.forEach(clearTimeout);\n    };\n  }, [asleep, blinkEvery]);\n\n  // Mouth flaps while the reply streams in\n  useEffect(() => {\n    if (busy !== \"talking\") return;\n    const interval = setInterval(() => setMouthOpen((o) => !o), 130);\n    return () => clearInterval(interval);\n  }, [busy]);\n\n  // \"Listening\" while someone types, settling a second after they stop\n  useEffect(() => {\n    if (!typing) return;\n    const timer = setTimeout(() => setTyping(false), 1200);\n    return () => clearTimeout(timer);\n  }, [typing, input]);\n\n  // Keep the newest message in view\n  useEffect(() => {\n    const list = listRef.current;\n    if (list) list.scrollTop = list.scrollHeight;\n  }, [messages, busy]);\n\n  const send = async (text: string) => {\n    const content = text.trim();\n    if (!content || busy !== \"no\") return;\n    poke();\n    setError(\"\");\n    setInput(\"\");\n    setTyping(false);\n    const history = [...messages, { role: \"user\" as const, content }];\n    setMessages(history);\n    setBusy(\"thinking\");\n    try {\n      // A quick reply with a ready answer is answered directly; anything else goes to your AI\n      const ready = quickReplies.find((q) => q.answer && q.question.trim().toLowerCase() === content.toLowerCase())?.answer;\n      const reply = await (ready ? typeOut(ready) : onMessage ? onMessage(content, history) : demoReply(content));\n      if (isIterable(reply)) {\n        let started = false;\n        for await (const chunk of reply) {\n          if (!started) {\n            started = true;\n            setBusy(\"talking\");\n            setMessages((m) => [...m, { role: \"assistant\", content: \"\" }]);\n          }\n          setMessages((m) => {\n            const next = [...m];\n            next[next.length - 1] = { role: \"assistant\", content: next[next.length - 1].content + chunk };\n            return next;\n          });\n          touched.current = true;\n        }\n        if (!started) setMessages((m) => [...m, { role: \"assistant\", content: \"…\" }]);\n      } else {\n        setBusy(\"talking\");\n        setMessages((m) => [...m, { role: \"assistant\", content: String(reply) }]);\n        await new Promise((r) => setTimeout(r, Math.min(1500, 200 + String(reply).length * 12)));\n      }\n    } catch (err) {\n      setError(err instanceof Error && err.message ? err.message : \"Something went wrong. Try again.\");\n    } finally {\n      setBusy(\"no\");\n      touched.current = true;\n    }\n  };\n\n  const keyframes = `\n@keyframes ${uid}-bob { 0%,100% { transform: translateY(0) } 50% { transform: translateY(-3px) } }\n@keyframes ${uid}-breathe { 0%,100% { transform: translateY(1px) scaleY(.97) } 50% { transform: translateY(0) scaleY(1) } }\n@keyframes ${uid}-z { 0% { opacity: 0; transform: translate(0,0) scale(.6) } 25% { opacity: 1 } 100% { opacity: 0; transform: translate(14px,-26px) scale(1.1) } }\n@keyframes ${uid}-glow { 0%,100% { opacity: 1 } 50% { opacity: .35 } }\n@keyframes ${uid}-dot { 0%,80%,100% { opacity: .25 } 40% { opacity: 1 } }\n@media (prefers-reduced-motion: reduce) { .${uid}-anim, .${uid}-anim * { animation: none !important } }\n`;\n\n  // The character with its bob or breathing, thinking glow and sleepy Zs, at any size\n  const character = (size: number) => (\n    <div className={`${uid}-anim`} style={{ position: \"relative\", width: size, height: size, flexShrink: 0 }}>\n      <div style={{ animation: asleep ? `${uid}-breathe 3.2s ease-in-out infinite` : `${uid}-bob 2.6s ease-in-out infinite`, transformOrigin: \"50% 100%\" }}>\n        <PixelCharacter mood={mood} blink={blink} mouthOpen={mouthOpen} body={bodyColor} accent={asleep ? \"#55555F\" : accentColor} size={size} />\n      </div>\n      {busy === \"thinking\" && (\n        <div style={{ position: \"absolute\", top: -2, left: 0, right: 0, height: 8, display: \"flex\", justifyContent: \"center\", pointerEvents: \"none\" }}>\n          <span style={{ width: 8, height: 8, background: accentColor, animation: `${uid}-glow .8s ease-in-out infinite`, filter: \"blur(3px)\" }} />\n        </div>\n      )}\n      {asleep &&\n        [0, 1, 2].map((i) => (\n          <span\n            key={i}\n            aria-hidden\n            style={{\n              position: \"absolute\",\n              right: -size * 0.1,\n              top: size * 0.1,\n              font: `400 ${Math.round(size / 6) + i * 3}px ${PIXEL_FONT}`,\n              color: muted,\n              opacity: 0,\n              animation: `${uid}-z 3s linear ${i}s infinite`,\n              pointerEvents: \"none\",\n            }}\n          >\n            z\n          </span>\n        ))}\n    </div>\n  );\n\n  const status = asleep ? \"Sleeping · say anything to wake me\" : busy === \"thinking\" ? \"Thinking…\" : busy === \"talking\" ? \"Typing…\" : \"Online\";\n  const onlyGreeting = messages.length <= 1;\n  const quickReplies = suggestions\n    .map((s) => (typeof s === \"string\" ? { question: s } : s))\n    .filter((q): q is QuickReply => Boolean(q?.question?.trim()));\n\n  if (!isOpen) {\n    return (\n      <div className={className} style={{ display: \"inline-flex\", flexDirection: \"column\", alignItems: \"center\", gap: 6, fontFamily: FONT, ...style }}>\n        <style>{keyframes}</style>\n        <button\n          type=\"button\"\n          aria-label={`Open chat with ${name}${asleep ? \" (asleep)\" : \"\"}`}\n          aria-expanded={false}\n          onClick={() => setOpen(true)}\n          onPointerMove={poke}\n          title={`Chat with ${name}`}\n          style={{ padding: 10, border: 0, background: \"transparent\", cursor: \"pointer\", lineHeight: 0 }}\n        >\n          {character(72)}\n        </button>\n      </div>\n    );\n  }\n\n  return (\n    <div\n      className={className}\n      onPointerMove={poke}\n      onPointerDown={poke}\n      onKeyDown={poke}\n      style={{\n        display: \"flex\",\n        flexDirection: \"column\",\n        width: \"100%\",\n        height,\n        boxSizing: \"border-box\",\n        overflow: \"hidden\",\n        background,\n        color: textColor,\n        border: `1px solid ${line}`,\n        fontFamily: FONT,\n        ...style,\n      }}\n    >\n      <style>{keyframes}</style>\n\n      {/* Header: the character, name and status */}\n      <div style={{ display: \"flex\", alignItems: \"center\", gap: 14, padding: \"18px 18px 14px\", borderBottom: `1px solid ${line}` }}>\n        {character(64)}\n        <div style={{ minWidth: 0 }}>\n          <div style={{ font: `400 16px ${PIXEL_FONT}`, letterSpacing: \"0.02em\" }}>{name}</div>\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 6, marginTop: 4, fontSize: 12, color: muted }} aria-live=\"polite\">\n            <span style={{ width: 6, height: 6, background: asleep ? \"#6B6B75\" : \"#22C55E\" }} />\n            {status}\n          </div>\n        </div>\n        <button\n          type=\"button\"\n          aria-label=\"Close chat\"\n          onClick={() => setOpen(false)}\n          style={{ marginLeft: \"auto\", alignSelf: \"flex-start\", width: 30, height: 30, border: `1px solid ${line}`, background: \"transparent\", color: textColor, font: `400 14px/1 ${PIXEL_FONT}`, cursor: \"pointer\" }}\n        >\n          ×\n        </button>\n      </div>\n\n      {/* Messages */}\n      <div ref={listRef} role=\"log\" aria-live=\"polite\" aria-label={`Chat with ${name}`} style={{ flex: 1, overflowY: \"auto\", padding: \"16px 18px\", display: \"flex\", flexDirection: \"column\", gap: 10 }}>\n        {messages.map((m, i) => (\n          <div\n            key={i}\n            style={{\n              alignSelf: m.role === \"user\" ? \"flex-end\" : \"flex-start\",\n              maxWidth: \"82%\",\n              padding: \"9px 12px\",\n              fontSize: 14,\n              lineHeight: 1.5,\n              whiteSpace: \"pre-wrap\",\n              overflowWrap: \"anywhere\",\n              background: m.role === \"user\" ? accentColor : `color-mix(in srgb, ${textColor} 7%, transparent)`,\n              color: m.role === \"user\" ? \"#0B0B0D\" : textColor,\n            }}\n          >\n            {m.content}\n          </div>\n        ))}\n        {busy === \"thinking\" && (\n          <div aria-label={`${name} is thinking`} style={{ alignSelf: \"flex-start\", display: \"flex\", gap: 4, padding: \"12px\", background: `color-mix(in srgb, ${textColor} 7%, transparent)` }}>\n            {[0, 1, 2].map((i) => (\n              <span key={i} className={`${uid}-anim`} style={{ width: 5, height: 5, background: textColor, animation: `${uid}-dot 1.2s ease-in-out ${i * 0.15}s infinite` }} />\n            ))}\n          </div>\n        )}\n        {error && <div style={{ alignSelf: \"flex-start\", fontSize: 13, color: \"#F87171\" }}>{error}</div>}\n        {onlyGreeting && busy === \"no\" && quickReplies.length > 0 && (\n          <div style={{ display: \"flex\", flexWrap: \"wrap\", gap: 6, marginTop: 4 }}>\n            {quickReplies.map(({ question }, i) => (\n              <button\n                key={`${i}-${question}`}\n                type=\"button\"\n                onClick={() => send(question)}\n                style={{ padding: \"6px 10px\", border: `1px solid ${line}`, background: \"transparent\", color: textColor, font: `500 12px ${FONT}`, cursor: \"pointer\" }}\n              >\n                {question}\n              </button>\n            ))}\n          </div>\n        )}\n      </div>\n\n      {/* Input */}\n      <form\n        onSubmit={(e: FormEvent) => {\n          e.preventDefault();\n          void send(input);\n        }}\n        style={{ display: \"flex\", gap: 8, padding: 12, borderTop: `1px solid ${line}` }}\n      >\n        <input\n          ref={inputRef}\n          aria-label={`Message ${name}`}\n          value={input}\n          placeholder={asleep ? `${name} is asleep · type to wake` : placeholder}\n          onChange={(e) => {\n            setInput(e.target.value);\n            setTyping(true);\n            poke();\n          }}\n          onFocus={poke}\n          style={{\n            flex: 1,\n            minWidth: 0,\n            height: 40,\n            padding: \"0 12px\",\n            border: `1px solid ${line}`,\n            background: `color-mix(in srgb, ${textColor} 4%, transparent)`,\n            color: textColor,\n            font: `400 14px ${FONT}`,\n            outline: \"none\",\n          }}\n        />\n        <button\n          type=\"submit\"\n          aria-label=\"Send\"\n          disabled={!input.trim() || busy !== \"no\"}\n          style={{\n            width: 40,\n            height: 40,\n            border: 0,\n            background: accentColor,\n            color: \"#0B0B0D\",\n            font: `400 16px ${PIXEL_FONT}`,\n            cursor: \"pointer\",\n            opacity: !input.trim() || busy !== \"no\" ? 0.4 : 1,\n          }}\n        >\n          ↑\n        </button>\n      </form>\n    </div>\n  );\n}\n"}],"docs":"Pixel Assistant is ready. Props and a live canvas: https://bydot.co/component/pixel-assistant","meta":{"tier":"free","category":"UI Elements","version":"1.0.0"}}