{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "illustration-09",
  "title": "Prompt keyboard",
  "description": "A prompt typed on a tilted keyboard, QWERTY or AZERTY, where each key lights as it goes down and sends a ripple across the floor under it, then Enter sends the line.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/speech-envelope.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-agent-run.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/illustration/illustration-09.tsx",
      "content": "'use client';\n\nimport { memo, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { prefixesOf } from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\nimport { percentOf } from './_parts/geometry';\nimport { PromptField } from './_parts/prompt-field';\nimport { keyHoldOf } from './_parts/typing';\nimport { useSceneFrames, type SceneFrame } from './_parts/use-scene-frames';\nimport { useScenePlay } from './_parts/use-scene-play';\n\nexport type KeyboardLayout = 'qwerty' | 'azerty';\n\ntype LayoutPlan = {\n  /** The letters of each row, left to right. */\n  rows: string[];\n  /** How many grid columns each row starts in from the left. A letter key is two columns wide. */\n  indents: number[];\n};\n\ntype KeyPlace = {\n  id: string;\n  legend: string;\n  style: { gridColumn: string; gridRow: number };\n  /** Where a ripple starts under the key, on the floor. */\n  floorSpot: { left: string; top: string };\n};\n\ntype Beat = {\n  promptIndex: number;\n  typed: string;\n  pressed: string | null;\n  isSent: boolean;\n  /** Counts the key presses of the round, so each one starts its own ripple. */\n  strike: number;\n};\n\nconst ENTER = 'enter';\n\nconst SPACE = 'space';\n\nconst COLUMN_COUNT = 20;\n\nconst LETTER_SPAN = 2;\n\nconst SPACE_START = 5;\n\nconst SPACE_SPAN = 10;\n\nconst PLANS: Record<KeyboardLayout, LayoutPlan> = {\n  qwerty: { rows: ['qwertyuiop', 'asdfghjkl', 'zxcvbnm'], indents: [0, 1, 2] },\n  azerty: { rows: ['azertyuiop', 'qsdfghjklm', 'wxcvbn'], indents: [0, 0, 2] },\n};\n\n/** The floor reaches past the keyboard on every side, by these shares of its width and of its height. */\nconst FLOOR_PAST_X = 0.06;\n\nconst FLOOR_PAST_Y = 0.12;\n\n/** The gap between two keys. The height of a row follows from it: a letter key is as tall as it is wide. */\nconst KEY_GAP_PX = 3;\n\nconst KEY_GRID = {\n  gridTemplateColumns: `repeat(${COLUMN_COUNT}, minmax(0, 1fr))`,\n  gridAutoRows: `calc(10cqw - ${KEY_GAP_PX * 0.9}px)`,\n  gap: KEY_GAP_PX,\n  transformStyle: 'preserve-3d',\n} as const;\n\nconst FLOOR_INSET = {\n  insetInline: percentOf(-FLOOR_PAST_X),\n  insetBlock: percentOf(-FLOOR_PAST_Y),\n};\n\nconst TILT = {\n  transform: 'rotateX(36deg)',\n  transformStyle: 'preserve-3d',\n} as const;\n\nconst REST_MS = 1800;\n\nconst ENTER_MS = 150;\n\nconst SENT_MS = 420;\n\nconst KEY_DOWN_MS = 90;\n\nconst KEY_UP_MS = 95;\n\nconst TYPING_SEED = 5;\n\n/** Enough rings for a new one at every key while the earlier ones are still spreading. */\nconst RIPPLE_COUNT = 6;\n\nconst RIPPLE_KEYFRAMES: Keyframe[] = [\n  { transform: 'scale(0.08)', opacity: 0.8 },\n  { transform: 'scale(1)', opacity: 0 },\n];\n\nconst RIPPLE_TIMING = {\n  duration: 950,\n  easing: 'cubic-bezier(0.23, 1, 0.32, 1)',\n};\n\nconst RIPPLES = Array.from({ length: RIPPLE_COUNT }, (_, index) => index);\n\nfunction floorSpotOf(\n  start: number,\n  span: number,\n  row: number,\n  rowCount: number\n) {\n  const across = (start + span / 2) / COLUMN_COUNT;\n  const down = (row + 0.5) / rowCount;\n  const floorWidth = 1 + FLOOR_PAST_X * 2;\n  const floorHeight = 1 + FLOOR_PAST_Y * 2;\n  const left = (FLOOR_PAST_X + across) / floorWidth;\n  const top = (FLOOR_PAST_Y + down) / floorHeight;\n  return { left: percentOf(left), top: percentOf(top) };\n}\n\nfunction keyPlaceOf(\n  id: string,\n  legend: string,\n  start: number,\n  span: number,\n  row: number,\n  rowCount: number\n): KeyPlace {\n  const firstColumn = start + 1;\n  return {\n    id,\n    legend,\n    style: { gridColumn: `${firstColumn} / span ${span}`, gridRow: row + 1 },\n    floorSpot: floorSpotOf(start, span, row, rowCount),\n  };\n}\n\n/** The letter rows, an Enter key that fills the end of the last one, and a space bar under them. */\nfunction keysOf(plan: LayoutPlan) {\n  const rowCount = plan.rows.length + 1;\n  const lastRow = plan.rows.length - 1;\n  const keys: KeyPlace[] = [];\n  plan.rows.forEach((letters, row) => {\n    const indent = plan.indents[row];\n    Array.from(letters).forEach((letter, index) => {\n      const start = indent + index * LETTER_SPAN;\n      const legend = letter.toUpperCase();\n      keys.push(keyPlaceOf(letter, legend, start, LETTER_SPAN, row, rowCount));\n    });\n  });\n  const lastLetters = plan.rows[lastRow].length;\n  const enterStart = plan.indents[lastRow] + lastLetters * LETTER_SPAN;\n  const enterSpan = COLUMN_COUNT - enterStart;\n  keys.push(\n    keyPlaceOf(ENTER, 'Enter', enterStart, enterSpan, lastRow, rowCount)\n  );\n  keys.push(\n    keyPlaceOf(SPACE, '', SPACE_START, SPACE_SPAN, plan.rows.length, rowCount)\n  );\n  return keys;\n}\n\nconst KEYS: Record<KeyboardLayout, KeyPlace[]> = {\n  qwerty: keysOf(PLANS.qwerty),\n  azerty: keysOf(PLANS.azerty),\n};\n\n/** The key a character is typed with. A character the keyboard does not draw is typed without a key going down. */\nfunction keyOf(character: string) {\n  if (character === ' ') {\n    return SPACE;\n  }\n  const lowered = character.toLowerCase();\n  const isLetter = /^[a-z]$/.test(lowered);\n  if (isLetter) {\n    return lowered;\n  }\n  return null;\n}\n\n/**\n * The book opens on the first prompt, typed. Each next prompt starts with Enter going down and the\n * line leaving, then its keys go down and up one by one. The round ends just before the first\n * prompt is whole again, so the loop closes on its first frame.\n */\nfunction beatsOf(prompts: string[]) {\n  const first = prompts[0] ?? '';\n  let strike = 0;\n  let leaving: Beat = {\n    promptIndex: 0,\n    typed: first,\n    pressed: null,\n    isSent: false,\n    strike,\n  };\n  const beats: SceneFrame<Beat>[] = [{ state: leaving, holdMs: REST_MS }];\n  for (let offset = 1; offset <= prompts.length; offset += 1) {\n    const promptIndex = offset % prompts.length;\n    const prompt = prompts[promptIndex];\n    const characters = Array.from(prompt);\n    strike += 1;\n    beats.push({\n      state: { ...leaving, pressed: ENTER, strike },\n      holdMs: ENTER_MS,\n    });\n    beats.push({\n      state: { ...leaving, isSent: true, strike },\n      holdMs: SENT_MS,\n    });\n    prefixesOf(prompt).forEach((typed, index) => {\n      const pressed = keyOf(characters[index]);\n      strike += 1;\n      const up: Beat = {\n        promptIndex,\n        typed,\n        pressed: null,\n        isSent: false,\n        strike,\n      };\n      const upHoldMs = keyHoldOf(index, KEY_UP_MS, TYPING_SEED);\n      beats.push({ state: { ...up, pressed }, holdMs: KEY_DOWN_MS });\n      beats.push({ state: up, holdMs: upHoldMs });\n    });\n    leaving = {\n      promptIndex,\n      typed: prompt,\n      pressed: null,\n      isSent: false,\n      strike,\n    };\n    beats.push({ state: leaving, holdMs: REST_MS });\n  }\n  if (beats.length > 1) {\n    beats.pop();\n  }\n  return beats;\n}\n\nfunction labelOf(prompt: string, layout: KeyboardLayout) {\n  const name = layout.toUpperCase();\n  return `A prompt types itself on a ${name} keyboard: ${prompt}`;\n}\n\ntype KeycapProps = {\n  place: KeyPlace;\n  isPressed: boolean;\n};\n\nconst Keycap = memo(function Keycap({ place, isPressed }: KeycapProps) {\n  return (\n    <span\n      data-pressed={isPressed}\n      style={place.style}\n      className='keycap-3d text-muted-foreground data-[pressed=true]:text-primary-foreground relative flex [transform:translateZ(5px)] items-center justify-center rounded-md text-[10px] leading-none font-medium transition-[transform,color] duration-100 ease-(--ease-out-strong) data-[pressed=true]:[transform:translateZ(1px)]'\n    >\n      <span\n        data-pressed={isPressed}\n        className='bg-primary absolute inset-0 rounded-[inherit] opacity-0 transition-opacity duration-150 ease-(--ease-out-strong) data-[pressed=true]:opacity-100'\n      />\n      <span className='relative'>{place.legend}</span>\n    </span>\n  );\n});\n\nexport type PromptKeyboardProps = {\n  /** The prompts the scene types in turn. Letters and spaces press their keys. */\n  prompts: string[];\n  layout?: KeyboardLayout;\n  className?: string;\n};\n\nexport function PromptKeyboard({\n  prompts,\n  layout = 'qwerty',\n  className,\n}: PromptKeyboardProps) {\n  const { ref, isPlaying, isStill } = useScenePlay();\n  const floorRef = useRef<HTMLSpanElement>(null);\n  const beats = useMemo(() => beatsOf(prompts), [prompts]);\n  const beat = useSceneFrames(beats, { isPlaying, isStill });\n  const keys = KEYS[layout];\n  const pressedKey = keys.find((key) => key.id === beat.pressed);\n  const rippleLeft = pressedKey?.floorSpot.left;\n  const rippleTop = pressedKey?.floorSpot.top;\n  const isSending = beat.pressed === ENTER;\n  const isTyping = !beat.isSent;\n  const prompt = prompts[beat.promptIndex] ?? '';\n\n  useEffect(() => {\n    const floor = floorRef.current;\n    const hasSpot = rippleLeft !== undefined && rippleTop !== undefined;\n    if (!floor || !hasSpot) {\n      return;\n    }\n    const rings = floor.querySelectorAll<HTMLElement>('[data-ripple]');\n    const ring = rings[beat.strike % RIPPLE_COUNT];\n    if (!ring) {\n      return;\n    }\n    ring.style.left = rippleLeft;\n    ring.style.top = rippleTop;\n    ring.animate(RIPPLE_KEYFRAMES, RIPPLE_TIMING);\n  }, [beat.strike, rippleLeft, rippleTop]);\n\n  return (\n    <div\n      ref={ref}\n      role='img'\n      aria-label={labelOf(prompt, layout)}\n      className={cn('flex w-full max-w-[26rem] flex-col gap-2', className)}\n    >\n      <PromptField\n        typed={beat.typed}\n        isTyping={isTyping}\n        isSending={isSending}\n        isSent={beat.isSent}\n        lineKey={beat.promptIndex}\n      />\n      <div\n        style={{ perspective: '900px' }}\n        className='@container overflow-hidden px-[10%] py-3'\n      >\n        <div style={TILT} className='relative'>\n          <span\n            ref={floorRef}\n            style={FLOOR_INSET}\n            className='bg-primary/[0.06] absolute overflow-hidden rounded-2xl'\n          >\n            {RIPPLES.map((ripple) => (\n              <span\n                key={ripple}\n                data-ripple=''\n                className='bg-primary/[0.06] ring-primary/40 absolute aspect-square w-[58%] -translate-x-1/2 -translate-y-1/2 rounded-full opacity-0 ring-[1.5px]'\n              />\n            ))}\n          </span>\n          <div style={KEY_GRID} className='relative grid'>\n            {keys.map((key) => (\n              <Keycap\n                key={key.id}\n                place={key}\n                isPressed={key.id === beat.pressed}\n              />\n            ))}\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nconst PROMPTS = [\n  'Draft the launch notes',\n  'Plan the data migration',\n  'Summarise this thread',\n];\n\nconst LAYOUTS: Segment<KeyboardLayout>[] = [\n  { value: 'qwerty', label: 'QWERTY' },\n  { value: 'azerty', label: 'AZERTY' },\n];\n\nexport default function Illustration09() {\n  const [layout, setLayout] = useState<KeyboardLayout>('qwerty');\n\n  return (\n    <div className='flex w-full max-w-[26rem] flex-col items-center gap-3'>\n      <PromptKeyboard prompts={PROMPTS} layout={layout} />\n      <Segments\n        value={layout}\n        segments={LAYOUTS}\n        onValueChange={setLayout}\n        label='Keyboard layout'\n        className='w-44'\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/illustration/illustration-09.tsx"
    },
    {
      "path": "registry/ndeko/components/illustration/_parts/geometry.ts",
      "content": "export type ScenePoint = {\n  /** Share of the stage width, from 0 to 1. */\n  x: number;\n  /** Share of the stage height, from 0 to 1. */\n  y: number;\n};\n\nexport type SceneSpan = {\n  /** Length of the line as a percentage of the stage width. */\n  lengthPercent: number;\n  /** Angle of the line in degrees, clockwise from the right, as CSS turns it. */\n  angleDeg: number;\n};\n\nconst HALF_TURN_DEG = 180;\n\nconst FULL_TURN_DEG = 360;\n\n/**\n * Two engines can disagree on the last digit of a sine. A value written into a style is rounded, so\n * the server and the browser print the same text.\n */\nexport function rounded(value: number) {\n  const hundredths = Math.round(value * 100);\n  return hundredths / 100;\n}\n\nexport function percentOf(share: number) {\n  const percent = rounded(share * 100);\n  return `${percent}%`;\n}\n\nexport function degreesOf(radians: number) {\n  return (radians * HALF_TURN_DEG) / Math.PI;\n}\n\nexport function radiansOf(degrees: number) {\n  return (degrees * Math.PI) / HALF_TURN_DEG;\n}\n\n/** The angle equal to `target` that is closest to `current`, so a turn towards it goes the short way round. */\nexport function nearestAngleOf(target: number, current: number) {\n  const difference = target - current;\n  const turns = Math.round(difference / FULL_TURN_DEG);\n  const wrapped = difference - FULL_TURN_DEG * turns;\n  return current + wrapped;\n}\n\n/** The line between two points of a stage that is `aspect` times wider than it is tall. */\nexport function spanBetween(\n  from: ScenePoint,\n  to: ScenePoint,\n  aspect: number\n): SceneSpan {\n  const acrossShare = to.x - from.x;\n  const downShare = to.y - from.y;\n  const downInWidths = downShare / aspect;\n  const lengthInWidths = Math.hypot(acrossShare, downInWidths);\n  const angle = Math.atan2(downInWidths, acrossShare);\n  const degrees = degreesOf(angle);\n  return {\n    lengthPercent: rounded(lengthInWidths * 100),\n    angleDeg: rounded(degrees),\n  };\n}\n\n/** Where a tile centred on a point of the stage goes: its `left` and `top`. */\nexport function placeOf(point: ScenePoint) {\n  return { left: percentOf(point.x), top: percentOf(point.y) };\n}\n",
      "type": "registry:component",
      "target": "components/illustration/_parts/geometry.ts"
    },
    {
      "path": "registry/ndeko/components/illustration/_parts/prompt-field.tsx",
      "content": "import { pressedSolidOf } from '@/registry/ndeko/lib/demonstration';\nimport { ArrowUpIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\ntype PromptFieldProps = {\n  typed: string;\n  /** Shows the caret after the text. */\n  isTyping: boolean;\n  /** Holds the send key down. */\n  isSending: boolean;\n  /** The line leaves upwards, as a request that has just been sent. */\n  isSent?: boolean;\n  /** A new key starts the next line in place, so it does not come back down the way the last one left. */\n  lineKey?: number;\n};\n\n/** The drawing of a prompt field for a scene: a line that a script types, and a send key it presses. */\nexport function PromptField({\n  typed,\n  isTyping,\n  isSending,\n  isSent = false,\n  lineKey = 0,\n}: PromptFieldProps) {\n  return (\n    <div className='bg-card hairline-ring ring-border flex h-10 items-center gap-2 rounded-xl ps-3.5 pe-1.5 shadow-[0_1px_2px_rgb(0_0_0/0.05)]'>\n      <p\n        key={lineKey}\n        data-sent={isSent}\n        className='min-w-0 flex-1 truncate text-[13px] leading-5 transition-[opacity,translate] duration-200 ease-(--ease-out-strong) data-[sent=true]:-translate-y-2 data-[sent=true]:opacity-0'\n      >\n        {typed}\n        {isTyping && (\n          <span className='bg-foreground ms-px inline-block h-4 w-px align-text-bottom' />\n        )}\n      </p>\n      <span\n        className={cn(\n          'bg-primary text-primary-foreground flex size-7 shrink-0 items-center justify-center rounded-full transition-[scale,background-color] duration-150 ease-(--ease-out-strong)',\n          pressedSolidOf(isSending)\n        )}\n      >\n        <ArrowUpIcon className='size-4' />\n      </span>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/illustration/_parts/prompt-field.tsx"
    },
    {
      "path": "registry/ndeko/components/illustration/_parts/typing.ts",
      "content": "import { noiseAt } from '@/registry/ndeko/lib/speech-envelope';\n\nconst SHORTEST_STRETCH = 0.55;\n\nconst STRETCH_SPAN = 0.95;\n\n/**\n * A person does not type at a steady pace: the wait after each key stretches or shrinks around\n * `characterMs`, the same way on every round. A scene picks its own `seed` so two scenes do not type\n * in step.\n */\nexport function keyHoldOf(index: number, characterMs: number, seed: number) {\n  const noise = noiseAt(index, seed);\n  const stretch = SHORTEST_STRETCH + noise * STRETCH_SPAN;\n  return characterMs * stretch;\n}\n",
      "type": "registry:component",
      "target": "components/illustration/_parts/typing.ts"
    },
    {
      "path": "registry/ndeko/components/illustration/_parts/use-scene-frames.ts",
      "content": "'use client';\n\nimport { useEffect, useState } from 'react';\n\nimport type { ScenePlay } from './use-scene-play';\n\nexport type SceneFrame<State> = {\n  state: State;\n  /** Milliseconds the scene stays in this state before the next one. */\n  holdMs: number;\n};\n\nfunction nextIndexOf(index: number, count: number) {\n  const next = index + 1;\n  return next % count;\n}\n\n/**\n * A scene told as a flipbook: whole states, each held for a while, played in a loop. The first frame\n * is the resting picture: it shows before the scene plays and under reduced motion. While the scene\n * does not play the book stays on its page and no timer is left. `frames` holds at least one frame.\n */\nexport function useSceneFrames<State>(\n  frames: readonly SceneFrame<State>[],\n  { isPlaying, isStill }: ScenePlay\n) {\n  const [index, setIndex] = useState(0);\n  const frameCount = frames.length;\n  const shownIndex = index % frameCount;\n  const frame = frames[shownIndex];\n  const holdMs = frame.holdMs;\n\n  useEffect(() => {\n    if (!isPlaying) {\n      return;\n    }\n    const timer = window.setTimeout(() => {\n      setIndex(nextIndexOf(shownIndex, frameCount));\n    }, holdMs);\n    return () => window.clearTimeout(timer);\n  }, [isPlaying, shownIndex, frameCount, holdMs]);\n\n  if (isStill) {\n    return frames[0].state;\n  }\n  return frame.state;\n}\n",
      "type": "registry:component",
      "target": "components/illustration/_parts/use-scene-frames.ts"
    },
    {
      "path": "registry/ndeko/components/illustration/_parts/use-scene-play.ts",
      "content": "'use client';\n\nimport { useInView } from 'motion/react';\nimport { useRef } from 'react';\n\nimport { useDocumentVisible } from '@/registry/ndeko/hooks/use-agent-run';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\n\nconst IN_VIEW_SHARE = 0.3;\n\nexport type ScenePlay = {\n  /** True while a visitor can see the scene move: on screen, in a visible tab, without reduced motion. */\n  isPlaying: boolean;\n  /** True under reduced motion: the scene rests on its still frame. */\n  isStill: boolean;\n};\n\n/**\n * An illustration moves only while someone can see it. Everything that loops in a scene hangs on\n * `isPlaying`, so nothing runs off screen, in a hidden tab or under reduced motion.\n */\nexport function useScenePlay<Element extends HTMLElement = HTMLDivElement>() {\n  const ref = useRef<Element>(null);\n  const isInView = useInView(ref, { amount: IN_VIEW_SHARE });\n  const isTabVisible = useDocumentVisible();\n  const isStill = usePrefersReducedMotion();\n  const isOnScreen = isInView && isTabVisible;\n  const isPlaying = isOnScreen && !isStill;\n\n  return { ref, isPlaying, isStill };\n}\n",
      "type": "registry:component",
      "target": "components/illustration/_parts/use-scene-play.ts"
    }
  ],
  "categories": [
    "components",
    "illustration"
  ],
  "type": "registry:component"
}