{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "badge-16",
  "title": "Seal",
  "description": "A round seal in one colour whose line of text circles a fixed centre label on a slow turn that holds off screen, under the pointer and under reduced motion, and that the demonstration can slow, quicken or pause.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/segments.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-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-16.tsx",
      "content": "'use client';\n\nimport { useEffect, useMemo, useRef, 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 { cn } from '@/registry/ndeko/lib/utils';\nimport { Badge, type BadgeProps } from '@/registry/ndeko/ui/badge';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\nimport { ringOf, TOP_EM } from './_parts/seal-ring';\nimport { useHover } from './_parts/use-hover';\nimport { usePlayWhileSeen } from './_parts/use-play-while-seen';\n\ntype RingStyle = React.CSSProperties & { '--r': string };\n\n/** The ring is one turn long at normal speed over this many seconds, and the speed it turns at is a playback rate of it. */\nconst TURN_SECONDS = 60;\n\nconst DEFAULT_SECONDS_PER_TURN = 28;\n\nconst TURN_KEYFRAMES: Keyframe[] = [\n  { transform: 'rotate(0deg)' },\n  { transform: 'rotate(360deg)' },\n];\n\n/**\n * The letters stand in a ring that has the size of the seal's text. When a long phrase makes them\n * smaller, the ring is given the smaller text size and the top of the letters is measured in it.\n */\nfunction ringStyleOf(scale: number): RingStyle {\n  const size = Math.round(scale * 1000) / 1000;\n  const top = Math.round((TOP_EM / size) * 1000) / 1000;\n  return { fontSize: `${size}em`, '--r': `${top}em` };\n}\n\nfunction rateOf(secondsPerTurn: number) {\n  const isUsable = Number.isFinite(secondsPerTurn) && secondsPerTurn > 0;\n  if (!isUsable) {\n    return TURN_SECONDS / DEFAULT_SECONDS_PER_TURN;\n  }\n  return TURN_SECONDS / secondsPerTurn;\n}\n\nexport type SealProps = {\n  /** The line that turns round the ring. It repeats until the ring is full, so a phrase of two to four words fits best. */\n  text: string;\n  /** The word at the centre, which stays still. Keep it short. */\n  label: string;\n  /** The colour of the whole seal, one of the colours of a badge. */\n  variant?: BadgeProps['variant'];\n  /** How long one full turn takes, in seconds. */\n  secondsPerTurn?: number;\n  /** Stops the ring. It also holds off screen, in a hidden tab, under the pointer and under reduced motion. */\n  isTurning?: boolean;\n  className?: string;\n};\n\n/**\n * A round seal in one colour: a line of text turns slowly round a label that stays still. The ring\n * is one element turned by a transform that the browser runs off the main thread, and it holds\n * wherever nobody can read it, so the seal costs nothing off screen. The seal is read as one image.\n */\nexport function Seal({\n  text,\n  label,\n  variant = 'default',\n  secondsPerTurn = DEFAULT_SECONDS_PER_TURN,\n  isTurning = true,\n  className,\n}: SealProps) {\n  const { ref, isPlaying } = usePlayWhileSeen<HTMLSpanElement>();\n  const { isHovered, hoverHandlers } = useHover();\n  const ringRef = useRef<HTMLSpanElement>(null);\n  const turn = useRef<Animation | null>(null);\n  const ring = useMemo(() => ringOf(text), [text]);\n  const shouldTurn = isPlaying && isTurning && !isHovered;\n  const rate = rateOf(secondsPerTurn);\n\n  useEffect(() => {\n    const element = ringRef.current;\n    if (!element) {\n      return;\n    }\n    const animation = element.animate(TURN_KEYFRAMES, {\n      duration: TURN_SECONDS * 1000,\n      iterations: Number.POSITIVE_INFINITY,\n    });\n    animation.pause();\n    turn.current = animation;\n    return () => {\n      animation.cancel();\n      turn.current = null;\n    };\n  }, []);\n\n  useEffect(() => {\n    turn.current?.updatePlaybackRate(rate);\n  }, [rate]);\n\n  useEffect(() => {\n    const animation = turn.current;\n    if (!animation) {\n      return;\n    }\n    if (shouldTurn) {\n      animation.play();\n      return;\n    }\n    animation.pause();\n  }, [shouldTurn]);\n\n  return (\n    <span ref={ref} className='inline-flex shrink-0' {...hoverHandlers}>\n      <Badge\n        variant={variant}\n        role='img'\n        aria-label={`${label}, ${text}`}\n        className={cn(\n          'hairline-ring relative size-[11em] overflow-hidden rounded-full p-0 ring-current/25',\n          className\n        )}\n      >\n        <span\n          ref={ringRef}\n          aria-hidden='true'\n          style={ringStyleOf(ring.scale)}\n          className='absolute inset-0 select-none *:absolute *:top-[calc(50%-var(--r))] *:left-[calc(50%-0.5em)] *:h-(--r) *:w-[1em] *:origin-bottom *:text-center *:leading-none'\n        >\n          {ring.letters.map((letter, index) => (\n            <span key={index} style={{ rotate: `${letter.angle}deg` }}>\n              {letter.char}\n            </span>\n          ))}\n        </span>\n        <span\n          aria-hidden='true'\n          className='absolute inset-[2em] rounded-full bg-current/7'\n        />\n        <span className='relative w-[5.6em] text-center text-[1.15em] leading-tight font-semibold text-balance'>\n          {label}\n        </span>\n      </Badge>\n    </span>\n  );\n}\n\ntype Pace = 'calm' | 'quick' | 'paused';\n\nconst PACES: Segment<Pace>[] = [\n  { value: 'calm', label: 'Calm' },\n  { value: 'quick', label: 'Quick' },\n  { value: 'paused', label: 'Paused' },\n];\n\nconst SECONDS_PER_TURN: Record<Pace, number> = {\n  calm: 28,\n  quick: 9,\n  paused: 28,\n};\n\n/** Long enough at each pace for the difference to be seen before the demonstration goes round again. */\nconst CALM_SHOWN_MS = 6000;\n\nconst QUICK_SHOWN_MS = 5000;\n\nexport default function Badge16() {\n  const [pace, setPace] = useState<Pace>('calm');\n  const { isHovered, hoverHandlers } = useHover();\n  const steps: AutoplayStep[] = [\n    { after: CALM_SHOWN_MS, run: () => setPace('quick') },\n    { after: QUICK_SHOWN_MS, run: () => setPace('calm') },\n  ];\n  const { ref } = useAutoplay(steps, {\n    loopAfter: 0,\n    onReset: () => setPace('calm'),\n    isEnabled: !isHovered,\n  });\n  const isTurning = pace !== 'paused';\n\n  useKeptHeight(ref);\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      <Seal\n        text='Roasted in Goma'\n        label='Small batch'\n        secondsPerTurn={SECONDS_PER_TURN[pace]}\n        isTurning={isTurning}\n      />\n      <Segments\n        value={pace}\n        segments={PACES}\n        onValueChange={setPace}\n        label='Turning pace'\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/badge/badge-16.tsx"
    },
    {
      "path": "registry/ndeko/components/badge/_parts/seal-ring.ts",
      "content": "/** The radius of the line the letters are centred on, in em of the seal. */\nconst MIDDLE_EM = 4.4;\n\n/** How far from the centre of the seal the top of a letter stands, in em of the seal. */\nexport const TOP_EM = 4.9;\n\nconst CIRCUMFERENCE_EM = 2 * Math.PI * MIDDLE_EM;\n\nconst SEPARATOR = ' · ';\n\n/** One more repeat of the phrase is fitted only when its letters can stay at this share of their size or more. */\nconst LEAST_SHRINK = 0.85;\n\nconst DEFAULT_ADVANCE_EM = 0.56;\n\n/**\n * How wide a letter is, in em, for a typical sans face. The seal spreads its letters by these\n * widths so that an i and an m do not stand the same distance apart; the real face may differ a\n * little, and the ring still closes since the widths are only shares of the circumference.\n */\nconst ADVANCE_GROUPS: readonly (readonly [chars: string, advance: number])[] = [\n  [' ', 0.28],\n  ['ijl', 0.23],\n  [\"'\", 0.2],\n  [',.:;!|', 0.27],\n  ['·', 0.3],\n  ['ft', 0.29],\n  ['I-', 0.3],\n  ['r', 0.34],\n  ['ckvxysJz', 0.5],\n  ['L', 0.56],\n  ['FTZ', 0.61],\n  ['ABEKPSVXY', 0.67],\n  ['CDHNRU', 0.72],\n  ['w', 0.72],\n  ['GOQ', 0.78],\n  ['mM', 0.83],\n  ['W', 0.94],\n];\n\nexport type RingLetter = {\n  char: string;\n  /** Degrees clockwise from the top, where the letter stands. */\n  angle: number;\n};\n\nexport type Ring = {\n  letters: RingLetter[];\n  /** The size of the letters as a share of the text size of the seal: 1, or less when the phrase is longer than the ring. */\n  scale: number;\n};\n\ntype Slot = {\n  char: string;\n  /** Where the middle of the letter's slot lies along the ring, in em. */\n  centre: number;\n};\n\nfunction advancesOf(groups: typeof ADVANCE_GROUPS) {\n  const advances = new Map<string, number>();\n  for (const [chars, advance] of groups) {\n    for (const char of chars) {\n      advances.set(char, advance);\n    }\n  }\n  return advances;\n}\n\nconst ADVANCES = advancesOf(ADVANCE_GROUPS);\n\nfunction advanceOf(char: string) {\n  return ADVANCES.get(char) ?? DEFAULT_ADVANCE_EM;\n}\n\nfunction widthOf(chars: readonly string[]) {\n  let total = 0;\n  for (const char of chars) {\n    total += advanceOf(char);\n  }\n  return total;\n}\n\n/** How many times the phrase goes round: as many as fit, or one more when the letters need not shrink much to make room. */\nfunction repeatsFor(unitWidth: number) {\n  const fits = CIRCUMFERENCE_EM / unitWidth;\n  const lower = Math.max(1, Math.floor(fits));\n  const upper = lower + 1;\n  const upperScale = CIRCUMFERENCE_EM / (upper * unitWidth);\n  if (upperScale >= LEAST_SHRINK) {\n    return upper;\n  }\n  return lower;\n}\n\n/** Every letter gets a slot as wide as itself plus its share of what the ring has left over, so the slots fill the ring exactly. */\nfunction slotsOf(\n  unit: readonly string[],\n  repeats: number,\n  scale: number,\n  spacing: number\n) {\n  const slots: Slot[] = [];\n  let cursor = 0;\n  for (let repeat = 0; repeat < repeats; repeat += 1) {\n    for (const char of unit) {\n      const width = advanceOf(char) * scale + spacing;\n      slots.push({ char, centre: cursor + width / 2 });\n      cursor += width;\n    }\n  }\n  return slots;\n}\n\nfunction angleOf(position: number, offset: number) {\n  const degrees = (position / CIRCUMFERENCE_EM) * 360 - offset;\n  return Math.round(degrees * 100) / 100;\n}\n\n/**\n * The letters of a phrase laid round a ring, the phrase repeated, a dot between two repeats, the\n * first phrase centred at the top. The same text always gives the same ring.\n */\nexport function ringOf(text: string): Ring {\n  const phrase = Array.from(text.trim());\n  if (phrase.length === 0) {\n    return { letters: [], scale: 1 };\n  }\n  const unit = [...phrase, ...Array.from(SEPARATOR)];\n  const unitWidth = widthOf(unit);\n  const repeats = repeatsFor(unitWidth);\n  const natural = repeats * unitWidth;\n  const scale = Math.min(1, CIRCUMFERENCE_EM / natural);\n  const leftOver = CIRCUMFERENCE_EM - natural * scale;\n  const spacing = leftOver / (repeats * unit.length);\n  const slots = slotsOf(unit, repeats, scale, spacing);\n  const lastIndex = phrase.length - 1;\n  const lastOfPhrase = slots[lastIndex];\n  const lastWidth = advanceOf(lastOfPhrase.char) * scale + spacing;\n  const phraseLength = lastOfPhrase.centre + lastWidth / 2;\n  const offset = (phraseLength / 2 / CIRCUMFERENCE_EM) * 360;\n  const inked = slots.filter((slot) => slot.char !== ' ');\n  const letters = inked.map((slot) => ({\n    char: slot.char,\n    angle: angleOf(slot.centre, offset),\n  }));\n  return { letters, scale };\n}\n",
      "type": "registry:component",
      "target": "components/badge/_parts/seal-ring.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"
    },
    {
      "path": "registry/ndeko/components/badge/_parts/use-play-while-seen.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\n/**\n * A badge that moves on its own plays only while someone can see it: on screen, in the tab that is\n * shown, without reduced motion. Everything that repeats hangs on `isPlaying`, and `isStill` asks\n * for the resting picture.\n */\nexport function usePlayWhileSeen<Element extends HTMLElement = HTMLElement>() {\n  const ref = useRef<Element>(null);\n  const isInView = useInView(ref);\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/badge/_parts/use-play-while-seen.ts"
    }
  ],
  "categories": [
    "components",
    "badge"
  ],
  "type": "registry:component"
}