{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "badge-14",
  "title": "Scan badge",
  "description": "A drawn code whose cells fall like grains into a small badge once it is scanned, the badge filling with the success tint and reading Scanned as the last ones land, then the cells growing back from the top left corner; the cells only fade under reduced motion.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/seeded.json",
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/badge/badge-14.tsx",
      "content": "'use client';\n\nimport { useEffect, useMemo, useState } from 'react';\n\nimport {\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { CheckIcon, ScanIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\nimport { ScanCells } from './_parts/scan-cells';\nimport { BADGE_GAP, CARD_PADDING, GRID, grainsOf } from './_parts/scan-pattern';\nimport { useHover } from './_parts/use-hover';\n\ntype UnitStyle = React.CSSProperties & { '--u': string };\n\n/** One module of the code: 9px, and narrower where the container is too narrow for the whole code. */\nconst UNIT_STYLE: UnitStyle = { '--u': 'min(0.5625rem, 3.4cqw)' };\n\nconst CARD_STYLE: React.CSSProperties = {\n  padding: `calc(var(--u) * ${CARD_PADDING})`,\n};\n\nconst CODE_STYLE: React.CSSProperties = {\n  width: `calc(var(--u) * ${GRID})`,\n};\n\nconst BADGE_STYLE: React.CSSProperties = {\n  marginTop: `calc(var(--u) * ${BADGE_GAP})`,\n};\n\n/** The badge reads Scanned once most of the grains have landed in it. */\nconst LABEL_AT_MS = 1100;\n\n/** The tint rises in the badge from the first grain that lands to the last. */\nconst FILL_DELAY_MS = 400;\n\nconst FILL_MS = 900;\n\nconst DRAIN_MS = 200;\n\nconst EASE_IN_OUT = 'cubic-bezier(0.77, 0, 0.175, 1)';\n\nconst EASE_OUT = 'cubic-bezier(0.23, 1, 0.32, 1)';\n\nconst STILL_FADE = 'opacity 200ms linear';\n\nconst STATUS_ROW = 'flex items-center gap-1.5';\n\nconst READY_LABEL = 'Ready to scan';\n\nconst SCANNED_LABEL = 'Scanned';\n\nfunction landingDelayOf(isStill: boolean) {\n  if (isStill) {\n    return 0;\n  }\n  return LABEL_AT_MS;\n}\n\nfunction statusKeyOf(isScanned: boolean) {\n  if (isScanned) {\n    return 'scanned';\n  }\n  return 'ready';\n}\n\nfunction fillOpacityOf(isFilled: boolean) {\n  if (isFilled) {\n    return 1;\n  }\n  return 0;\n}\n\nfunction fillStyleOf(isFilled: boolean, isStill: boolean): React.CSSProperties {\n  if (isStill) {\n    return { opacity: fillOpacityOf(isFilled), transition: STILL_FADE };\n  }\n  if (isFilled) {\n    const rise = `scale ${FILL_MS}ms ${EASE_IN_OUT} ${FILL_DELAY_MS}ms`;\n    return { scale: '1 1', transition: rise };\n  }\n  return { scale: '1 0', transition: `scale ${DRAIN_MS}ms ${EASE_OUT}` };\n}\n\n/** True once the grains of a scan have had the time to land. Going back to unscanned is at once. */\nfunction useLanded(isScanned: boolean, landingMs: number) {\n  const [hasLanded, setHasLanded] = useState(isScanned);\n\n  useEffect(() => {\n    if (!isScanned || hasLanded) {\n      return;\n    }\n    const timer = window.setTimeout(() => setHasLanded(true), landingMs);\n    return () => window.clearTimeout(timer);\n  }, [isScanned, hasLanded, landingMs]);\n\n  if (!isScanned && hasLanded) {\n    setHasLanded(false);\n  }\n\n  return isScanned && hasLanded;\n}\n\ntype StatusProps = {\n  isScanned: boolean;\n  readyLabel: string;\n  scannedLabel: string;\n};\n\nfunction Status({ isScanned, readyLabel, scannedLabel }: StatusProps) {\n  if (isScanned) {\n    return (\n      <span className={STATUS_ROW}>\n        <CheckIcon strokeWidth={2.25} />\n        {scannedLabel}\n      </span>\n    );\n  }\n  return (\n    <span className={STATUS_ROW}>\n      <ScanIcon />\n      {readyLabel}\n    </span>\n  );\n}\n\nexport type ScanBadgeProps = {\n  /** What the code stands for. Its cells are drawn from this text, so one text always draws one code. It is a picture of a code, not one a camera can read. */\n  value: string;\n  /** True once the code was scanned: its cells pour into the badge. Back to false, they grow back. */\n  isScanned: boolean;\n  /** What the badge says before the scan. */\n  readyLabel?: string;\n  /** What it says once the cells have landed. */\n  scannedLabel?: string;\n  className?: string;\n};\n\n/**\n * A code drawn in cells, with a badge under it. When the code is scanned the cells fall like grains\n * into the badge, which fills with the success tint as they land and then says Scanned; when it is\n * ready again they grow back from the top left corner. Each cell is a transition of its own, so the\n * browser moves them and nothing runs at rest. Under reduced motion the cells fade where they stand.\n * The change is not announced: say it where the scan is handled.\n */\nexport function ScanBadge({\n  value,\n  isScanned,\n  readyLabel = READY_LABEL,\n  scannedLabel = SCANNED_LABEL,\n  className,\n}: ScanBadgeProps) {\n  const isStill = usePrefersReducedMotion();\n  const grains = useMemo(() => grainsOf(value), [value]);\n  const isLabelScanned = useLanded(isScanned, landingDelayOf(isStill));\n\n  return (\n    <div className={cn('@container w-full', className)}>\n      <div\n        style={UNIT_STYLE}\n        className='mx-auto flex w-fit flex-col items-center'\n      >\n        <div\n          style={CARD_STYLE}\n          className='bg-card hairline-ring ring-border rounded-xl shadow-[0_1px_2px_rgb(0_0_0/0.04)]'\n        >\n          <div style={CODE_STYLE} className='relative aspect-square'>\n            <ScanCells grains={grains} isFallen={isScanned} isStill={isStill} />\n          </div>\n        </div>\n        <Badge\n          variant='outline'\n          data-scanned={isLabelScanned}\n          style={BADGE_STYLE}\n          className='data-[scanned=true]:text-success-foreground data-[scanned=true]:ring-success/30 relative z-10 h-6 gap-0 overflow-hidden rounded-full px-2.5 transition-[color,box-shadow] duration-300'\n        >\n          <span\n            aria-hidden='true'\n            style={fillStyleOf(isScanned, isStill)}\n            className='bg-success/10 absolute inset-0 origin-bottom'\n          />\n          <AnimatedSize as='span' axis='width' contentClassName='relative flex'>\n            <Swap swapKey={statusKeyOf(isLabelScanned)}>\n              <Status\n                isScanned={isLabelScanned}\n                readyLabel={readyLabel}\n                scannedLabel={scannedLabel}\n              />\n            </Swap>\n          </AnimatedSize>\n        </Badge>\n      </div>\n    </div>\n  );\n}\n\ntype ScanPhase = 'ready' | 'scanned';\n\nconst PHASES: Segment<ScanPhase>[] = [\n  { value: 'ready', label: 'Ready' },\n  { value: 'scanned', label: 'Scanned' },\n];\n\n/** Long enough in each state for the pour, the landing and the growing back to be seen whole. */\nconst READY_HOLD_MS = 1500;\n\nconst SCANNED_HOLD_MS = 3700;\n\nconst REGROW_HOLD_MS = 1200;\n\nconst SAMPLE_CODE = 'ndekoui-entry-0042';\n\nfunction phaseOf(isScanned: boolean): ScanPhase {\n  if (isScanned) {\n    return 'scanned';\n  }\n  return 'ready';\n}\n\nfunction statusLineOf(isScanned: boolean) {\n  if (isScanned) {\n    return SCANNED_LABEL;\n  }\n  return READY_LABEL;\n}\n\nexport default function Badge14() {\n  const [isScanned, setIsScanned] = useState(false);\n  const [announcement, setAnnouncement] = useState('');\n  const { isHovered, hoverHandlers } = useHover();\n  const steps: AutoplayStep[] = [\n    { after: READY_HOLD_MS, run: () => setIsScanned(true) },\n    { after: SCANNED_HOLD_MS, run: () => setIsScanned(false) },\n  ];\n  const { ref } = useAutoplay(steps, {\n    loopAfter: REGROW_HOLD_MS,\n    onReset: () => setIsScanned(false),\n    isEnabled: !isHovered,\n  });\n\n  useKeptHeight(ref);\n\n  function choose(phase: ScanPhase) {\n    const isScannedNow = phase === 'scanned';\n    setIsScanned(isScannedNow);\n    setAnnouncement(statusLineOf(isScannedNow));\n  }\n\n  return (\n    <div\n      ref={ref}\n      className='flex w-full max-w-[22rem] flex-col items-center gap-5'\n      {...hoverHandlers}\n    >\n      <ScanBadge value={SAMPLE_CODE} isScanned={isScanned} />\n      <Segments\n        value={phaseOf(isScanned)}\n        segments={PHASES}\n        onValueChange={choose}\n        label='Scan state'\n      />\n      <LiveRegion message={announcement} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/badge/badge-14.tsx"
    },
    {
      "path": "registry/ndeko/components/badge/_parts/scan-cells.tsx",
      "content": "import { GRID, type Grain } from './scan-pattern';\n\ntype CellsStyle = React.CSSProperties & {\n  '--cell': string;\n  '--fall-ease': string;\n};\n\n/** A module is drawn a little smaller than its square, so the cells read as separate grains. */\nconst REST_SCALE = 0.88;\n\nconst CELL_PERCENT = 100 / GRID;\n\nconst GROW_MS = 340;\n\nconst APPEAR_MS = 200;\n\n/** A grain fades over the last part of its fall, so none is left showing under the badge. */\nconst FADE_SHARE = 0.3;\n\nconst STILL_FADE = 'opacity 200ms linear';\n\n/** The size of a cell and the curve of a fall are written once on the grid, not on each of its cells. */\nconst CELLS_STYLE: CellsStyle = {\n  '--cell': `${percentOf(1)}%`,\n  '--fall-ease': 'cubic-bezier(0.55, 0.085, 0.68, 0.53)',\n};\n\nfunction percentOf(index: number) {\n  const percent = index * CELL_PERCENT;\n  return Math.round(percent * 1000) / 1000;\n}\n\nfunction placeOf(grain: Grain): React.CSSProperties {\n  return {\n    left: `${percentOf(grain.col)}%`,\n    top: `${percentOf(grain.row)}%`,\n  };\n}\n\n/** A translate in percent of the cell's own size, so one module is 100%. */\nfunction travelOf(grain: Grain) {\n  const across = Math.round(grain.fallX * 100);\n  const down = Math.round(grain.fallY * 100);\n  return `${across}% ${down}%`;\n}\n\n/**\n * A grain falls the way a weight does, slowly at first and then faster, fades out over the end of\n * its fall, and only then shrinks to nothing: the shrinking is what lets it grow back from nothing.\n */\nfunction fallTransitionOf(grain: Grain) {\n  const fadeMs = Math.round(grain.fallMs * FADE_SHARE);\n  const landsAt = grain.pourDelayMs + grain.fallMs;\n  const fall = `translate ${grain.fallMs}ms var(--fall-ease) ${grain.pourDelayMs}ms`;\n  const fade = `opacity ${fadeMs}ms linear ${landsAt - fadeMs}ms`;\n  const shrink = `scale 1ms linear ${landsAt}ms`;\n  return [fall, fade, shrink].join(', ');\n}\n\n/** Growing back is in place: the translate is not in the list, so the cell is back on its square at once, unseen. */\nfunction growTransitionOf(grain: Grain) {\n  const grow = `scale ${GROW_MS}ms var(--ease-out-strong) ${grain.growDelayMs}ms`;\n  const appear = `opacity ${APPEAR_MS}ms linear ${grain.growDelayMs}ms`;\n  return [grow, appear].join(', ');\n}\n\nfunction stillOpacityOf(isFallen: boolean) {\n  if (isFallen) {\n    return 0;\n  }\n  return 1;\n}\n\nfunction grainStyleOf(\n  grain: Grain,\n  isFallen: boolean,\n  isStill: boolean\n): React.CSSProperties {\n  const place = placeOf(grain);\n  const restScale = String(REST_SCALE);\n  if (isStill) {\n    return {\n      ...place,\n      scale: restScale,\n      opacity: stillOpacityOf(isFallen),\n      transition: STILL_FADE,\n    };\n  }\n  if (isFallen) {\n    return {\n      ...place,\n      translate: travelOf(grain),\n      scale: '0',\n      opacity: 0,\n      transition: fallTransitionOf(grain),\n    };\n  }\n  return {\n    ...place,\n    translate: '0% 0%',\n    scale: restScale,\n    opacity: 1,\n    transition: growTransitionOf(grain),\n  };\n}\n\nexport type ScanCellsProps = {\n  grains: readonly Grain[];\n  /** The cells have poured into the badge. */\n  isFallen: boolean;\n  /** Reduced motion: the cells fade out and in where they stand. */\n  isStill: boolean;\n};\n\n/**\n * The cells of the code, each one its own element placed on the grid of the code. A change of\n * `isFallen` moves them with transitions of `translate`, `scale` and `opacity` and nothing else, so\n * the browser animates them off the main thread and nothing runs between two changes.\n */\nexport function ScanCells({ grains, isFallen, isStill }: ScanCellsProps) {\n  return (\n    <div\n      aria-hidden='true'\n      style={CELLS_STYLE}\n      className='absolute inset-0 forced-colors:*:bg-[CanvasText]'\n    >\n      {grains.map((grain) => (\n        <span\n          key={`${grain.col}-${grain.row}`}\n          style={grainStyleOf(grain, isFallen, isStill)}\n          className='bg-foreground absolute size-(--cell) rounded-[30%]'\n        />\n      ))}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/badge/_parts/scan-cells.tsx"
    },
    {
      "path": "registry/ndeko/components/badge/_parts/scan-pattern.ts",
      "content": "import { hashOf } from '@/registry/ndeko/lib/seeded';\n\nexport const GRID = 15;\n\n/** An eye is the mark at a corner of a code: a ring of modules round an empty ring and a dot. */\nconst EYE = 5;\n\nconst EYE_MARGIN = 1;\n\nconst DATA_DENSITY_PERCENT = 50;\n\n/** The padding of the card round the code and the gap under it, in modules: the grains need them to know how far the badge is. */\nexport const CARD_PADDING = 1.25;\n\nexport const BADGE_GAP = 1.25;\n\n/** A grain ends this far into the badge, where the badge hides it. */\nconst SINK = 0.9;\n\nconst LAND_AT = GRID + CARD_PADDING + BADGE_GAP + SINK;\n\n/** The longest fall, from the top row, in milliseconds. A nearer grain falls for less, as under gravity. */\nconst FALL_MS = 700;\n\n/** The bottom row sets off first and the top row this long after it. */\nconst POUR_SPAN_MS = 520;\n\nconst POUR_JITTER_MS = 140;\n\n/** The cells grow back from the top left corner to the bottom right one in this span. */\nconst GROW_SPAN_MS = 600;\n\nconst GROW_JITTER_MS = 80;\n\n/** How far to the middle of the code a grain drifts on its way down, so the cells gather into a stream. */\nconst FUNNEL = 0.6;\n\nexport type Grain = {\n  col: number;\n  row: number;\n  /** How far the grain travels across, in modules, to reach the stream. */\n  fallX: number;\n  /** How far it travels down, in modules, to reach the badge. */\n  fallY: number;\n  fallMs: number;\n  /** When it sets off, counted from the moment the code is scanned. */\n  pourDelayMs: number;\n  /** When it starts to grow back, counted from the moment the code is ready again. */\n  growDelayMs: number;\n};\n\ntype Spot = {\n  col: number;\n  row: number;\n};\n\ntype Offsets = {\n  across: number;\n  down: number;\n};\n\nconst EYE_CORNERS: readonly Spot[] = [\n  { col: 0, row: 0 },\n  { col: GRID - EYE, row: 0 },\n  { col: 0, row: GRID - EYE },\n];\n\nfunction hundredthsOf(value: number) {\n  return Math.round(value * 100) / 100;\n}\n\nfunction offsetsIn(corner: Spot, spot: Spot): Offsets {\n  return { across: spot.col - corner.col, down: spot.row - corner.row };\n}\n\nfunction isInsideBox(offsets: Offsets, from: number, to: number) {\n  const isInsideAcross = offsets.across >= from && offsets.across < to;\n  const isInsideDown = offsets.down >= from && offsets.down < to;\n  return isInsideAcross && isInsideDown;\n}\n\nfunction eyeHolding(spot: Spot, margin: number) {\n  return EYE_CORNERS.find((corner) => {\n    const offsets = offsetsIn(corner, spot);\n    return isInsideBox(offsets, -margin, EYE + margin);\n  });\n}\n\nfunction isOnEyeRing(offsets: Offsets) {\n  const last = EYE - 1;\n  const isEdgeAcross = offsets.across === 0 || offsets.across === last;\n  const isEdgeDown = offsets.down === 0 || offsets.down === last;\n  return isEdgeAcross || isEdgeDown;\n}\n\nfunction isEyeDot(offsets: Offsets) {\n  const middle = (EYE - 1) / 2;\n  const isMiddleAcross = offsets.across === middle;\n  const isMiddleDown = offsets.down === middle;\n  return isMiddleAcross && isMiddleDown;\n}\n\nfunction isDataModule(value: string, spot: Spot) {\n  const hash = hashOf(`${value}:${spot.col}:${spot.row}`);\n  const share = (hash >>> 11) % 100;\n  return share < DATA_DENSITY_PERCENT;\n}\n\nfunction isFilled(value: string, spot: Spot) {\n  const eye = eyeHolding(spot, 0);\n  if (eye) {\n    const offsets = offsetsIn(eye, spot);\n    return isOnEyeRing(offsets) || isEyeDot(offsets);\n  }\n  const isBesideEye = eyeHolding(spot, EYE_MARGIN) !== undefined;\n  if (isBesideEye) {\n    return false;\n  }\n  return isDataModule(value, spot);\n}\n\n/** A steady number between 0 and 1 for a spot, so a grain never changes its mind between two renders. */\nfunction jitterOf(value: string, spot: Spot) {\n  const hash = hashOf(`${value}|${spot.col}|${spot.row}|grain`);\n  const thousandths = (hash >>> 6) % 1000;\n  return thousandths / 1000;\n}\n\nfunction grainOf(value: string, spot: Spot): Grain {\n  const jitter = jitterOf(value, spot);\n  const fallY = LAND_AT - spot.row;\n  const towardsStream = GRID / 2 - (spot.col + 0.5);\n  const nearness = fallY / LAND_AT;\n  const fallMs = Math.round(FALL_MS * Math.sqrt(nearness));\n  const rowsBelow = (GRID - 1 - spot.row) / (GRID - 1);\n  const pourDelayMs = Math.round(\n    rowsBelow * POUR_SPAN_MS + jitter * POUR_JITTER_MS\n  );\n  const diagonal = (spot.col + spot.row) / (2 * (GRID - 1));\n  const growDelayMs = Math.round(\n    diagonal * GROW_SPAN_MS + jitter * GROW_JITTER_MS\n  );\n  return {\n    col: spot.col,\n    row: spot.row,\n    fallX: hundredthsOf(towardsStream * FUNNEL),\n    fallY: hundredthsOf(fallY),\n    fallMs,\n    pourDelayMs,\n    growDelayMs,\n  };\n}\n\n/**\n * The cells of a code drawn from a text, each with the way it falls into the badge and the way it\n * grows back. The same text always gives the same code, on the server and in the browser.\n */\nexport function grainsOf(value: string): Grain[] {\n  const grains: Grain[] = [];\n  for (let row = 0; row < GRID; row += 1) {\n    for (let col = 0; col < GRID; col += 1) {\n      const spot: Spot = { col, row };\n      if (isFilled(value, spot)) {\n        grains.push(grainOf(value, spot));\n      }\n    }\n  }\n  return grains;\n}\n",
      "type": "registry:component",
      "target": "components/badge/_parts/scan-pattern.ts"
    },
    {
      "path": "registry/ndeko/components/badge/_parts/use-hover.ts",
      "content": "'use client';\n\nimport { useState } from 'react';\n\n/** Whether a mouse or a pen rests on an element. A finger does not hover, so a touch never counts. */\nexport function useHover() {\n  const [isHovered, setIsHovered] = useState(false);\n\n  function hoverStarts(event: React.PointerEvent<HTMLElement>) {\n    if (event.pointerType !== 'touch') {\n      setIsHovered(true);\n    }\n  }\n\n  function hoverEnds() {\n    setIsHovered(false);\n  }\n\n  const hoverHandlers = {\n    onPointerEnter: hoverStarts,\n    onPointerLeave: hoverEnds,\n  };\n\n  return { isHovered, hoverHandlers };\n}\n",
      "type": "registry:component",
      "target": "components/badge/_parts/use-hover.ts"
    }
  ],
  "categories": [
    "components",
    "badge"
  ],
  "type": "registry:component"
}