{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "illustration-10",
  "title": "Agent face",
  "description": "An agent face whose eyes follow the pointer and blink, then take on its state: wide while it listens, up past a trail of dots while it thinks, over a moving mouth while it speaks.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.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-autoplay.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-10.tsx",
      "content": "'use client';\n\nimport { useEffect, useRef, useState } from 'react';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport {\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { speechLevelAt } from '@/registry/ndeko/lib/speech-envelope';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\nimport { penOf, tokenOf, watchTheme } from './_parts/canvas';\nimport { radiansOf } from './_parts/geometry';\nimport { useScenePlay } from './_parts/use-scene-play';\n\nexport type FaceState = 'idle' | 'listening' | 'thinking' | 'speaking';\n\ntype Weights = Record<FaceState, number>;\n\n/** Where the eyes look, from -1 to 1 on both axes: left to right, up to down. */\ntype Look = {\n  x: number;\n  y: number;\n};\n\ntype Palette = {\n  skin: string;\n  feature: string;\n  ink: string;\n};\n\ntype FaceFrame = {\n  weights: Weights;\n  look: Look;\n  /** How open the eyes are: 1 open, 0 shut. */\n  lid: number;\n  level: number;\n  seconds: number;\n};\n\ntype TrailDot = {\n  x: number;\n  y: number;\n  radius: number;\n};\n\nconst STATES: FaceState[] = ['idle', 'listening', 'thinking', 'speaking'];\n\nconst STATE_WORD: Record<FaceState, string> = {\n  idle: 'Idle',\n  listening: 'Listening',\n  thinking: 'Thinking',\n  speaking: 'Speaking',\n};\n\nconst TAU = Math.PI * 2;\n\n/** Every measure of the face is a share of the side of its canvas. */\nconst HEAD_WIDTH = 0.62;\n\nconst HEAD_HEIGHT = 0.58;\n\nconst HEAD_RADIUS = 0.2;\n\nconst EYE_WIDTH = 0.085;\n\nconst EYE_HEIGHT = 0.17;\n\nconst EYE_SPREAD = 0.115;\n\nconst EYE_LIFT = 0.03;\n\nconst LOOK_REACH_X = 0.045;\n\nconst LOOK_REACH_Y = 0.035;\n\n/** The eyes never shut to nothing: a blink leaves a line. */\nconst SHUT_EYE = 0.1;\n\nconst WIDER_WHEN_HEARD = 0.22;\n\nconst TALLER_WHEN_HEARD = 0.16;\n\nconst MOUTH_DROP = 0.145;\n\nconst MOUTH_WIDTH = 0.11;\n\nconst MOUTH_SHUT = 0.022;\n\nconst MOUTH_OPEN = 0.075;\n\nconst LISTENING_TILT_DEG = -7;\n\nconst THINKING_TILT_DEG = 3;\n\nconst BREATH_HERTZ = 0.25;\n\nconst BREATH_RISE = 0.008;\n\n/** The thought that leaves the head while it thinks: three dots, each a little further and a little larger. */\nconst TRAIL: TrailDot[] = [\n  { x: 0.3, y: -0.3, radius: 0.022 },\n  { x: 0.365, y: -0.37, radius: 0.028 },\n  { x: 0.43, y: -0.425, radius: 0.034 },\n];\n\nconst TRAIL_HERTZ = 0.9;\n\nconst TRAIL_LAG = 0.22;\n\nconst THINKING_LOOK: Look = { x: 0.8, y: -0.85 };\n\nconst CENTRED_LOOK: Look = { x: 0, y: 0 };\n\n/** A pointer this far from the face turns the eyes all the way. */\nconst POINTER_REACH_PX = 240;\n\nconst STATE_EASE_S = 0.22;\n\nconst LOOK_EASE_S = 0.12;\n\n/** A frame that comes late, after a hidden tab, moves the face no further than this long would. */\nconst MAX_STEP_S = 0.05;\n\nconst ATTACK = 0.45;\n\nconst RELEASE = 0.12;\n\nconst BLINK_MS = 150;\n\nconst BLINK_MIN_GAP_MS = 2200;\n\nconst BLINK_MAX_GAP_MS = 5200;\n\nconst VOICE_SEED = 1.6;\n\nfunction oneHotOf(state: FaceState): Weights {\n  return {\n    idle: Number(state === 'idle'),\n    listening: Number(state === 'listening'),\n    thinking: Number(state === 'thinking'),\n    speaking: Number(state === 'speaking'),\n  };\n}\n\nfunction paletteOf(canvas: HTMLCanvasElement): Palette {\n  return {\n    skin: tokenOf(canvas, '--primary'),\n    feature: tokenOf(canvas, '--primary-foreground'),\n    ink: tokenOf(canvas, '--foreground'),\n  };\n}\n\nfunction traceBox(\n  pen: CanvasRenderingContext2D,\n  left: number,\n  top: number,\n  width: number,\n  height: number,\n  radius: number\n) {\n  const right = left + width;\n  const bottom = top + height;\n  pen.beginPath();\n  pen.moveTo(left + radius, top);\n  pen.arcTo(right, top, right, bottom, radius);\n  pen.arcTo(right, bottom, left, bottom, radius);\n  pen.arcTo(left, bottom, left, top, radius);\n  pen.arcTo(left, top, right, top, radius);\n  pen.closePath();\n}\n\n/** A pill centred on a point: its ends are as round as its short side allows. */\nfunction fillPill(\n  pen: CanvasRenderingContext2D,\n  centreX: number,\n  centreY: number,\n  width: number,\n  height: number\n) {\n  const shortSide = Math.min(width, height);\n  const left = centreX - width / 2;\n  const top = centreY - height / 2;\n  traceBox(pen, left, top, width, height, shortSide / 2);\n  pen.fill();\n}\n\nfunction drawHead(pen: CanvasRenderingContext2D, size: number, skin: string) {\n  const width = size * HEAD_WIDTH;\n  const height = size * HEAD_HEIGHT;\n  pen.fillStyle = skin;\n  traceBox(pen, -width / 2, -height / 2, width, height, size * HEAD_RADIUS);\n  pen.fill();\n}\n\nfunction drawEyes(\n  pen: CanvasRenderingContext2D,\n  size: number,\n  frame: FaceFrame,\n  feature: string\n) {\n  const heard = frame.weights.listening * frame.level;\n  const lid = Math.max(SHUT_EYE, frame.lid);\n  const width = size * EYE_WIDTH * (1 + WIDER_WHEN_HEARD * heard);\n  const openHeight = size * EYE_HEIGHT * (1 + TALLER_WHEN_HEARD * heard);\n  const height = openHeight * lid;\n  const lookX = frame.look.x * size * LOOK_REACH_X;\n  const lookY = frame.look.y * size * LOOK_REACH_Y;\n  const spread = size * EYE_SPREAD;\n  const eyeY = lookY - size * EYE_LIFT;\n  pen.fillStyle = feature;\n  fillPill(pen, lookX - spread, eyeY, width, height);\n  fillPill(pen, lookX + spread, eyeY, width, height);\n}\n\nfunction drawMouth(\n  pen: CanvasRenderingContext2D,\n  size: number,\n  frame: FaceFrame,\n  feature: string\n) {\n  const shown = frame.weights.speaking;\n  if (shown < 0.01) {\n    return;\n  }\n  const opening = MOUTH_SHUT + MOUTH_OPEN * frame.level;\n  pen.globalAlpha = shown;\n  pen.fillStyle = feature;\n  fillPill(pen, 0, size * MOUTH_DROP, size * MOUTH_WIDTH, size * opening);\n  pen.globalAlpha = 1;\n}\n\n/** The dots light one after the other, from the head outwards. */\nfunction drawTrail(\n  pen: CanvasRenderingContext2D,\n  size: number,\n  frame: FaceFrame,\n  ink: string\n) {\n  const shown = frame.weights.thinking;\n  if (shown < 0.01) {\n    return;\n  }\n  const centre = size / 2;\n  pen.fillStyle = ink;\n  TRAIL.forEach((dot, index) => {\n    const turns = frame.seconds * TRAIL_HERTZ - index * TRAIL_LAG;\n    const wave = (Math.sin(turns * TAU) + 1) / 2;\n    const light = 0.18 + wave * 0.42;\n    const dotX = centre + dot.x * size;\n    const dotY = centre + dot.y * size;\n    pen.globalAlpha = shown * light;\n    pen.beginPath();\n    pen.arc(dotX, dotY, dot.radius * size, 0, TAU);\n    pen.fill();\n  });\n  pen.globalAlpha = 1;\n}\n\nfunction drawFace(\n  pen: CanvasRenderingContext2D,\n  size: number,\n  frame: FaceFrame,\n  palette: Palette\n) {\n  const centre = size / 2;\n  const calm = frame.weights.idle + frame.weights.thinking;\n  const breath = Math.sin(frame.seconds * TAU * BREATH_HERTZ);\n  const rise = breath * size * BREATH_RISE * calm;\n  const listeningTilt = radiansOf(LISTENING_TILT_DEG) * frame.weights.listening;\n  const thinkingTilt = radiansOf(THINKING_TILT_DEG) * frame.weights.thinking;\n  pen.clearRect(0, 0, size, size);\n  pen.save();\n  pen.translate(centre, centre + rise);\n  pen.rotate(listeningTilt + thinkingTilt);\n  drawHead(pen, size, palette.skin);\n  drawEyes(pen, size, frame, palette.feature);\n  drawMouth(pen, size, frame, palette.feature);\n  pen.restore();\n  drawTrail(pen, size, frame, palette.ink);\n}\n\nfunction stillLookOf(state: FaceState) {\n  if (state === 'thinking') {\n    return THINKING_LOOK;\n  }\n  return CENTRED_LOOK;\n}\n\n/** The frame a face rests on while it does not play: its state at full strength, eyes open, a voice half way. */\nfunction stillFrameOf(state: FaceState): FaceFrame {\n  return {\n    weights: oneHotOf(state),\n    look: stillLookOf(state),\n    lid: 1,\n    level: 0.55,\n    seconds: 0,\n  };\n}\n\n/** How much of the way left is covered in `seconds`: the same glide whatever the frame rate. */\nfunction shareOf(seconds: number, easeSeconds: number) {\n  const decay = Math.exp(-seconds / easeSeconds);\n  return 1 - decay;\n}\n\nfunction towards(from: number, to: number, share: number) {\n  const gap = to - from;\n  return from + gap * share;\n}\n\nfunction easeWeights(weights: Weights, target: Weights, share: number) {\n  for (const state of STATES) {\n    weights[state] = towards(weights[state], target[state], share);\n  }\n}\n\n/** A level rises fast and falls slowly, the way a voice is heard. */\nfunction followOf(current: number, target: number) {\n  const gap = target - current;\n  if (gap > 0) {\n    return current + gap * ATTACK;\n  }\n  return current + gap * RELEASE;\n}\n\nfunction levelFrom(provider: (() => number) | undefined, elapsed: number) {\n  if (provider) {\n    return provider();\n  }\n  return speechLevelAt(elapsed, VOICE_SEED);\n}\n\n/** A blink shuts the eyes and opens them again in a straight line each way. */\nfunction lidAt(sinceBlinkMs: number) {\n  const isBefore = sinceBlinkMs < 0;\n  const isAfter = sinceBlinkMs >= BLINK_MS;\n  if (isBefore || isAfter) {\n    return 1;\n  }\n  const half = BLINK_MS / 2;\n  const fromShut = Math.abs(sinceBlinkMs - half);\n  return fromShut / half;\n}\n\nfunction blinkGapOf() {\n  const spread = BLINK_MAX_GAP_MS - BLINK_MIN_GAP_MS;\n  return BLINK_MIN_GAP_MS + Math.random() * spread;\n}\n\nfunction boundedOf(value: number) {\n  const atLeast = Math.max(-1, value);\n  return Math.min(1, atLeast);\n}\n\nexport type AgentFaceProps = {\n  state: FaceState;\n  /** A live level between 0 and 1, such as a microphone or the voice of the agent. Left out, a simulated voice moves the face. */\n  level?: () => number;\n  /** The side of the canvas, in pixels. */\n  size?: number;\n  className?: string;\n};\n\nexport function AgentFace({\n  state,\n  level,\n  size = 176,\n  className,\n}: AgentFaceProps) {\n  const { ref, isPlaying } = useScenePlay<HTMLCanvasElement>();\n  const stateRef = useRef(state);\n  const levelRef = useRef(level);\n\n  useEffect(() => {\n    stateRef.current = state;\n    levelRef.current = level;\n  }, [state, level]);\n\n  useEffect(() => {\n    const canvas = ref.current;\n    if (!canvas || isPlaying) {\n      return;\n    }\n    const surface: HTMLCanvasElement = canvas;\n\n    function drawStill() {\n      const pen = penOf(surface, size, size);\n      if (!pen) {\n        return;\n      }\n      drawFace(pen, size, stillFrameOf(state), paletteOf(surface));\n    }\n\n    drawStill();\n    return watchTheme(drawStill);\n  }, [ref, isPlaying, state, size]);\n\n  useEffect(() => {\n    const canvas = ref.current;\n    if (!canvas || !isPlaying) {\n      return;\n    }\n    const context = penOf(canvas, size, size);\n    if (!context) {\n      return;\n    }\n    const surface: HTMLCanvasElement = canvas;\n    const pen: CanvasRenderingContext2D = context;\n    const weights = oneHotOf(stateRef.current);\n    const look: Look = { x: 0, y: 0 };\n    const pointer: Look = { x: 0, y: 0 };\n    const shown: FaceFrame = { weights, look, lid: 1, level: 0, seconds: 0 };\n    const startedAt = performance.now();\n    let palette = paletteOf(surface);\n    let last = startedAt;\n    let blinkAt = startedAt + blinkGapOf();\n    let frame = 0;\n\n    function follow(event: PointerEvent) {\n      const box = surface.getBoundingClientRect();\n      const centreX = box.left + box.width / 2;\n      const centreY = box.top + box.height / 2;\n      const across = (event.clientX - centreX) / POINTER_REACH_PX;\n      const down = (event.clientY - centreY) / POINTER_REACH_PX;\n      pointer.x = boundedOf(across);\n      pointer.y = boundedOf(down);\n    }\n\n    function draw(now: number) {\n      const sinceLast = (now - last) / 1000;\n      const step = Math.min(MAX_STEP_S, sinceLast);\n      const elapsed = now - startedAt;\n      last = now;\n      const targetWeights = oneHotOf(stateRef.current);\n      const stateShare = shareOf(step, STATE_EASE_S);\n      easeWeights(weights, targetWeights, stateShare);\n      const thinking = weights.thinking;\n      const lookShare = shareOf(step, LOOK_EASE_S);\n      const targetX = towards(pointer.x, THINKING_LOOK.x, thinking);\n      const targetY = towards(pointer.y, THINKING_LOOK.y, thinking);\n      look.x = towards(look.x, targetX, lookShare);\n      look.y = towards(look.y, targetY, lookShare);\n      const hasBlinked = now - blinkAt >= BLINK_MS;\n      if (hasBlinked) {\n        blinkAt = now + blinkGapOf();\n      }\n      const heard = levelFrom(levelRef.current, elapsed);\n      shown.lid = lidAt(now - blinkAt);\n      shown.level = followOf(shown.level, heard);\n      shown.seconds = elapsed / 1000;\n      drawFace(pen, size, shown, palette);\n      frame = requestAnimationFrame(draw);\n    }\n\n    const stopWatching = watchTheme(() => {\n      palette = paletteOf(surface);\n    });\n    window.addEventListener('pointermove', follow, { passive: true });\n    frame = requestAnimationFrame(draw);\n    return () => {\n      cancelAnimationFrame(frame);\n      window.removeEventListener('pointermove', follow);\n      stopWatching();\n    };\n  }, [ref, isPlaying, size]);\n\n  return (\n    <canvas\n      ref={ref}\n      aria-hidden='true'\n      style={{ width: size, height: size }}\n      className={cn('block', className)}\n    />\n  );\n}\n\nconst STATE_LABELS = STATES.map((state) => STATE_WORD[state]);\n\nconst SEGMENTS: Segment<FaceState>[] = STATES.map((state) => ({\n  value: state,\n  label: STATE_WORD[state],\n}));\n\nconst STATE_HOLD_MS = 2600;\n\nconst START_STATE: FaceState = 'listening';\n\nexport default function Illustration10() {\n  const [state, setState] = useState<FaceState>(START_STATE);\n  const steps: AutoplayStep[] = [\n    { after: STATE_HOLD_MS, run: () => setState('thinking') },\n    { after: STATE_HOLD_MS, run: () => setState('speaking') },\n    { after: STATE_HOLD_MS, run: () => setState('idle') },\n  ];\n  const { ref, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: STATE_HOLD_MS,\n    onReset: () => setState(START_STATE),\n  });\n\n  return (\n    <div\n      ref={ref}\n      className='flex w-full max-w-[20rem] flex-col items-center gap-3'\n    >\n      <AgentFace state={state} />\n      <p className='text-sm font-medium'>\n        <WordRoll text={STATE_WORD[state]} labels={STATE_LABELS} />\n      </p>\n      <Segments\n        value={state}\n        segments={SEGMENTS}\n        onValueChange={setState}\n        label='Agent state'\n        className='w-full max-w-[19rem]'\n      />\n      <LiveRegion message={spokenUnless(isAutoplaying, STATE_WORD[state])} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/illustration/illustration-10.tsx"
    },
    {
      "path": "registry/ndeko/components/illustration/_parts/canvas.ts",
      "content": "/** A backing store above two device pixels a point costs four times the fill for a picture nobody sees sharper. */\nconst MAX_PIXEL_RATIO = 2;\n\nexport function pixelRatioOf() {\n  const screenRatio = window.devicePixelRatio || 1;\n  return Math.min(screenRatio, MAX_PIXEL_RATIO);\n}\n\n/** Sizes the backing store of a canvas for the screen and hands back a pen that draws in CSS pixels. */\nexport function penOf(\n  canvas: HTMLCanvasElement,\n  width: number,\n  height: number\n) {\n  const ratio = pixelRatioOf();\n  const pixelWidth = Math.round(width * ratio);\n  const pixelHeight = Math.round(height * ratio);\n  if (canvas.width !== pixelWidth) {\n    canvas.width = pixelWidth;\n  }\n  if (canvas.height !== pixelHeight) {\n    canvas.height = pixelHeight;\n  }\n  const pen = canvas.getContext('2d');\n  pen?.setTransform(ratio, 0, 0, ratio, 0, 0);\n  return pen;\n}\n\n/** The value of a theme token where the element stands, or its text colour when the token is not set. */\nexport function tokenOf(element: Element, token: string) {\n  const styles = getComputedStyle(element);\n  const value = styles.getPropertyValue(token).trim();\n  return value || styles.color;\n}\n\n/** A canvas holds the colours it was drawn with: it is told when the theme of the page changes. */\nexport function watchTheme(onChange: () => void) {\n  const observer = new MutationObserver(onChange);\n  observer.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: ['class', 'style', 'data-theme'],\n  });\n  return () => observer.disconnect();\n}\n",
      "type": "registry:component",
      "target": "components/illustration/_parts/canvas.ts"
    },
    {
      "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/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"
}