{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "background-09",
  "title": "Perspective grid",
  "description": "A grid floor behind a hero that runs towards the viewer and fades into the horizon, every fourth line in the hue.",
  "dependencies": [
    "not showing"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/background/background-09.tsx",
      "content": "'use client';\n\nimport { useEffect, useRef, type CSSProperties } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nimport { DemoBand } from './_parts/demo-band';\nimport { DEFAULT_HUE, useHueCycle } from './_parts/hue';\nimport { runWhileShowing } from './_parts/loops';\n\nconst DEFAULT_CELL = 44;\n\nconst MIN_CELL = 16;\n\nconst DEFAULT_DURATION_S = 9;\n\n/** The hue is on every fourth line, so the floor repeats every four cells: the loop runs exactly that far. */\nconst MAJOR_EVERY = 4;\n\n/**\n * The eye of the scene: how far it stands from the screen, and how high in the box. The floor lies\n * flat under it, so its lines run towards that height, which is the horizon.\n */\nconst EYE: CSSProperties = {\n  perspective: '240px',\n  perspectiveOrigin: '50% 38%',\n};\n\n/**\n * The floor lies down from the bottom edge of the box, which is its near edge. It is short and\n * fades out long before the horizon: the far part of a floor is a large surface for a few pixels\n * on screen, and its lines would crowd there.\n */\nconst FLOOR: CSSProperties = {\n  height: 460,\n  transform: 'rotateX(90deg)',\n};\n\nconst MINOR_LINE = 'var(--border)';\n\nconst MAJOR_LINE = 'color-mix(in oklab, currentColor 55%, transparent)';\n\nfunction lineOf(direction: string, colour: string) {\n  return `linear-gradient(${direction}, ${colour} 1px, transparent 1px)`;\n}\n\nconst LINES = [\n  lineOf('to right', MAJOR_LINE),\n  lineOf('to bottom', MAJOR_LINE),\n  lineOf('to right', MINOR_LINE),\n  lineOf('to bottom', MINOR_LINE),\n].join(', ');\n\n/**\n * The lines hang from the near edge and reach one round of the loop past the far edge, so the\n * floor stays covered while they run. Both grids start from the same corner, so every fourth line\n * of the neutral grid is under a line of the hue.\n */\nfunction linesOf(cell: number): CSSProperties {\n  const major = cell * MAJOR_EVERY;\n  const majorTile = `${major}px ${major}px`;\n  const minorTile = `${cell}px ${cell}px`;\n  const tiles = [majorTile, majorTile, minorTile, minorTile];\n  return {\n    top: -major,\n    backgroundImage: LINES,\n    backgroundSize: tiles.join(', '),\n    backgroundPosition: '0 100%',\n  };\n}\n\nfunction runOf(lines: HTMLElement, cell: number, durationSeconds: number) {\n  const travel = cell * MAJOR_EVERY;\n  const duration = durationSeconds * 1000;\n  const frames = [\n    { transform: 'translateY(0px)' },\n    { transform: `translateY(${travel}px)` },\n  ];\n  return lines.animate(frames, {\n    duration,\n    easing: 'linear',\n    iterations: Infinity,\n  });\n}\n\nexport type PerspectiveGridProps = {\n  className?: string;\n  /** Any colour token, such as `var(--primary)` or `var(--series-2)`. Every fourth line wears it. */\n  hue?: string;\n  /** The side of a cell of the floor, in pixels. */\n  size?: number;\n  /** Seconds for the floor to run four cells towards the viewer. */\n  duration?: number;\n};\n\n/**\n * A grid floor that runs towards the viewer and fades into a soft horizon. The lines are hairlines\n * in the border colour, with the hue on every fourth one. It is all CSS: one plane laid down in 3D\n * and one transform that loops, so nothing is repainted while it runs. It fills its parent, which\n * must be positioned. Under reduced motion the floor stands still.\n */\nexport function PerspectiveGrid({\n  className,\n  hue = DEFAULT_HUE,\n  size = DEFAULT_CELL,\n  duration = DEFAULT_DURATION_S,\n}: PerspectiveGridProps) {\n  const hostRef = useRef<HTMLDivElement>(null);\n  const linesRef = useRef<HTMLDivElement>(null);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const cell = Math.max(MIN_CELL, size);\n\n  useEffect(() => {\n    const host = hostRef.current;\n    const lines = linesRef.current;\n    if (!host || !lines) {\n      return;\n    }\n    if (shouldReduceMotion) {\n      return;\n    }\n    const run = runOf(lines, cell, duration);\n    return runWhileShowing(host, [run]);\n  }, [cell, duration, shouldReduceMotion]);\n\n  return (\n    <div\n      ref={hostRef}\n      aria-hidden='true'\n      style={{ ...EYE, color: hue }}\n      className={cn(\n        'pointer-events-none absolute inset-0 overflow-hidden transition-colors duration-500',\n        className\n      )}\n    >\n      <div\n        style={FLOOR}\n        className='absolute -inset-x-3/4 bottom-0 origin-bottom [mask-image:linear-gradient(to_top,black_12%,transparent_92%)]'\n      >\n        <div\n          ref={linesRef}\n          style={linesOf(cell)}\n          className='absolute inset-x-0 bottom-0'\n        />\n      </div>\n    </div>\n  );\n}\n\nexport default function Background09() {\n  const { hue, nextHue } = useHueCycle();\n\n  return (\n    <DemoBand\n      title='A floor that runs to the horizon'\n      background={<PerspectiveGrid hue={hue} />}\n    >\n      <Button onClick={nextHue}>Change hue</Button>\n    </DemoBand>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/background/background-09.tsx"
    },
    {
      "path": "registry/ndeko/components/background/_parts/demo-band.tsx",
      "content": "import { useId, type ReactNode, type Ref } from 'react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\n\ntype BandAlign = 'center' | 'end';\n\nconst ALIGNMENTS: Record<BandAlign, string> = {\n  center: 'justify-center',\n  end: 'justify-end pb-10',\n};\n\ntype DemoBandProps = {\n  ref?: Ref<HTMLElement>;\n  title: string;\n  /** The background under test. It fills the band, behind the headline and the actions. */\n  background: ReactNode;\n  /** `end` sets the headline at the foot of the band and leaves its middle to the background. */\n  align?: BandAlign;\n  children: ReactNode;\n};\n\n/**\n * The band every background is shown in: the page colour, a headline in the foreground colour and\n * the actions laid straight over the background, to prove that text stays readable above it.\n */\nexport function DemoBand({\n  ref,\n  title,\n  background,\n  align = 'center',\n  children,\n}: DemoBandProps) {\n  const titleId = useId();\n\n  return (\n    <section\n      ref={ref}\n      aria-labelledby={titleId}\n      className={cn(\n        'bg-background @container relative isolate flex h-90 w-full flex-col items-center overflow-hidden rounded-xl',\n        ALIGNMENTS[align]\n      )}\n    >\n      {background}\n      <div className='relative flex max-w-lg flex-col items-center gap-5 px-6 text-center'>\n        <h3\n          id={titleId}\n          className='text-2xl font-semibold text-balance @lg:text-3xl'\n        >\n          {title}\n        </h3>\n        <div className='flex flex-wrap items-center justify-center gap-2'>\n          {children}\n        </div>\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/demo-band.tsx"
    },
    {
      "path": "registry/ndeko/components/background/_parts/hue.ts",
      "content": "'use client';\n\nimport { useState } from 'react';\n\n/** A background wears one hue: the brand unless it is told otherwise. */\nexport const DEFAULT_HUE = 'var(--primary)';\n\n/** The brand first, then the series hues that differ from it. */\nconst DEMO_HUES = [\n  DEFAULT_HUE,\n  'var(--series-2)',\n  'var(--series-3)',\n  'var(--series-4)',\n  'var(--series-5)',\n];\n\n/** The hue of a demo, and the step to the next one, to show a background in each hue it accepts. */\nexport function useHueCycle() {\n  const [index, setIndex] = useState(0);\n  const hue = DEMO_HUES[index] ?? DEFAULT_HUE;\n\n  function nextHue() {\n    setIndex((current) => {\n      const next = current + 1;\n      return next % DEMO_HUES.length;\n    });\n  }\n\n  return { hue, nextHue };\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/hue.ts"
    },
    {
      "path": "registry/ndeko/components/background/_parts/loops.ts",
      "content": "import { watchShowing } from './showing';\n\nfunction hold(animations: Animation[]) {\n  for (const animation of animations) {\n    animation.pause();\n  }\n}\n\nfunction resume(animations: Animation[]) {\n  for (const animation of animations) {\n    animation.play();\n  }\n}\n\nfunction cancel(animations: Animation[]) {\n  for (const animation of animations) {\n    animation.cancel();\n  }\n}\n\n/**\n * Lands every transition still running under `host` at its end value. A transition asks for frames\n * until it ends, on screen or not, and a host that stops showing must ask for none.\n */\nexport function landTransitions(host: Element) {\n  const animations = host.getAnimations({ subtree: true });\n  for (const animation of animations) {\n    const isTransition = animation instanceof CSSTransition;\n    if (isTransition) {\n      animation.finish();\n    }\n  }\n}\n\n/**\n * Endless animations that run only while their host shows. Off screen and in a hidden tab they are\n * paused: they keep their place and ask for no frame. They start paused, and `onShowing` is told\n * each time the host starts or stops showing. The function returned removes them.\n */\nexport function runWhileShowing(\n  host: Element,\n  animations: Animation[],\n  onShowing?: (isShowing: boolean) => void\n) {\n  hold(animations);\n  const stopWatching = watchShowing(host, (isShowing) => {\n    onShowing?.(isShowing);\n    if (isShowing) {\n      resume(animations);\n      return;\n    }\n    hold(animations);\n  });\n  return () => {\n    stopWatching();\n    cancel(animations);\n  };\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/loops.ts"
    },
    {
      "path": "registry/ndeko/components/background/_parts/showing.ts",
      "content": "/**\n * A background sits behind content for as long as the page is open, so everything it runs hangs on\n * this answer: its box touches the screen and the tab is the one looked at. `onChange` is called\n * each time the answer changes, starting from \"not showing\". The function returned ends the watch.\n */\nexport function watchShowing(\n  element: Element,\n  onChange: (isShowing: boolean) => void\n) {\n  let isOnScreen = false;\n  let wasShowing = false;\n\n  function report() {\n    const isTabShown = document.visibilityState === 'visible';\n    const isShowing = isOnScreen && isTabShown;\n    if (isShowing === wasShowing) {\n      return;\n    }\n    wasShowing = isShowing;\n    onChange(isShowing);\n  }\n\n  function onCrossing(entries: IntersectionObserverEntry[]) {\n    const latest = entries.at(-1);\n    if (!latest) {\n      return;\n    }\n    isOnScreen = latest.isIntersecting;\n    report();\n  }\n\n  const observer = new IntersectionObserver(onCrossing);\n  observer.observe(element);\n  document.addEventListener('visibilitychange', report);\n\n  return () => {\n    observer.disconnect();\n    document.removeEventListener('visibilitychange', report);\n  };\n}\n",
      "type": "registry:component",
      "target": "components/background/_parts/showing.ts"
    }
  ],
  "categories": [
    "components",
    "background"
  ],
  "type": "registry:component"
}