{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "card-14",
  "title": "Range summary",
  "description": "A reading on a range cut into bands, where the marker slides along the range and the weekly and monthly averages roll when the period changes.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/card.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.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/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/card/card-14.tsx",
      "content": "'use client';\n\nimport { useId, useState } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { WordRoll } from '@/components/core/word-roll';\nimport type { AutoplayStep } from '@/registry/ndeko/hooks/use-autoplay';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Card } from '@/registry/ndeko/ui/card';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\nimport { SampleNote } from './_parts/sample-note';\nimport { useCardDemo } from './_parts/use-card-demo';\n\nexport type RangeBand = {\n  id: string;\n  label: string;\n  /** Where the band ends on the scale. A band starts where the one before it ends, the first one at the start of the scale. */\n  upTo: number;\n};\n\nexport type RangePeriod = {\n  id: string;\n  label: string;\n  today: number;\n  weeklyAverage: number;\n  monthlyAverage: number;\n};\n\ntype BandSpan = { band: RangeBand; from: number; width: number };\n\nconst BAND_GLOW =\n  'bg-primary/60 absolute inset-0 transition-opacity duration-300 ease-(--ease-out-strong)';\n\nfunction spansOf(bands: RangeBand[], scaleStart: number) {\n  const spans: BandSpan[] = [];\n  let from = scaleStart;\n  for (const band of bands) {\n    const reach = band.upTo - from;\n    const width = Math.max(reach, 0);\n    spans.push({ band, from, width });\n    from = Math.max(band.upTo, from);\n  }\n  return spans;\n}\n\nfunction lastOf(spans: BandSpan[]) {\n  const lastIndex = spans.length - 1;\n  return spans[lastIndex];\n}\n\nfunction scaleEndOf(spans: BandSpan[], scaleStart: number) {\n  const last = lastOf(spans);\n  if (!last) {\n    return scaleStart;\n  }\n  return last.from + last.width;\n}\n\n/** The band a value falls in: the first one that reaches it, or the last one for a value past the scale. */\nfunction bandOf(value: number, spans: BandSpan[]) {\n  const reaching = spans.find((span) => value <= span.band.upTo);\n  return reaching ?? lastOf(spans);\n}\n\n/** How far along the scale a value sits, from 0 to 100, held inside the track. */\nfunction shareOf(value: number, scaleStart: number, scaleEnd: number) {\n  const length = scaleEnd - scaleStart;\n  if (length <= 0) {\n    return 0;\n  }\n  const along = value - scaleStart;\n  const part = along / length;\n  const percent = part * 100;\n  const atLeastZero = Math.max(percent, 0);\n  return Math.min(atLeastZero, 100);\n}\n\nfunction comparisonOf(today: number, average: number) {\n  const exactDifference = today - average;\n  const difference = Math.round(exactDifference);\n  const gap = Math.abs(difference);\n  if (difference === 0) {\n    return 'Level with the weekly average';\n  }\n  if (difference < 0) {\n    return `${gap} below the weekly average`;\n  }\n  return `${gap} above the weekly average`;\n}\n\nfunction opacityOf(isShown: boolean) {\n  if (isShown) {\n    return 'opacity-100';\n  }\n  return 'opacity-0';\n}\n\nfunction labelToneOf(isActive: boolean) {\n  if (isActive) {\n    return 'font-medium';\n  }\n  return 'text-muted-foreground';\n}\n\ntype RangeTrackProps = {\n  spans: BandSpan[];\n  activeBandId: string | undefined;\n  /** Where the marker sits, as a percentage of the track. */\n  share: number;\n};\n\nfunction RangeTrack({ spans, activeBandId, share }: RangeTrackProps) {\n  const markerStyle = { transform: `translateX(${share}cqw)` };\n\n  return (\n    <div className='flex flex-col gap-2'>\n      <div aria-hidden='true' className='@container relative py-1'>\n        <div className='flex h-2 gap-0.5'>\n          {spans.map((span) => {\n            const isActive = span.band.id === activeBandId;\n            const bandStyle = { flexGrow: span.width };\n            return (\n              <span\n                key={span.band.id}\n                style={bandStyle}\n                className='bg-foreground/10 relative basis-0 overflow-hidden rounded-full'\n              >\n                <span className={cn(BAND_GLOW, opacityOf(isActive))} />\n              </span>\n            );\n          })}\n        </div>\n        <div\n          style={markerStyle}\n          className='absolute inset-y-0 start-0 w-0 transition-transform duration-500 ease-(--ease-in-out-strong)'\n        >\n          <span className='bg-card ring-primary absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full shadow-[0_1px_2px_rgb(0_0_0/0.14)] ring-2' />\n        </div>\n      </div>\n      <ul className='flex gap-0.5 text-xs'>\n        {spans.map((span) => {\n          const isActive = span.band.id === activeBandId;\n          const bandStyle = { flexGrow: span.width };\n          return (\n            <li\n              key={span.band.id}\n              style={bandStyle}\n              className='flex min-w-0 basis-0 flex-col items-center'\n            >\n              <span className={cn('truncate', labelToneOf(isActive))}>\n                {span.band.label}\n              </span>\n              <span className='text-muted-foreground truncate tabular-nums'>\n                {span.from} to {span.band.upTo}\n              </span>\n            </li>\n          );\n        })}\n      </ul>\n    </div>\n  );\n}\n\n/** Under 16rem the two tiles stack, each a row with its label beside the figure, so no label is cut. */\nconst AVERAGE_TILE = [\n  'bg-foreground/[0.04] flex min-w-0 items-baseline justify-between gap-3 rounded-lg px-3 py-2.5',\n  '@3xs:flex-col @3xs:items-stretch @3xs:justify-start @3xs:gap-0.5',\n].join(' ');\n\nfunction AverageTile({ label, value }: { label: string; value: number }) {\n  return (\n    <div className={AVERAGE_TILE}>\n      <dt className='text-muted-foreground truncate text-xs'>{label}</dt>\n      <dd className='text-lg leading-6 font-semibold'>\n        <MotionNumber value={value} />\n      </dd>\n    </div>\n  );\n}\n\nexport type RangeSummaryProps = {\n  title: string;\n  /** Where the scale starts. It ends where the last band does. */\n  scaleStart?: number;\n  bands: RangeBand[];\n  periods: RangePeriod[];\n  periodId: string;\n  onPeriodChange: (periodId: string) => void;\n  /** Says the readings are made up. Leave it out for real ones. */\n  note?: string;\n  className?: string;\n};\n\nexport function RangeSummary({\n  title,\n  scaleStart = 0,\n  bands,\n  periods,\n  periodId,\n  onPeriodChange,\n  note,\n  className,\n}: RangeSummaryProps) {\n  const titleId = useId();\n  const period = periods.find((candidate) => candidate.id === periodId);\n\n  if (!period) {\n    return null;\n  }\n\n  const spans = spansOf(bands, scaleStart);\n  const scaleEnd = scaleEndOf(spans, scaleStart);\n  const activeSpan = bandOf(period.today, spans);\n  const share = shareOf(period.today, scaleStart, scaleEnd);\n  const bandLabel = activeSpan?.band.label ?? '';\n  const comparison = comparisonOf(period.today, period.weeklyAverage);\n  const segments: Segment<string>[] = periods.map((candidate) => ({\n    value: candidate.id,\n    label: candidate.label,\n  }));\n\n  return (\n    <Card\n      role='group'\n      aria-labelledby={titleId}\n      className={cn('@container w-full gap-4 p-5', className)}\n    >\n      <div className='flex items-baseline justify-between gap-3'>\n        <h3 id={titleId} className='text-sm font-medium'>\n          {title}\n        </h3>\n        {note && <SampleNote>{note}</SampleNote>}\n      </div>\n      <Segments\n        value={period.id}\n        segments={segments}\n        onValueChange={onPeriodChange}\n        label='Period'\n        className='w-full'\n        itemClassName='@max-3xs:px-1.5'\n      />\n      <div className='flex flex-col gap-1'>\n        <p className='flex flex-wrap items-baseline gap-x-2'>\n          <MotionNumber\n            value={period.today}\n            className='text-[28px] leading-8 font-semibold'\n          />\n          <span className='text-muted-foreground flex items-baseline gap-1 text-[13px]'>\n            today, in the\n            <WordRoll\n              text={bandLabel}\n              className='text-foreground font-medium'\n            />\n            band\n          </span>\n        </p>\n        <WordRoll text={comparison} className='text-muted-foreground text-xs' />\n      </div>\n      <RangeTrack\n        spans={spans}\n        activeBandId={activeSpan?.band.id}\n        share={share}\n      />\n      <dl className='grid grid-cols-1 gap-2 @3xs:grid-cols-2'>\n        <AverageTile label='Weekly average' value={period.weeklyAverage} />\n        <AverageTile label='Monthly average' value={period.monthlyAverage} />\n      </dl>\n    </Card>\n  );\n}\n\nconst BANDS: RangeBand[] = [\n  { id: 'low', label: 'Low', upTo: 40 },\n  { id: 'steady', label: 'Steady', upTo: 70 },\n  { id: 'high', label: 'High', upTo: 100 },\n];\n\nconst PERIODS: RangePeriod[] = [\n  {\n    id: 'morning',\n    label: 'Morning',\n    today: 82,\n    weeklyAverage: 74,\n    monthlyAverage: 71,\n  },\n  {\n    id: 'afternoon',\n    label: 'Afternoon',\n    today: 54,\n    weeklyAverage: 61,\n    monthlyAverage: 63,\n  },\n  {\n    id: 'evening',\n    label: 'Evening',\n    today: 67,\n    weeklyAverage: 58,\n    monthlyAverage: 60,\n  },\n];\n\nconst FIRST_PERIOD_ID = 'morning';\n\nfunction announcementOf(periodId: string) {\n  const period = PERIODS.find((candidate) => candidate.id === periodId);\n  if (!period) {\n    return '';\n  }\n  const comparison = comparisonOf(period.today, period.weeklyAverage);\n  return `${period.label}: energy ${period.today} today, ${comparison}, monthly average ${period.monthlyAverage}`;\n}\n\nexport default function Card14() {\n  const [periodId, setPeriodId] = useState(FIRST_PERIOD_ID);\n\n  const steps: AutoplayStep[] = [\n    { after: 2400, run: () => setPeriodId('afternoon') },\n    { after: 2600, run: () => setPeriodId('evening') },\n    { after: 2600, run: () => setPeriodId(FIRST_PERIOD_ID) },\n  ];\n  const { ref, isAutoplaying } = useCardDemo(steps, {\n    loopAfter: 400,\n  });\n\n  return (\n    <div ref={ref} className='min-h-[20rem] w-full max-w-[22rem]'>\n      <RangeSummary\n        title='Energy'\n        bands={BANDS}\n        periods={PERIODS}\n        periodId={periodId}\n        onPeriodChange={setPeriodId}\n        note='Illustrative'\n      />\n      <LiveRegion\n        message={spokenUnless(isAutoplaying, announcementOf(periodId))}\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/card-14.tsx"
    },
    {
      "path": "registry/ndeko/components/card/_parts/sample-note.tsx",
      "content": "import { cn } from '@/registry/ndeko/lib/utils';\n\ntype SampleNoteProps = {\n  /** What the sample is: \"Illustrative\", \"Sample quote\". */\n  children?: React.ReactNode;\n  className?: string;\n};\n\n/** The word that says the figures or the words of a demo are made up. */\nexport function SampleNote({\n  children = 'Illustrative',\n  className,\n}: SampleNoteProps) {\n  return (\n    <span className={cn('text-muted-foreground text-xs', className)}>\n      {children}\n    </span>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/_parts/sample-note.tsx"
    },
    {
      "path": "registry/ndeko/components/card/_parts/use-card-demo.ts",
      "content": "'use client';\n\nimport {\n  useAutoplay,\n  type AutoplayOptions,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\n\n/**\n * What every card demo shares: the demonstration, and the box that keeps its tallest height so a\n * round never moves the page.\n */\nexport function useCardDemo(\n  steps: readonly AutoplayStep[],\n  options?: AutoplayOptions\n) {\n  const demo = useAutoplay(steps, options);\n  const { ref } = demo;\n\n  useKeptHeight(ref);\n\n  return demo;\n}\n",
      "type": "registry:component",
      "target": "components/card/_parts/use-card-demo.ts"
    }
  ],
  "categories": [
    "components",
    "card"
  ],
  "type": "registry:component"
}