{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "card-03",
  "title": "Revenue card",
  "description": "Monthly revenue with its share of the goal, the trend against the month before in words and a hatched bar by channel, where the line draws itself as the figures land.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/card.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/hatch.json",
    "https://ui.ndekocode.dev/r/icons.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-03.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 { seriesColorOf, type SeriesSlot } from '@/registry/ndeko/lib/agent-run';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { hatchOf } from '@/registry/ndeko/lib/hatch';\nimport { TrendingDownIcon, TrendingUpIcon } from '@/registry/ndeko/lib/icons';\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 RevenueChannel = {\n  id: string;\n  name: string;\n  amount: number;\n  /** The colour the channel keeps from one month to the next. */\n  series: SeriesSlot;\n};\n\nexport type RevenueMonth = {\n  id: string;\n  /** The full name for sentences, and the short one for the switch: \"November\", \"Nov\". */\n  name: string;\n  shortName: string;\n  daysInMonth: number;\n  /** Revenue to date at the end of each day so far, one value per day, each at least the one before. */\n  toDate: number[];\n  goal: number;\n  /** What the month before had made after the same number of days, and its name. */\n  previousToDate: number;\n  previousName: string;\n  channels: RevenueChannel[];\n};\n\nconst LOCALE = 'en-US';\n\nconst CHART_WIDTH = 100;\n\nconst CHART_HEIGHT = 40;\n\n/** Room above the highest point, so the line and its end dot are never cut by the frame. */\nconst HEADROOM = 1.14;\n\nconst DRAWN =\n  'transition-transform duration-1000 ease-(--ease-out-strong) starting:-translate-x-full';\n\nconst DRAWN_CONTENT =\n  'transition-transform duration-1000 ease-(--ease-out-strong) starting:translate-x-full';\n\nconst FADED_IN = 'transition-opacity duration-300 starting:opacity-0';\n\n/** The plot stops short of the right edge, so the dot of a full month is not cut in half. */\nconst PLOT = 'absolute inset-y-0 start-0 end-1.5';\n\nfunction moneyFormatOf(currency: string): Intl.NumberFormatOptions {\n  return { style: 'currency', currency, maximumFractionDigits: 0 };\n}\n\nfunction revenueOf(month: RevenueMonth) {\n  const lastDay = month.toDate.length - 1;\n  return month.toDate[lastDay] ?? 0;\n}\n\nfunction topOf(month: RevenueMonth) {\n  const revenue = revenueOf(month);\n  const highest = Math.max(month.goal, revenue, 1);\n  return highest * HEADROOM;\n}\n\nfunction xOf(day: number, daysInMonth: number) {\n  const days = Math.max(daysInMonth, 1);\n  const share = day / days;\n  return share * CHART_WIDTH;\n}\n\nfunction yOf(value: number, top: number) {\n  const share = value / top;\n  const rise = share * CHART_HEIGHT;\n  return CHART_HEIGHT - rise;\n}\n\nfunction pointsOf(month: RevenueMonth) {\n  const top = topOf(month);\n  return month.toDate.map((value, index) => {\n    const day = index + 1;\n    const x = xOf(day, month.daysInMonth);\n    const y = yOf(value, top);\n    return `${x.toFixed(2)} ${y.toFixed(2)}`;\n  });\n}\n\nfunction linePathOf(points: string[]) {\n  const start = `M0 ${CHART_HEIGHT}`;\n  if (points.length === 0) {\n    return start;\n  }\n  const segments = points.join(' L');\n  return `${start} L${segments}`;\n}\n\nfunction areaPathOf(month: RevenueMonth, linePath: string) {\n  const lastX = xOf(month.toDate.length, month.daysInMonth);\n  return `${linePath} L${lastX.toFixed(2)} ${CHART_HEIGHT} Z`;\n}\n\nfunction percentOf(value: number, whole: number) {\n  if (whole <= 0) {\n    return 0;\n  }\n  const share = value / whole;\n  const percent = share * 100;\n  return Math.round(percent);\n}\n\nfunction isClosed(month: RevenueMonth) {\n  return month.toDate.length >= month.daysInMonth;\n}\n\nfunction captionOf(month: RevenueMonth) {\n  if (isClosed(month)) {\n    return `${month.name}, closed`;\n  }\n  return `${month.name} to date, day ${month.toDate.length} of ${month.daysInMonth}`;\n}\n\nfunction momentOf(month: RevenueMonth) {\n  if (isClosed(month)) {\n    return 'at the close';\n  }\n  return `after ${month.toDate.length} days`;\n}\n\n/** The comparison and the moment it is taken at stay apart, so a narrow card puts the moment on a second line. */\ntype Trend = { isBehind: boolean; comparison: string; moment: string };\n\nfunction trendOf(month: RevenueMonth): Trend {\n  const revenue = revenueOf(month);\n  const previous = month.previousToDate;\n  if (previous <= 0) {\n    const comparison = `Nothing to compare in ${month.previousName}`;\n    return { isBehind: false, comparison, moment: '' };\n  }\n  const difference = revenue - previous;\n  const gap = Math.abs(difference);\n  const percent = percentOf(gap, previous);\n  const moment = momentOf(month);\n  if (difference < 0) {\n    const comparison = `${percent}% behind ${month.previousName}`;\n    return { isBehind: true, comparison, moment };\n  }\n  const comparison = `${percent}% ahead of ${month.previousName}`;\n  return { isBehind: false, comparison, moment };\n}\n\nfunction sentenceOf(trend: Trend) {\n  if (trend.moment === '') {\n    return trend.comparison;\n  }\n  return `${trend.comparison} ${trend.moment}`;\n}\n\n/** The filled part of a bar slides in from the left, so its round end keeps its shape. */\nfunction fillShiftOf(percent: number) {\n  const filled = Math.min(percent, 100);\n  const hidden = 100 - filled;\n  return `translateX(-${hidden}%)`;\n}\n\nfunction drawnIf(isRedrawn: boolean, classes: string) {\n  if (isRedrawn) {\n    return classes;\n  }\n  return undefined;\n}\n\ntype MonthLineProps = {\n  month: RevenueMonth;\n  label: string;\n  /** False on the first render: the line is there. True after a change of month: it draws itself. */\n  isRedrawn: boolean;\n};\n\nfunction MonthLine({ month, label, isRedrawn }: MonthLineProps) {\n  const top = topOf(month);\n  const revenue = revenueOf(month);\n  const points = pointsOf(month);\n  const linePath = linePathOf(points);\n  const areaPath = areaPathOf(month, linePath);\n  const endX = xOf(month.toDate.length, month.daysInMonth);\n  const endY = yOf(revenue, top);\n  const goalY = yOf(month.goal, top);\n  const endLeft = percentOf(endX, CHART_WIDTH);\n  const endTop = percentOf(endY, CHART_HEIGHT);\n  const goalTop = percentOf(goalY, CHART_HEIGHT);\n  const endStyle = { left: `${endLeft}%`, top: `${endTop}%` };\n  const goalStyle = { top: `${goalTop}%` };\n  const halfMonth = month.daysInMonth / 2;\n  const middleDay = Math.round(halfMonth);\n\n  return (\n    <div>\n      <div className='relative h-24 overflow-x-clip'>\n        <div\n          aria-hidden='true'\n          style={goalStyle}\n          className='bg-foreground/15 absolute inset-x-0 h-px'\n        />\n        <span\n          aria-hidden='true'\n          style={goalStyle}\n          className='text-muted-foreground absolute start-0 -translate-y-full pb-0.5 text-xs'\n        >\n          Goal\n        </span>\n        <div\n          key={month.id}\n          className={cn(\n            'absolute inset-0 overflow-hidden',\n            drawnIf(isRedrawn, DRAWN)\n          )}\n        >\n          <div\n            className={cn(\n              'absolute inset-0',\n              drawnIf(isRedrawn, DRAWN_CONTENT)\n            )}\n          >\n            <div className={PLOT}>\n              <svg\n                role='img'\n                aria-label={label}\n                viewBox={`0 0 ${CHART_WIDTH} ${CHART_HEIGHT}`}\n                preserveAspectRatio='none'\n                className='size-full'\n              >\n                <path d={areaPath} className='fill-primary/10' />\n                <path\n                  d={linePath}\n                  fill='none'\n                  strokeWidth={1.75}\n                  strokeLinejoin='round'\n                  strokeLinecap='round'\n                  vectorEffect='non-scaling-stroke'\n                  className='stroke-primary'\n                />\n              </svg>\n              <span\n                aria-hidden='true'\n                style={endStyle}\n                className='bg-primary ring-card absolute size-2 -translate-x-1/2 -translate-y-1/2 rounded-full ring-2'\n              />\n            </div>\n          </div>\n        </div>\n      </div>\n      <div\n        aria-hidden='true'\n        className='text-muted-foreground mt-1.5 flex justify-between text-xs tabular-nums'\n      >\n        <span>1</span>\n        <span>{middleDay}</span>\n        <span>{month.daysInMonth}</span>\n      </div>\n    </div>\n  );\n}\n\nfunction channelTotalOf(channels: RevenueChannel[]) {\n  let total = 0;\n  for (const channel of channels) {\n    total += channel.amount;\n  }\n  return total;\n}\n\nfunction ChannelBar({ channels }: { channels: RevenueChannel[] }) {\n  const total = channelTotalOf(channels);\n\n  return (\n    <div className='flex flex-col gap-2'>\n      <div\n        aria-hidden='true'\n        className='flex h-2.5 gap-0.5 overflow-hidden rounded-full'\n      >\n        {channels.map((channel) => {\n          const color = seriesColorOf(channel.series);\n          const segmentStyle = {\n            flexGrow: channel.amount,\n            backgroundColor: `color-mix(in oklab, ${color} 16%, transparent)`,\n            backgroundImage: hatchOf(color, 70),\n          };\n          return (\n            <span key={channel.id} style={segmentStyle} className='basis-0' />\n          );\n        })}\n      </div>\n      <ul className='flex flex-wrap gap-x-4 gap-y-1'>\n        {channels.map((channel) => {\n          const dotStyle = { backgroundColor: seriesColorOf(channel.series) };\n          return (\n            <li key={channel.id} className='flex items-center gap-1.5 text-xs'>\n              <span\n                aria-hidden='true'\n                style={dotStyle}\n                className='size-2 rounded-full'\n              />\n              {channel.name}\n              <span className='text-muted-foreground tabular-nums'>\n                {percentOf(channel.amount, total)}%\n              </span>\n            </li>\n          );\n        })}\n      </ul>\n    </div>\n  );\n}\n\nfunction TrendMark({ isBehind }: { isBehind: boolean }) {\n  if (isBehind) {\n    return (\n      <TrendingDownIcon className='text-warning-foreground size-4 shrink-0' />\n    );\n  }\n  return <TrendingUpIcon className='text-success-foreground size-4 shrink-0' />;\n}\n\nexport type RevenueCardProps = {\n  months: RevenueMonth[];\n  monthId: string;\n  onMonthChange: (monthId: string) => void;\n  currency?: string;\n  /** Says the figures are made up. Leave it out for real figures. */\n  note?: string;\n  className?: string;\n};\n\nexport function RevenueCard({\n  months,\n  monthId,\n  onMonthChange,\n  currency = 'USD',\n  note,\n  className,\n}: RevenueCardProps) {\n  const titleId = useId();\n  const [firstMonthId] = useState(monthId);\n  const [hasSwitched, setHasSwitched] = useState(false);\n  const hasOtherMonth = monthId !== firstMonthId;\n  const isFirstSwitch = hasOtherMonth && !hasSwitched;\n  if (isFirstSwitch) {\n    setHasSwitched(true);\n  }\n  const isRedrawn = hasSwitched || isFirstSwitch;\n  const month = months.find((candidate) => candidate.id === monthId);\n\n  if (!month) {\n    return null;\n  }\n\n  const moneyFormat = moneyFormatOf(currency);\n  const money = new Intl.NumberFormat(LOCALE, moneyFormat);\n  const revenue = revenueOf(month);\n  const goalPercent = percentOf(revenue, month.goal);\n  const goalStyle = { transform: fillShiftOf(goalPercent) };\n  const trend = trendOf(month);\n  const hasMoment = trend.moment !== '';\n  const caption = captionOf(month);\n  const revenueText = money.format(revenue);\n  const goalText = money.format(month.goal);\n  const chartLabel = `${caption}: ${revenueText}`;\n  const segments: Segment<string>[] = months.map((candidate) => ({\n    value: candidate.id,\n    label: candidate.shortName,\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 flex-wrap items-center justify-between gap-x-3 gap-y-2'>\n        <div className='flex min-w-0 items-baseline gap-2'>\n          <h3 id={titleId} className='text-sm font-medium'>\n            Revenue\n          </h3>\n          {note && <SampleNote className='truncate'>{note}</SampleNote>}\n        </div>\n        <Segments\n          value={month.id}\n          segments={segments}\n          onValueChange={onMonthChange}\n          label='Month'\n          className='@max-2xs:w-full'\n        />\n      </div>\n      <div className='flex flex-col gap-1'>\n        <MotionNumber\n          value={revenue}\n          locale={LOCALE}\n          format={moneyFormat}\n          className='text-[28px] leading-8 font-semibold'\n        />\n        <p className='text-muted-foreground truncate text-xs tabular-nums'>\n          {caption}\n        </p>\n        <p className='flex min-w-0 items-center gap-1.5 text-[13px]'>\n          <TrendMark isBehind={trend.isBehind} />\n          <span className='flex min-w-0 flex-wrap items-baseline gap-x-1'>\n            <WordRoll text={trend.comparison} />\n            {hasMoment && (\n              <WordRoll text={trend.moment} className='@max-3xs:basis-full' />\n            )}\n          </span>\n        </p>\n      </div>\n      <MonthLine month={month} label={chartLabel} isRedrawn={isRedrawn} />\n      <div className='flex flex-col gap-1.5'>\n        <p className='text-xs tabular-nums'>\n          <MotionNumber value={goalPercent} locale={LOCALE} suffix='%' />\n          <span className='text-muted-foreground'> of the {goalText} goal</span>\n        </p>\n        <div\n          aria-hidden='true'\n          className='bg-foreground/[0.06] h-1.5 overflow-hidden rounded-full'\n        >\n          <div\n            style={goalStyle}\n            className='bg-primary h-full rounded-full transition-transform duration-500 ease-(--ease-out-strong)'\n          />\n        </div>\n      </div>\n      <div key={month.id} className={drawnIf(isRedrawn, FADED_IN)}>\n        <ChannelBar channels={month.channels} />\n      </div>\n    </Card>\n  );\n}\n\nfunction runningTotalOf(amounts: number[]) {\n  const totals: number[] = [];\n  let total = 0;\n  for (const amount of amounts) {\n    total += amount;\n    totals.push(total);\n  }\n  return totals;\n}\n\nconst SEPTEMBER_DAYS = [\n  4200, 4600, 4400, 3500, 1000, 600, 3900, 4800, 4500, 4700, 3600, 1100, 700,\n  4400, 5000, 4600, 4800, 3700, 900, 800, 4500, 5100, 4700, 4900, 3900, 1200,\n  700, 4600, 5200, 4800,\n];\n\nconst OCTOBER_DAYS = [\n  4400, 3900, 1100, 700, 4800, 5300, 4500, 5000, 3700, 1300, 900, 4600, 5400,\n  4900, 5200, 4100, 1000, 800, 5100, 5600, 4700, 5300, 3800, 1200, 900, 4900,\n  5500, 5000, 5400, 4200, 1400,\n];\n\nconst NOVEMBER_DAYS = [\n  900, 4600, 5200, 4800, 5600, 4300, 1200, 800, 5100, 5900, 4700, 5150,\n];\n\nconst MONTHS: RevenueMonth[] = [\n  {\n    id: 'september',\n    name: 'September',\n    shortName: 'Sep',\n    daysInMonth: 30,\n    toDate: runningTotalOf(SEPTEMBER_DAYS),\n    goal: 100000,\n    previousToDate: 108900,\n    previousName: 'August',\n    channels: [\n      { id: 'direct', name: 'Direct', amount: 47400, series: 1 },\n      { id: 'partners', name: 'Partners', amount: 33700, series: 2 },\n      { id: 'marketplace', name: 'Marketplace', amount: 24300, series: 3 },\n    ],\n  },\n  {\n    id: 'october',\n    name: 'October',\n    shortName: 'Oct',\n    daysInMonth: 31,\n    toDate: runningTotalOf(OCTOBER_DAYS),\n    goal: 120000,\n    previousToDate: 105400,\n    previousName: 'September',\n    channels: [\n      { id: 'direct', name: 'Direct', amount: 49300, series: 1 },\n      { id: 'partners', name: 'Partners', amount: 37800, series: 2 },\n      { id: 'marketplace', name: 'Marketplace', amount: 27500, series: 3 },\n    ],\n  },\n  {\n    id: 'november',\n    name: 'November',\n    shortName: 'Nov',\n    daysInMonth: 30,\n    toDate: runningTotalOf(NOVEMBER_DAYS),\n    goal: 125000,\n    previousToDate: 40200,\n    previousName: 'October',\n    channels: [\n      { id: 'direct', name: 'Direct', amount: 21700, series: 1 },\n      { id: 'partners', name: 'Partners', amount: 14450, series: 2 },\n      { id: 'marketplace', name: 'Marketplace', amount: 12100, series: 3 },\n    ],\n  },\n];\n\nconst CURRENT_MONTH_ID = 'november';\n\nconst DEMO_MONEY = new Intl.NumberFormat(LOCALE, moneyFormatOf('USD'));\n\nfunction announcementOf(monthId: string) {\n  const month = MONTHS.find((candidate) => candidate.id === monthId);\n  if (!month) {\n    return '';\n  }\n  const revenue = revenueOf(month);\n  const revenueText = DEMO_MONEY.format(revenue);\n  const caption = captionOf(month);\n  const trend = trendOf(month);\n  const sentence = sentenceOf(trend);\n  return `${caption}: ${revenueText}, ${sentence}`;\n}\n\nexport default function Card03() {\n  const [monthId, setMonthId] = useState(CURRENT_MONTH_ID);\n\n  const steps: AutoplayStep[] = [\n    { after: 2400, run: () => setMonthId('october') },\n    { after: 2800, run: () => setMonthId('september') },\n    { after: 2800, run: () => setMonthId(CURRENT_MONTH_ID) },\n  ];\n  const { ref, isAutoplaying } = useCardDemo(steps, {\n    loopAfter: 600,\n  });\n\n  return (\n    <div ref={ref} className='min-h-[24rem] w-full max-w-[24rem]'>\n      <RevenueCard\n        months={MONTHS}\n        monthId={monthId}\n        onMonthChange={setMonthId}\n        note='Illustrative'\n      />\n      <LiveRegion\n        message={spokenUnless(isAutoplaying, announcementOf(monthId))}\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/card-03.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"
}