{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "application-16",
  "title": "Marketing dashboard",
  "description": "A Tarnbrook marketing dashboard whose sidebar and cards settle in once, then one period switch moves every chart together: leads split by origin, goals as tick meters, daily traffic against the period before dashed, clicks by channel and month, a conversion funnel, the week's campaigns on a strip and a table of campaigns grouped by channel that sorts by column. Plug your analytics into onPeriodChange, onSortChange and onCampaignSelect.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/avatar.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/company-mark.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/inline-sheet.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/run-session.json",
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/settle.json",
    "https://ui.ndekocode.dev/r/table.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-is-narrow.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/templates/dashboards/application-16/index.tsx",
      "content": "'use client';\n\nimport { useRef, useState } from 'react';\n\nimport { useIsNarrow } from '@/registry/ndeko/hooks/use-is-narrow';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { InlineSheet } from '@/registry/ndeko/ui/inline-sheet';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { Settle, SettleItem } from '@/registry/ndeko/ui/settle';\n\nimport { AppSidebar } from './app-sidebar';\nimport type { SortKey } from './campaign-sort';\nimport { CampaignTable } from './campaign-table';\nimport { ChannelBars } from './channel-bars';\nimport { ConversionFunnel } from './conversion-funnel';\nimport type { PeriodId, SectionId } from './data';\nimport { GoalMeters } from './goal-meters';\nimport { LeadSplit } from './lead-split';\nimport { PageHeader } from './page-header';\nimport { dataOf } from './period-data';\nimport { INITIAL, LOOP_AFTER_MS, reducer, RESTING, SCRIPT } from './session';\nimport { TrafficLine } from './traffic-line';\nimport { WeekStrip } from './week-strip';\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n};\n\n/** The width of the `@3xl` container variant: under it the sections live in a sheet. */\nconst SHEET_BELOW_REM = 48;\n\nconst SCROLL_MARGIN_PX = 16;\n\nfunction scrollBehaviorOf(shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return 'auto';\n  }\n  return 'smooth';\n}\n\n/** Nothing calls a network. A real analytics source plugs in here: the period a person picks, and the campaign they open. */\nexport type Application16Props = {\n  onPeriodChange?: (period: PeriodId) => void;\n  onSortChange?: (key: SortKey) => void;\n  onCampaignSelect?: (id: string | null) => void;\n};\n\nexport default function Application16({\n  onPeriodChange,\n  onSortChange,\n  onCampaignSelect,\n}: Application16Props) {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const scrollerRef = useRef<HTMLDivElement>(null);\n  const [activeId, setActiveId] = useState<SectionId>('overview');\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const isNarrow = useIsNarrow(ref, SHEET_BELOW_REM);\n  const isSheetShown = isNarrow && state.isSidebarOpen;\n  const canReplay = isFinished && !isAutoplaying;\n  const message = spokenUnless(isAutoplaying, state.spoken);\n  const data = dataOf(state.period);\n\n  function focusLater(selector: string) {\n    requestAnimationFrame(() => {\n      const target = ref.current?.querySelector<HTMLElement>(selector);\n      target?.focus();\n    });\n  }\n\n  function scrollToSection(id: SectionId) {\n    const scroller = scrollerRef.current;\n    if (!scroller) {\n      return;\n    }\n    const behavior = scrollBehaviorOf(shouldReduceMotion);\n    const target = ref.current?.querySelector<HTMLElement>(\n      `[data-section=\"${id}\"]`\n    );\n    if (!target) {\n      scroller.scrollTo({ top: 0, behavior });\n      return;\n    }\n    const scrollerTop = scroller.getBoundingClientRect().top;\n    const targetTop = target.getBoundingClientRect().top;\n    const offset = targetTop - scrollerTop + scroller.scrollTop;\n    const top = Math.max(offset - SCROLL_MARGIN_PX, 0);\n    scroller.scrollTo({ top, behavior });\n  }\n\n  function navigate(id: SectionId) {\n    setActiveId(id);\n    scrollToSection(id);\n    if (isSheetShown) {\n      closeSidebar();\n    }\n  }\n\n  function openSidebar() {\n    act({ type: 'sidebar', isOpen: true });\n    focusLater('[data-sheet-close=\"sections\"]');\n  }\n\n  function closeSidebar() {\n    act({ type: 'sidebar', isOpen: false });\n    focusLater('[data-menu-open]');\n  }\n\n  function changePeriod(period: PeriodId) {\n    act({ type: 'periodSet', period });\n    onPeriodChange?.(period);\n  }\n\n  function sortBy(key: SortKey) {\n    act({ type: 'sorted', key });\n    onSortChange?.(key);\n  }\n\n  function selectCampaign(id: string) {\n    if (state.campaignId === id) {\n      act({ type: 'campaignSelected', id: null });\n      onCampaignSelect?.(null);\n      return;\n    }\n    act({ type: 'campaignSelected', id });\n    onCampaignSelect?.(id);\n  }\n\n  return (\n    <ClockGate isActive={isInView}>\n      <div\n        ref={ref}\n        className='bg-sidebar text-foreground @container min-h-dvh w-full'\n      >\n        <div className='relative flex h-dvh min-h-[40rem] overflow-hidden'>\n          <div inert={isSheetShown} className='flex min-w-0 flex-1 @3xl:p-2'>\n            <aside\n              aria-label='Sections'\n              className='hidden w-56 shrink-0 pe-2 @3xl:flex'\n            >\n              {!isNarrow && (\n                <AppSidebar\n                  activeId={activeId}\n                  isShown={isInView}\n                  onNavigate={navigate}\n                />\n              )}\n            </aside>\n            <main className='bg-background @3xl:hairline-ring @3xl:ring-border flex min-w-0 flex-1 flex-col overflow-hidden @3xl:rounded-xl @3xl:shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n              <PageHeader\n                period={state.period}\n                canReplay={canReplay}\n                onPeriodChange={changePeriod}\n                onReplay={restart}\n                onOpenMenu={openSidebar}\n              />\n              <div\n                ref={scrollerRef}\n                className='@container/page min-h-0 flex-1 overflow-y-auto'\n              >\n                <Settle\n                  isShown={isInView}\n                  className='mx-auto flex w-full max-w-6xl flex-col gap-4 px-3 pt-1 pb-6'\n                >\n                  <div className='grid gap-4 @3xl/page:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]'>\n                    <SettleItem className='min-w-0'>\n                      <LeadSplit data={data} />\n                    </SettleItem>\n                    <SettleItem className='min-w-0'>\n                      <GoalMeters data={data} />\n                    </SettleItem>\n                  </div>\n                  <SettleItem>\n                    <TrafficLine data={data} />\n                  </SettleItem>\n                  <div className='grid gap-4 @3xl/page:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]'>\n                    <SettleItem className='min-w-0'>\n                      <ChannelBars data={data} />\n                    </SettleItem>\n                    <SettleItem className='min-w-0'>\n                      <ConversionFunnel data={data} />\n                    </SettleItem>\n                  </div>\n                  <SettleItem>\n                    <WeekStrip\n                      selectedId={state.campaignId}\n                      pressed={pressed}\n                      onSelect={selectCampaign}\n                    />\n                  </SettleItem>\n                  <SettleItem>\n                    <CampaignTable\n                      data={data}\n                      sortKey={state.sortKey}\n                      sortDirection={state.sortDirection}\n                      selectedId={state.campaignId}\n                      pressed={pressed}\n                      onSort={sortBy}\n                      onSelect={selectCampaign}\n                    />\n                  </SettleItem>\n                </Settle>\n              </div>\n            </main>\n          </div>\n\n          <InlineSheet\n            name='sections'\n            label='Sections of the dashboard'\n            closeLabel='Close the sections'\n            side='start'\n            isOpen={isSheetShown}\n            className='@3xl:hidden'\n            panelClassName='bg-sidebar gap-1 p-3'\n            onClose={closeSidebar}\n          >\n            {isNarrow && (\n              <AppSidebar\n                activeId={activeId}\n                isShown={isInView}\n                onNavigate={navigate}\n              />\n            )}\n          </InlineSheet>\n          <LiveRegion message={message} />\n        </div>\n      </div>\n    </ClockGate>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/index.tsx"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/app-sidebar.tsx",
      "content": "'use client';\n\nimport { motion } from 'motion/react';\nimport { useId } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { springOf } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Avatar } from '@/registry/ndeko/ui/avatar';\nimport { CompanyMark } from '@/registry/ndeko/ui/company-mark';\nimport { Settle, SettleItem } from '@/registry/ndeko/ui/settle';\n\nimport {\n  BRAND,\n  MARKETING_LEAD,\n  NAV_GROUPS,\n  type NavItem,\n  type SectionId,\n} from './data';\n\nconst NAV_ROW =\n  \"relative flex h-7 w-full min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 text-start text-[13px] font-medium outline-none transition-colors duration-150 hover:bg-foreground/5 focus-visible:ring-[3px] focus-visible:ring-ring/25 [&_svg]:pointer-events-none [&_svg]:relative [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground\";\n\nfunction currentOf(isActive: boolean) {\n  if (isActive) {\n    return 'location';\n  }\n  return undefined;\n}\n\nfunction ActiveIndicator({ layoutId }: { layoutId: string }) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n\n  return (\n    <motion.span\n      aria-hidden='true'\n      layoutId={layoutId}\n      transition={springOf(shouldReduceMotion)}\n      className='bg-foreground/[0.07] absolute inset-0 rounded-md'\n    />\n  );\n}\n\ntype NavRowProps = {\n  item: NavItem;\n  isActive: boolean;\n  indicatorId: string;\n  onNavigate: (id: SectionId) => void;\n};\n\nfunction NavRow({ item, isActive, indicatorId, onNavigate }: NavRowProps) {\n  const ItemIcon = item.icon;\n\n  function navigate() {\n    onNavigate(item.id);\n  }\n\n  return (\n    <li>\n      <button\n        type='button'\n        aria-current={currentOf(isActive)}\n        onClick={navigate}\n        className={NAV_ROW}\n      >\n        {isActive && <ActiveIndicator layoutId={indicatorId} />}\n        <ItemIcon />\n        <span className='relative min-w-0 flex-1 truncate'>{item.label}</span>\n      </button>\n    </li>\n  );\n}\n\ntype AppSidebarProps = {\n  activeId: SectionId;\n  isShown: boolean;\n  onNavigate: (id: SectionId) => void;\n  className?: string;\n};\n\nexport function AppSidebar({\n  activeId,\n  isShown,\n  onNavigate,\n  className,\n}: AppSidebarProps) {\n  const indicatorId = useId();\n\n  return (\n    <Settle\n      isShown={isShown}\n      className={cn('flex min-h-0 w-full flex-col gap-4', className)}\n    >\n      <SettleItem className='flex h-9 items-center gap-2 px-1.5'>\n        <CompanyMark seed={BRAND.name} className='size-6 rounded-md' />\n        <span className='text-[13px] font-semibold'>{BRAND.name}</span>\n      </SettleItem>\n      {NAV_GROUPS.map((group) => (\n        <SettleItem key={group.id} className='flex flex-col gap-0.5'>\n          <p className='text-muted-foreground flex h-6 items-center px-2 text-xs font-medium'>\n            {group.label}\n          </p>\n          <nav aria-label={group.label}>\n            <ul className='flex flex-col gap-px'>\n              {group.items.map((item) => (\n                <NavRow\n                  key={item.id}\n                  item={item}\n                  isActive={item.id === activeId}\n                  indicatorId={indicatorId}\n                  onNavigate={onNavigate}\n                />\n              ))}\n            </ul>\n          </nav>\n        </SettleItem>\n      ))}\n      <SettleItem className='mt-auto flex items-center gap-2 px-1.5 py-1'>\n        <Avatar className='size-7' seed={MARKETING_LEAD.name} />\n        <div className='flex min-w-0 flex-col leading-tight'>\n          <span className='truncate text-[13px] font-medium'>\n            {MARKETING_LEAD.name}\n          </span>\n          <span className='text-muted-foreground truncate text-xs'>\n            {MARKETING_LEAD.role}\n          </span>\n        </div>\n      </SettleItem>\n    </Settle>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/app-sidebar.tsx"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/campaign-sort.ts",
      "content": "import type { Campaign } from './data';\nimport type { CampaignTotals } from './period-data';\n\nexport type SortKey = 'name' | 'spend' | 'clicks' | 'leads' | 'cost';\n\nexport type SortDirection = 'asc' | 'desc';\n\nexport type SortColumn = {\n  key: SortKey;\n  label: string;\n  isNumeric: boolean;\n};\n\nexport const SORT_COLUMNS: SortColumn[] = [\n  { key: 'name', label: 'Campaign', isNumeric: false },\n  { key: 'spend', label: 'Spend', isNumeric: true },\n  { key: 'clicks', label: 'Clicks', isNumeric: true },\n  { key: 'leads', label: 'Leads', isNumeric: true },\n  { key: 'cost', label: 'Cost per lead', isNumeric: true },\n];\n\n/** Names read from A to Z and a lower cost is better, so those two start ascending. The others start with the biggest. */\nexport function defaultDirectionOf(key: SortKey): SortDirection {\n  if (key === 'name' || key === 'cost') {\n    return 'asc';\n  }\n  return 'desc';\n}\n\nexport function columnOf(key: SortKey) {\n  const column = SORT_COLUMNS.find((candidate) => candidate.key === key);\n  return column ?? SORT_COLUMNS[0];\n}\n\nfunction numberOf(totals: CampaignTotals, key: SortKey) {\n  if (key === 'spend') {\n    return totals.spend;\n  }\n  if (key === 'clicks') {\n    return totals.clicks;\n  }\n  if (key === 'leads') {\n    return totals.leads;\n  }\n  return totals.costPerLead;\n}\n\nfunction directionFactorOf(direction: SortDirection) {\n  if (direction === 'asc') {\n    return 1;\n  }\n  return -1;\n}\n\n/** The campaigns of one channel in the order a column asks for. Equal values keep the order of their names. */\nexport function sortedCampaigns(\n  members: readonly Campaign[],\n  totals: Record<string, CampaignTotals>,\n  key: SortKey,\n  direction: SortDirection\n) {\n  const factor = directionFactorOf(direction);\n  return [...members].sort((first, second) => {\n    if (key === 'name') {\n      return first.name.localeCompare(second.name) * factor;\n    }\n    const gap =\n      numberOf(totals[first.id], key) - numberOf(totals[second.id], key);\n    if (gap !== 0) {\n      return gap * factor;\n    }\n    return first.name.localeCompare(second.name);\n  });\n}\n\nexport function sortSentenceOf(key: SortKey, direction: SortDirection) {\n  const column = columnOf(key);\n  const name = column.label.toLowerCase();\n  if (key === 'name') {\n    return `Sorted by ${name}, ${wordsOfDirection(direction, 'A to Z', 'Z to A')}`;\n  }\n  return `Sorted by ${name}, ${wordsOfDirection(direction, 'lowest first', 'highest first')}`;\n}\n\nfunction wordsOfDirection(\n  direction: SortDirection,\n  ascending: string,\n  descending: string\n) {\n  if (direction === 'asc') {\n    return ascending;\n  }\n  return descending;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/campaign-sort.ts"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/campaign-table.tsx",
      "content": "'use client';\n\nimport { LayoutGroup, motion } from 'motion/react';\nimport { Fragment, useId } from 'react';\n\nimport { seriesColorOf } from '@/registry/ndeko/lib/agent-run';\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { ArrowUpIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf } from '@/registry/ndeko/lib/words';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport {\n  Table,\n  TableBody,\n  TableCell,\n  TableHead,\n  TableHeader,\n  TableRow,\n} from '@/registry/ndeko/ui/table';\n\nimport {\n  SORT_COLUMNS,\n  sortedCampaigns,\n  sortSentenceOf,\n  type SortColumn,\n  type SortDirection,\n  type SortKey,\n} from './campaign-sort';\nimport { ChartCard } from './chart-card';\nimport {\n  CAMPAIGNS,\n  CHANNELS,\n  type Campaign,\n  type CampaignStatus,\n} from './data';\nimport { COUNT_FORMAT, MONEY_FORMAT, PRECISE_MONEY_FORMAT } from './format';\nimport type { CampaignTotals, PeriodData } from './period-data';\n\nconst MotionRow = motion.create(TableRow);\n\nconst STATUS_DOT: Record<CampaignStatus, string> = {\n  live: 'bg-success',\n  paused: 'bg-muted-foreground/45',\n};\n\nconst STATUS_WORD: Record<CampaignStatus, string> = {\n  live: 'Live',\n  paused: 'Paused',\n};\n\nconst MONEY = new Intl.NumberFormat('en-US', MONEY_FORMAT);\n\nconst COUNT = new Intl.NumberFormat('en-US', COUNT_FORMAT);\n\nconst PRECISE_MONEY = new Intl.NumberFormat('en-US', PRECISE_MONEY_FORMAT);\n\nfunction figuresOf(totals: CampaignTotals) {\n  return [\n    MONEY.format(totals.spend),\n    COUNT.format(totals.clicks),\n    COUNT.format(totals.leads),\n    PRECISE_MONEY.format(totals.costPerLead),\n  ];\n}\n\nfunction ariaSortOf(\n  column: SortColumn,\n  sortKey: SortKey,\n  direction: SortDirection\n) {\n  if (column.key !== sortKey) {\n    return 'none';\n  }\n  if (direction === 'asc') {\n    return 'ascending';\n  }\n  return 'descending';\n}\n\nfunction arrowClassOf(isActive: boolean, direction: SortDirection) {\n  if (!isActive) {\n    return 'opacity-0 group-hover/sort:opacity-40';\n  }\n  if (direction === 'desc') {\n    return 'rotate-180 opacity-100';\n  }\n  return 'opacity-100';\n}\n\nfunction stateOf(isSelected: boolean) {\n  if (isSelected) {\n    return 'selected';\n  }\n  return undefined;\n}\n\n/** A figure that changes is drawn again and fades in: the whole table changes with the period, and a row that travels keeps plain text. */\nfunction Figure({ text }: { text: string }) {\n  return (\n    <span\n      key={text}\n      className='inline-block tabular-nums transition-opacity duration-300 starting:opacity-0'\n    >\n      {text}\n    </span>\n  );\n}\n\ntype SortHeadProps = {\n  column: SortColumn;\n  sortKey: SortKey;\n  direction: SortDirection;\n  isPressed: boolean;\n  onSort: (key: SortKey) => void;\n};\n\nfunction SortHead({\n  column,\n  sortKey,\n  direction,\n  isPressed,\n  onSort,\n}: SortHeadProps) {\n  const isActive = column.key === sortKey;\n\n  function sort() {\n    onSort(column.key);\n  }\n\n  return (\n    <TableHead\n      aria-sort={ariaSortOf(column, sortKey, direction)}\n      className='p-0'\n    >\n      <button\n        type='button'\n        onClick={sort}\n        className={cn(\n          'group/sort focus-visible:ring-ring/25 hover:text-foreground flex h-10 w-full cursor-pointer items-center gap-1 px-3 outline-none focus-visible:ring-[3px] focus-visible:ring-inset',\n          column.isNumeric && 'justify-end',\n          isActive && 'text-foreground',\n          pressedQuietOf(isPressed)\n        )}\n      >\n        {column.label}\n        <ArrowUpIcon\n          aria-hidden='true'\n          className={cn(\n            'size-3 transition-[opacity,rotate] duration-150 ease-(--ease-out-strong)',\n            arrowClassOf(isActive, direction)\n          )}\n        />\n      </button>\n    </TableHead>\n  );\n}\n\ntype CampaignRowProps = {\n  campaign: Campaign;\n  totals: CampaignTotals;\n  orderKey: string;\n  isSelected: boolean;\n  onSelect: (id: string) => void;\n};\n\nfunction CampaignRow({\n  campaign,\n  totals,\n  orderKey,\n  isSelected,\n  onSelect,\n}: CampaignRowProps) {\n  const figures = figuresOf(totals);\n\n  function select() {\n    onSelect(campaign.id);\n  }\n\n  return (\n    <MotionRow\n      layout='position'\n      layoutDependency={orderKey}\n      data-state={stateOf(isSelected)}\n      onClick={select}\n      className='cursor-pointer'\n    >\n      <TableCell className='min-w-44'>\n        <button\n          type='button'\n          aria-pressed={isSelected}\n          className='focus-visible:ring-ring/25 flex max-w-full cursor-pointer items-center gap-2 rounded-md text-start text-[13px] font-medium outline-none focus-visible:ring-[3px]'\n        >\n          <span\n            aria-hidden='true'\n            className={cn(\n              'size-1.5 shrink-0 rounded-full',\n              STATUS_DOT[campaign.status]\n            )}\n          />\n          <span className='truncate'>{campaign.name}</span>\n          <span className='sr-only'>{STATUS_WORD[campaign.status]}</span>\n        </button>\n      </TableCell>\n      {figures.map((text, index) => (\n        <TableCell key={SORT_COLUMNS[index + 1].key} className='text-end'>\n          <Figure text={text} />\n        </TableCell>\n      ))}\n    </MotionRow>\n  );\n}\n\ntype CampaignTableProps = {\n  data: PeriodData;\n  sortKey: SortKey;\n  sortDirection: SortDirection;\n  selectedId: string | null;\n  pressed: string | null;\n  onSort: (key: SortKey) => void;\n  onSelect: (id: string) => void;\n};\n\nexport function CampaignTable({\n  data,\n  sortKey,\n  sortDirection,\n  selectedId,\n  pressed,\n  onSort,\n  onSelect,\n}: CampaignTableProps) {\n  const groupId = useId();\n  const sentence = sortSentenceOf(sortKey, sortDirection);\n\n  return (\n    <ChartCard\n      title='Campaigns'\n      section='campaigns'\n      description={\n        <Swap swapKey={sentence} className='text-muted-foreground text-xs'>\n          {sentence}\n        </Swap>\n      }\n    >\n      <LayoutGroup id={groupId}>\n        <div className='-mx-3'>\n          <Table className='min-w-[34rem]'>\n            <TableHeader>\n              <TableRow className='hover:bg-transparent'>\n                {SORT_COLUMNS.map((column) => (\n                  <SortHead\n                    key={column.key}\n                    column={column}\n                    sortKey={sortKey}\n                    direction={sortDirection}\n                    isPressed={pressed === `sort-${column.key}`}\n                    onSort={onSort}\n                  />\n                ))}\n              </TableRow>\n            </TableHeader>\n            <TableBody>\n              {CHANNELS.map((channel) => {\n                const members = CAMPAIGNS.filter(\n                  (campaign) => campaign.channel === channel.id\n                );\n                const rows = sortedCampaigns(\n                  members,\n                  data.campaigns,\n                  sortKey,\n                  sortDirection\n                );\n                const orderKey = rows.map((row) => row.id).join(',');\n                const subtotals = figuresOf(data.groups[channel.id]);\n                return (\n                  <Fragment key={channel.id}>\n                    <TableRow className='bg-foreground/[0.03] hover:bg-foreground/[0.03]'>\n                      <TableCell className='py-2'>\n                        <span className='flex items-center gap-2 text-xs font-medium'>\n                          <span\n                            aria-hidden='true'\n                            className='size-2 shrink-0 rounded-full'\n                            style={{\n                              backgroundColor: seriesColorOf(channel.series),\n                            }}\n                          />\n                          {channel.name}\n                          <span className='text-muted-foreground font-normal'>\n                            {countOf(members.length, 'campaign')}\n                          </span>\n                        </span>\n                      </TableCell>\n                      {subtotals.map((text, index) => (\n                        <TableCell\n                          key={SORT_COLUMNS[index + 1].key}\n                          className='text-muted-foreground py-2 text-end text-xs'\n                        >\n                          <Figure text={text} />\n                        </TableCell>\n                      ))}\n                    </TableRow>\n                    {rows.map((campaign) => (\n                      <CampaignRow\n                        key={campaign.id}\n                        campaign={campaign}\n                        totals={data.campaigns[campaign.id]}\n                        orderKey={orderKey}\n                        isSelected={campaign.id === selectedId}\n                        onSelect={onSelect}\n                      />\n                    ))}\n                  </Fragment>\n                );\n              })}\n            </TableBody>\n          </Table>\n        </div>\n      </LayoutGroup>\n    </ChartCard>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/campaign-table.tsx"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/channel-bars.tsx",
      "content": "'use client';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { seriesColorOf } from '@/registry/ndeko/lib/agent-run';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport { ChartCard } from './chart-card';\nimport { GRID_STEPS, niceScaleOf, shareOf } from './chart-math';\nimport { CHANNELS } from './data';\nimport { COMPACT_FORMAT, formatCount } from './format';\nimport { BAR_SLOTS, type PeriodData } from './period-data';\nimport { useReading } from './use-reading';\n\nconst PLOT_HEIGHT = 176;\n\nconst GROUP_SHARE = 0.72;\n\n/** A bar that is not in the period shrinks to the corner it grows out of when the period gets longer. */\nconst COLLAPSED = 'inset(100% 100% 0% 0% round 2px 2px 0 0)';\n\nconst GRID_STEP_LIST = Array.from(\n  { length: GRID_STEPS + 1 },\n  (_, step) => step\n);\n\nfunction gridTopOf(step: number) {\n  const share = step / GRID_STEPS;\n  return PLOT_HEIGHT - share * PLOT_HEIGHT;\n}\n\nfunction percentText(share: number) {\n  return `${(share * 100).toFixed(2)}%`;\n}\n\n/**\n * Every bar is a layer as big as the plot, clipped to its own rectangle: one property says where it\n * stands and how tall it is, so a bar glides to a new place and a new height in one movement, with\n * its corner radius intact.\n */\nfunction barInsetOf(\n  position: number,\n  channelIndex: number,\n  months: number,\n  value: number,\n  largest: number\n) {\n  const slotWidth = 1 / months;\n  const groupWidth = slotWidth * GROUP_SHARE;\n  const barWidth = groupWidth / CHANNELS.length;\n  const groupStart = position * slotWidth + (slotWidth - groupWidth) / 2;\n  const left = groupStart + channelIndex * barWidth;\n  const right = left + barWidth;\n  const top = 1 - shareOf(value, largest);\n  const rightEdge = `calc(${percentText(1 - right)} + 0.5px)`;\n  const leftEdge = `calc(${percentText(left)} + 0.5px)`;\n  return `inset(${percentText(top)} ${rightEdge} 0% ${leftEdge} round 2px 2px 0 0)`;\n}\n\nfunction clipOf(\n  isPresent: boolean,\n  position: number,\n  channelIndex: number,\n  months: number,\n  value: number,\n  largest: number\n) {\n  if (!isPresent) {\n    return COLLAPSED;\n  }\n  return barInsetOf(position, channelIndex, months, value, largest);\n}\n\ntype BarSpec = {\n  id: string;\n  slot: number;\n  color: string;\n  clip: string;\n};\n\nfunction barSpecsOf(data: PeriodData, largest: number) {\n  const firstPresent = BAR_SLOTS - data.months;\n  const specs: BarSpec[] = [];\n  data.bars.forEach((bar, slot) => {\n    const position = slot - firstPresent;\n    CHANNELS.forEach((channel, channelIndex) => {\n      const clip = clipOf(\n        bar.isPresent,\n        position,\n        channelIndex,\n        data.months,\n        bar.values[channelIndex],\n        largest\n      );\n      specs.push({\n        id: `${bar.label}-${channel.id}`,\n        slot,\n        color: seriesColorOf(channel.series),\n        clip,\n      });\n    });\n  });\n  return specs;\n}\n\nfunction dimmedClassOf(isDimmed: boolean) {\n  if (isDimmed) {\n    return 'opacity-30';\n  }\n  return 'opacity-100';\n}\n\nfunction labelLeftOf(position: number, months: number) {\n  const share = (position + 0.5) / months;\n  return percentText(share);\n}\n\nfunction isMinorLabel(position: number, months: number) {\n  const isCrowded = months === BAR_SLOTS;\n  const isOdd = position % 2 === 1;\n  return isCrowded && isOdd;\n}\n\nfunction readingCaptionOf(data: PeriodData, slot: number) {\n  const bar = data.bars[slot];\n  const parts = CHANNELS.map((channel, index) => {\n    return `${channel.name} ${formatCount(bar.values[index])}`;\n  });\n  return `${bar.label}: ${parts.join(', ')}`;\n}\n\ntype ChannelBarsProps = {\n  data: PeriodData;\n};\n\nexport function ChannelBars({ data }: ChannelBarsProps) {\n  const { months } = data;\n  const firstPresent = BAR_SLOTS - months;\n  const reading = useReading(months, 'column');\n  const scale = niceScaleOf(data.largestBar);\n  const readSlot = reading.shownIndex + firstPresent;\n  const caption = readingCaptionOf(data, readSlot);\n  const barSpecs = barSpecsOf(data, scale.max);\n  const presentBars = data.bars.filter((bar) => bar.isPresent);\n\n  return (\n    <ChartCard\n      title='Clicks by channel and month'\n      section='channels'\n      description={\n        <p className='text-muted-foreground text-xs'>Clicks per month</p>\n      }\n    >\n      <p className='text-muted-foreground min-h-5 text-xs'>{caption}</p>\n      <div className='grid grid-cols-[auto_minmax(0,1fr)] gap-x-2'>\n        <div\n          aria-hidden='true'\n          className='relative w-9 shrink-0'\n          style={{ height: PLOT_HEIGHT }}\n        >\n          {GRID_STEP_LIST.map((step) => (\n            <span\n              key={step}\n              className='text-muted-foreground absolute right-0 -translate-y-1/2 text-[11px]'\n              style={{ top: gridTopOf(step) }}\n            >\n              <MotionNumber value={scale.ticks[step]} format={COMPACT_FORMAT} />\n            </span>\n          ))}\n        </div>\n        <div\n          role='slider'\n          tabIndex={0}\n          aria-label='Clicks by channel and month. The arrow keys read each month'\n          aria-orientation='horizontal'\n          aria-valuemin={0}\n          aria-valuemax={months - 1}\n          aria-valuenow={reading.shownIndex}\n          aria-valuetext={caption}\n          className='focus-visible:ring-ring/25 relative touch-pan-y rounded-md outline-none focus-visible:ring-[3px]'\n          style={{ height: PLOT_HEIGHT }}\n          {...reading.handlers}\n        >\n          {GRID_STEP_LIST.map((step) => (\n            <span\n              key={step}\n              aria-hidden='true'\n              className='hairline-t border-border pointer-events-none absolute inset-x-0'\n              style={{ top: gridTopOf(step) }}\n            />\n          ))}\n          {barSpecs.map((spec) => {\n            const isDimmed = reading.isReading && spec.slot !== readSlot;\n            return (\n              <span\n                key={spec.id}\n                aria-hidden='true'\n                className={cn(\n                  'pointer-events-none absolute inset-0 transition-[clip-path,opacity] duration-[500ms,150ms] ease-(--ease-out-strong)',\n                  dimmedClassOf(isDimmed)\n                )}\n                style={{ backgroundColor: spec.color, clipPath: spec.clip }}\n              />\n            );\n          })}\n        </div>\n        <div\n          aria-hidden='true'\n          className='relative col-start-2 mt-2 h-4 text-[11px]'\n        >\n          {data.bars.map((bar, slot) => {\n            const position = slot - firstPresent;\n            const isMinor = isMinorLabel(position, months);\n            return (\n              <span\n                key={bar.label}\n                className={cn(\n                  'text-muted-foreground absolute top-0 -translate-x-1/2 whitespace-nowrap transition-[left,opacity] duration-500 ease-(--ease-out-strong)',\n                  !bar.isPresent && 'opacity-0',\n                  isMinor && '@max-md/card:opacity-0'\n                )}\n                style={{ left: labelLeftOf(Math.max(position, 0), months) }}\n              >\n                {bar.label}\n              </span>\n            );\n          })}\n        </div>\n      </div>\n      <div className='sr-only'>\n        <table>\n          <caption>Clicks by channel and month</caption>\n          <thead>\n            <tr>\n              <th scope='col'>Month</th>\n              {CHANNELS.map((channel) => (\n                <th key={channel.id} scope='col'>\n                  {channel.name}\n                </th>\n              ))}\n            </tr>\n          </thead>\n          <tbody>\n            {presentBars.map((bar) => (\n              <tr key={bar.label}>\n                <th scope='row'>{bar.label}</th>\n                {bar.values.map((value, index) => (\n                  <td key={CHANNELS[index].id}>{formatCount(value)}</td>\n                ))}\n              </tr>\n            ))}\n          </tbody>\n        </table>\n      </div>\n      <ul className='text-muted-foreground flex flex-wrap items-center gap-x-4 gap-y-1 text-xs'>\n        {CHANNELS.map((channel) => (\n          <li key={channel.id} className='flex items-center gap-1.5'>\n            <span\n              aria-hidden='true'\n              className='size-2 rounded-full'\n              style={{ backgroundColor: seriesColorOf(channel.series) }}\n            />\n            {channel.name}\n          </li>\n        ))}\n      </ul>\n    </ChartCard>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/channel-bars.tsx"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/chart-card.tsx",
      "content": "'use client';\n\nimport { useId } from 'react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nconst CARD =\n  'bg-card hairline-ring ring-border dark:bg-foreground/[0.03] @container/card flex h-full scroll-mt-4 flex-col gap-4 rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]';\n\ntype ChartCardProps = {\n  title: string;\n  description?: React.ReactNode;\n  section?: string;\n  className?: string;\n  children: React.ReactNode;\n};\n\nexport function ChartCard({\n  title,\n  description,\n  section,\n  className,\n  children,\n}: ChartCardProps) {\n  const titleId = useId();\n\n  return (\n    <section\n      data-section={section}\n      aria-labelledby={titleId}\n      className={cn(CARD, className)}\n    >\n      <header className='flex flex-col leading-tight'>\n        <h2 id={titleId} className='text-sm font-medium'>\n          {title}\n        </h2>\n        {description}\n      </header>\n      {children}\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/chart-card.tsx"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/chart-math.ts",
      "content": "export type Point = {\n  x: number;\n  y: number;\n};\n\n/** Paths are drawn in a box this wide and stretched to the plot, so a change of width never redraws them. */\nexport const VIEW_WIDTH = 1000;\n\n/** Every chart draws this many gridlines above zero, so the lines stay put and only their figures change. */\nexport const GRID_STEPS = 4;\n\nconst NICE_FACTORS = [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10];\n\nexport type Scale = {\n  max: number;\n  ticks: number[];\n};\n\nfunction niceStepOf(roughStep: number) {\n  const logarithm = Math.log10(roughStep);\n  const exponent = Math.floor(logarithm);\n  const magnitude = 10 ** exponent;\n  const factor = NICE_FACTORS.find((candidate) => {\n    const candidateStep = candidate * magnitude;\n    return candidateStep >= roughStep;\n  });\n  const safeFactor = factor ?? 10;\n  return safeFactor * magnitude;\n}\n\n/** Four equal steps from zero that hold the largest value, so the plot keeps five lines whatever the data. */\nexport function niceScaleOf(largest: number): Scale {\n  const safeLargest = Math.max(largest, 1);\n  const roughStep = safeLargest / GRID_STEPS;\n  const step = niceStepOf(roughStep);\n  const ticks = Array.from({ length: GRID_STEPS + 1 }, (_, index) => {\n    return index * step;\n  });\n  return { max: step * GRID_STEPS, ticks };\n}\n\nexport function shareOf(value: number, max: number) {\n  if (max === 0) {\n    return 0;\n  }\n  return value / max;\n}\n\nexport function clamp(value: number, min: number, max: number) {\n  const atLeastMin = Math.max(value, min);\n  return Math.min(atLeastMin, max);\n}\n\nfunction commandOf(point: Point, index: number) {\n  const x = point.x.toFixed(1);\n  const y = point.y.toFixed(1);\n  if (index === 0) {\n    return `M${x} ${y}`;\n  }\n  return `L${x} ${y}`;\n}\n\nexport function linePathOf(points: readonly Point[]) {\n  const commands = points.map((point, index) => commandOf(point, index));\n  return commands.join(' ');\n}\n\nexport function areaPathOf(points: readonly Point[], levelY: number) {\n  if (points.length === 0) {\n    return '';\n  }\n  const line = linePathOf(points);\n  const lastIndex = points.length - 1;\n  const firstX = points[0].x.toFixed(1);\n  const lastX = points[lastIndex].x.toFixed(1);\n  const level = levelY.toFixed(1);\n  return `${line} L${lastX} ${level} L${firstX} ${level} Z`;\n}\n\nexport function pointsOf(\n  values: readonly number[],\n  max: number,\n  height: number\n) {\n  const lastIndex = Math.max(values.length - 1, 1);\n  return values.map((value, index) => {\n    const x = (index / lastIndex) * VIEW_WIDTH;\n    const share = shareOf(value, max);\n    const y = height - share * height;\n    return { x, y };\n  });\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/chart-math.ts"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/conversion-funnel.tsx",
      "content": "'use client';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport { ChartCard } from './chart-card';\nimport { STAGES } from './data';\nimport { COUNT_FORMAT, percentOf } from './format';\nimport type { PeriodData } from './period-data';\n\n/** The narrowest a bar gets, so the last stage stays a bar and not a line. */\nconst MIN_SHARE = 0.16;\n\nconst PRECISE_PERCENT: Intl.NumberFormatOptions = {\n  minimumFractionDigits: 1,\n  maximumFractionDigits: 1,\n};\n\n/** The first three stages are the primary colour, fading as the funnel narrows. The last one is a customer won. */\nconst BAR_FILL = [\n  'bg-primary/90',\n  'bg-primary/72',\n  'bg-primary/54',\n  'bg-success/80',\n];\n\n/** Counts fall faster than a person can read bars, so a bar is as wide as the square root of its count. */\nfunction widthShareOf(count: number, first: number) {\n  if (first === 0) {\n    return MIN_SHARE;\n  }\n  const share = Math.sqrt(count / first);\n  return Math.max(share, MIN_SHARE);\n}\n\nfunction insetOf(share: number) {\n  const side = ((1 - share) / 2) * 100;\n  const text = `${side.toFixed(2)}%`;\n  return `inset(0 ${text} 0 ${text} round 6px)`;\n}\n\nfunction moveOnOf(count: number, before: number) {\n  if (before === 0) {\n    return 0;\n  }\n  return percentOf(count / before);\n}\n\ntype ConversionFunnelProps = {\n  data: PeriodData;\n};\n\nexport function ConversionFunnel({ data }: ConversionFunnelProps) {\n  const first = data.funnel[0];\n  const last = data.funnel[data.funnel.length - 1];\n  const overall = (last / first) * 100;\n\n  return (\n    <ChartCard\n      title='Conversion funnel'\n      section='funnel'\n      description={\n        <p className='text-muted-foreground text-xs'>From lead to customer</p>\n      }\n    >\n      <ol aria-label='Conversion funnel' className='flex flex-col gap-2'>\n        {STAGES.map((stage, index) => {\n          const count = data.funnel[index];\n          const before = data.funnel[index - 1] ?? 0;\n          const share = widthShareOf(count, first);\n          const hasRate = index > 0;\n          return (\n            <li\n              key={stage.id}\n              className='grid grid-cols-[6.5rem_minmax(0,1fr)_auto] items-center gap-x-3'\n            >\n              <span className='text-muted-foreground truncate text-xs'>\n                {stage.label}\n              </span>\n              <span aria-hidden='true' className='relative h-7'>\n                <span\n                  className={cn(\n                    'absolute inset-0 transition-[clip-path] duration-500 ease-(--ease-out-strong)',\n                    BAR_FILL[index]\n                  )}\n                  style={{ clipPath: insetOf(share) }}\n                />\n              </span>\n              <span className='flex items-baseline justify-end gap-2'>\n                <MotionNumber\n                  value={count}\n                  format={COUNT_FORMAT}\n                  className='w-14 justify-end text-[13px] font-medium'\n                />\n                <span\n                  className={cn(\n                    'text-muted-foreground hidden w-9 justify-end text-xs @sm/card:inline-flex',\n                    !hasRate && 'invisible'\n                  )}\n                >\n                  <MotionNumber\n                    value={moveOnOf(count, before)}\n                    format={COUNT_FORMAT}\n                    suffix='%'\n                  />\n                  <span className='sr-only'> of the stage before</span>\n                </span>\n              </span>\n            </li>\n          );\n        })}\n      </ol>\n      <p className='text-muted-foreground flex items-baseline gap-1 text-xs'>\n        <span>Overall</span>\n        <MotionNumber\n          value={overall}\n          format={PRECISE_PERCENT}\n          suffix='%'\n          className='text-foreground font-medium'\n        />\n        <span>of leads become customers</span>\n      </p>\n    </ChartCard>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/conversion-funnel.tsx"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/data.ts",
      "content": "import type { SeriesSlot } from '@/registry/ndeko/lib/agent-run';\nimport {\n  CalendarIcon,\n  ChartBarIcon,\n  FilterIcon,\n  HomeIcon,\n  LineChartIcon,\n  RocketIcon,\n  UsersIcon,\n  type Icon,\n} from '@/registry/ndeko/lib/icons';\n\nexport const BRAND = { name: 'Tarnbrook' };\n\nexport const MARKETING_LEAD = {\n  name: 'Mireille Kabasele',\n  role: 'Marketing lead',\n};\n\nexport type SectionId =\n  | 'overview'\n  | 'leads'\n  | 'traffic'\n  | 'channels'\n  | 'funnel'\n  | 'week'\n  | 'campaigns';\n\nexport type NavItem = {\n  id: SectionId;\n  label: string;\n  icon: Icon;\n};\n\nexport type NavGroup = {\n  id: string;\n  label: string;\n  items: NavItem[];\n};\n\nexport const NAV_GROUPS: NavGroup[] = [\n  {\n    id: 'reports',\n    label: 'Reports',\n    items: [\n      { id: 'overview', label: 'Overview', icon: HomeIcon },\n      { id: 'leads', label: 'Leads', icon: UsersIcon },\n      { id: 'traffic', label: 'Traffic', icon: LineChartIcon },\n      { id: 'channels', label: 'Channels', icon: ChartBarIcon },\n      { id: 'funnel', label: 'Funnel', icon: FilterIcon },\n    ],\n  },\n  {\n    id: 'plan',\n    label: 'Plan',\n    items: [\n      { id: 'week', label: 'This week', icon: CalendarIcon },\n      { id: 'campaigns', label: 'Campaigns', icon: RocketIcon },\n    ],\n  },\n];\n\nexport type PeriodId = '3m' | '6m' | '12m';\n\nexport type PeriodOption = {\n  value: PeriodId;\n  label: string;\n  months: number;\n};\n\nexport const PERIODS: PeriodOption[] = [\n  { value: '3m', label: '3 months', months: 3 },\n  { value: '6m', label: '6 months', months: 6 },\n  { value: '12m', label: '12 months', months: 12 },\n];\n\nexport function periodOf(id: PeriodId) {\n  const period = PERIODS.find((candidate) => candidate.value === id);\n  return period ?? PERIODS[1];\n}\n\nexport type ChannelId = 'search' | 'social' | 'email';\n\nexport type Channel = {\n  id: ChannelId;\n  name: string;\n  series: SeriesSlot;\n};\n\nexport const CHANNELS: Channel[] = [\n  { id: 'search', name: 'Search', series: 1 },\n  { id: 'social', name: 'Social', series: 2 },\n  { id: 'email', name: 'Email', series: 3 },\n];\n\nexport function channelOf(id: ChannelId) {\n  const channel = CHANNELS.find((candidate) => candidate.id === id);\n  return channel ?? CHANNELS[0];\n}\n\nexport type OriginId = 'search' | 'social' | 'email' | 'referral' | 'events';\n\nexport type Origin = {\n  id: OriginId;\n  name: string;\n  series: SeriesSlot;\n};\n\nexport const ORIGINS: Origin[] = [\n  { id: 'search', name: 'Search', series: 1 },\n  { id: 'social', name: 'Social', series: 2 },\n  { id: 'email', name: 'Email', series: 3 },\n  { id: 'referral', name: 'Referral', series: 4 },\n  { id: 'events', name: 'Events', series: 5 },\n];\n\nexport type GoalId = 'leads' | 'demos' | 'signups';\n\nexport type Goal = {\n  id: GoalId;\n  label: string;\n  noun: string;\n  targets: Record<PeriodId, number>;\n};\n\nexport const GOALS: Goal[] = [\n  {\n    id: 'leads',\n    label: 'Leads',\n    noun: 'leads',\n    targets: { '3m': 1800, '6m': 4400, '12m': 9800 },\n  },\n  {\n    id: 'demos',\n    label: 'Demo bookings',\n    noun: 'demos',\n    targets: { '3m': 500, '6m': 640, '12m': 1800 },\n  },\n  {\n    id: 'signups',\n    label: 'Newsletter signups',\n    noun: 'signups',\n    targets: { '3m': 1400, '6m': 2200, '12m': 3500 },\n  },\n];\n\nexport type StageId = 'leads' | 'qualified' | 'opportunities' | 'customers';\n\nexport type Stage = {\n  id: StageId;\n  label: string;\n};\n\nexport const STAGES: Stage[] = [\n  { id: 'leads', label: 'Leads' },\n  { id: 'qualified', label: 'Qualified' },\n  { id: 'opportunities', label: 'Opportunities' },\n  { id: 'customers', label: 'Customers' },\n];\n\nexport type CampaignStatus = 'live' | 'paused';\n\nexport type Campaign = {\n  id: string;\n  name: string;\n  channel: ChannelId;\n  status: CampaignStatus;\n  /** How many of the last twenty-four months the campaign has been running. */\n  ageMonths: number;\n  monthlySpend: number;\n  monthlyClicks: number;\n  monthlyLeads: number;\n  /** The days of the current week it runs on, Monday first. A campaign not running this week has none. */\n  weekFrom?: number;\n  weekTo?: number;\n};\n\nexport const CAMPAIGNS: Campaign[] = [\n  {\n    id: 'brand-keywords',\n    name: 'Brand keywords',\n    channel: 'search',\n    status: 'live',\n    ageMonths: 24,\n    monthlySpend: 3200,\n    monthlyClicks: 5200,\n    monthlyLeads: 118,\n    weekFrom: 0,\n    weekTo: 6,\n  },\n  {\n    id: 'competitor-terms',\n    name: 'Competitor terms',\n    channel: 'search',\n    status: 'live',\n    ageMonths: 20,\n    monthlySpend: 2400,\n    monthlyClicks: 2900,\n    monthlyLeads: 54,\n  },\n  {\n    id: 'local-intent',\n    name: 'Local intent, Kinshasa',\n    channel: 'search',\n    status: 'live',\n    ageMonths: 4,\n    monthlySpend: 1500,\n    monthlyClicks: 2400,\n    monthlyLeads: 71,\n  },\n  {\n    id: 'creator-takeover',\n    name: 'Creator takeover',\n    channel: 'social',\n    status: 'live',\n    ageMonths: 10,\n    monthlySpend: 2800,\n    monthlyClicks: 3600,\n    monthlyLeads: 62,\n    weekFrom: 2,\n    weekTo: 4,\n  },\n  {\n    id: 'retargeting-stories',\n    name: 'Retargeting stories',\n    channel: 'social',\n    status: 'paused',\n    ageMonths: 19,\n    monthlySpend: 1800,\n    monthlyClicks: 2500,\n    monthlyLeads: 41,\n  },\n  {\n    id: 'community-ads',\n    name: 'Community ads, Goma',\n    channel: 'social',\n    status: 'live',\n    ageMonths: 2,\n    monthlySpend: 1200,\n    monthlyClicks: 1900,\n    monthlyLeads: 38,\n    weekFrom: 4,\n    weekTo: 6,\n  },\n  {\n    id: 'weekly-digest',\n    name: 'Weekly digest',\n    channel: 'email',\n    status: 'live',\n    ageMonths: 24,\n    monthlySpend: 600,\n    monthlyClicks: 2800,\n    monthlyLeads: 49,\n    weekFrom: 3,\n    weekTo: 3,\n  },\n  {\n    id: 'winback-series',\n    name: 'Winback series',\n    channel: 'email',\n    status: 'live',\n    ageMonths: 6,\n    monthlySpend: 450,\n    monthlyClicks: 1100,\n    monthlyLeads: 33,\n    weekFrom: 0,\n    weekTo: 2,\n  },\n  {\n    id: 'onboarding-drip',\n    name: 'Onboarding drip',\n    channel: 'email',\n    status: 'live',\n    ageMonths: 21,\n    monthlySpend: 380,\n    monthlyClicks: 900,\n    monthlyLeads: 27,\n  },\n];\n\nexport function campaignOf(id: string) {\n  const campaign = CAMPAIGNS.find((candidate) => candidate.id === id);\n  return campaign ?? CAMPAIGNS[0];\n}\n\nexport type WeekDay = {\n  index: number;\n  weekday: string;\n  dayOfMonth: number;\n};\n\n/** The week the strip shows starts on a fixed Monday, so the server and the browser draw the same dates. */\nexport const WEEK_START = '2026-11-09';\n\nexport const TODAY_INDEX = 4;\n\nconst WEEKDAY = new Intl.DateTimeFormat('en-US', {\n  weekday: 'short',\n  timeZone: 'UTC',\n});\n\nconst DAY_MS = 86_400_000;\n\nfunction weekDayOf(index: number): WeekDay {\n  const start = Date.parse(`${WEEK_START}T00:00:00Z`);\n  const date = new Date(start + index * DAY_MS);\n  return {\n    index,\n    weekday: WEEKDAY.format(date),\n    dayOfMonth: date.getUTCDate(),\n  };\n}\n\nexport const WEEK: WeekDay[] = Array.from({ length: 7 }, (_, index) =>\n  weekDayOf(index)\n);\n\nexport const WEEK_RANGE = 'Nov 9 to 15';\n\nexport const DEMO_CAMPAIGN = 'creator-takeover';\n",
      "type": "registry:component",
      "target": "components/templates/application-16/data.ts"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/format.ts",
      "content": "export const COUNT_FORMAT: Intl.NumberFormatOptions = {\n  maximumFractionDigits: 0,\n};\n\nexport const MONEY_FORMAT: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  maximumFractionDigits: 0,\n};\n\nexport const PRECISE_MONEY_FORMAT: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  minimumFractionDigits: 2,\n  maximumFractionDigits: 2,\n};\n\nexport const COMPACT_FORMAT: Intl.NumberFormatOptions = {\n  notation: 'compact',\n  maximumFractionDigits: 1,\n};\n\nconst COUNT = new Intl.NumberFormat('en-US', COUNT_FORMAT);\n\nexport function formatCount(value: number) {\n  return COUNT.format(value);\n}\n\nexport function percentOf(share: number) {\n  return Math.round(share * 100);\n}\n\n/** A start at zero has no percentage to grow from: it reads as no change. */\nexport function percentChangeOf(current: number, previous: number) {\n  if (previous === 0) {\n    return 0;\n  }\n  const difference = current - previous;\n  const ratio = difference / Math.abs(previous);\n  return Math.round(ratio * 100);\n}\n\nexport function changeWordsOf(percent: number, reference: string) {\n  if (percent === 0) {\n    return `level with ${reference}`;\n  }\n  const size = Math.abs(percent);\n  if (percent > 0) {\n    return `up ${size}% on ${reference}`;\n  }\n  return `down ${size}% on ${reference}`;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/format.ts"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/goal-meters.tsx",
      "content": "'use client';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport { ChartCard } from './chart-card';\nimport { GOALS, type Goal } from './data';\nimport { COUNT_FORMAT, formatCount } from './format';\nimport type { GoalResult, PeriodData } from './period-data';\n\nconst TICK_COUNT = 28;\n\nconst TICKS = Array.from({ length: TICK_COUNT }, (_, index) => index);\n\n/** Each tick follows the one before by this long, so a meter fills like a wave and no two meters move at once alone. */\nconst TICK_WAVE_MS = 14;\n\nfunction filledOf(share: number) {\n  const capped = Math.min(share, 1);\n  return Math.round(capped * TICK_COUNT);\n}\n\nfunction tickToneOf(isFilled: boolean, isReached: boolean) {\n  if (!isFilled) {\n    return 'bg-foreground/[0.08]';\n  }\n  if (isReached) {\n    return 'bg-success';\n  }\n  return 'bg-primary';\n}\n\ntype TickMeterProps = {\n  goal: Goal;\n  result: GoalResult;\n};\n\nfunction TickMeter({ goal, result }: TickMeterProps) {\n  const filled = filledOf(result.share);\n  const isReached = result.share >= 1;\n  const spoken = `${goal.label}: ${formatCount(result.actual)} of ${formatCount(result.target)} ${goal.noun}`;\n\n  return (\n    <div\n      role='meter'\n      aria-label={spoken}\n      aria-valuemin={0}\n      aria-valuemax={result.target}\n      aria-valuenow={result.actual}\n      className='flex h-4 gap-0.5'\n    >\n      {TICKS.map((tick) => {\n        const isFilled = tick < filled;\n        return (\n          <span\n            key={tick}\n            aria-hidden='true'\n            className={cn(\n              'min-w-0 flex-1 rounded-[2px] transition-colors duration-300',\n              tickToneOf(isFilled, isReached)\n            )}\n            style={{ transitionDelay: `${tick * TICK_WAVE_MS}ms` }}\n          />\n        );\n      })}\n    </div>\n  );\n}\n\ntype GoalMetersProps = {\n  data: PeriodData;\n};\n\nexport function GoalMeters({ data }: GoalMetersProps) {\n  return (\n    <ChartCard\n      title='Goals'\n      description={\n        <p className='text-muted-foreground text-xs'>\n          Against the target for the period\n        </p>\n      }\n    >\n      <ul className='flex flex-col gap-4'>\n        {GOALS.map((goal, index) => {\n          const result = data.goals[index];\n          return (\n            <li key={goal.id} className='flex flex-col gap-1.5'>\n              <p className='flex items-baseline gap-2'>\n                <span className='min-w-0 flex-1 truncate text-[13px] font-medium'>\n                  {goal.label}\n                </span>\n                <MotionNumber\n                  value={Math.round(result.share * 100)}\n                  format={COUNT_FORMAT}\n                  suffix='%'\n                  className='text-[13px] font-semibold'\n                />\n              </p>\n              <TickMeter goal={goal} result={result} />\n              <p className='text-muted-foreground flex items-baseline gap-1 text-xs'>\n                <MotionNumber value={result.actual} format={COUNT_FORMAT} />\n                <span>of</span>\n                <MotionNumber value={result.target} format={COUNT_FORMAT} />\n                <span>{goal.noun}</span>\n              </p>\n            </li>\n          );\n        })}\n      </ul>\n    </ChartCard>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/goal-meters.tsx"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/lead-split.tsx",
      "content": "'use client';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { seriesColorOf } from '@/registry/ndeko/lib/agent-run';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\n\nimport { ChartCard } from './chart-card';\nimport { ORIGINS } from './data';\nimport { COUNT_FORMAT, percentOf } from './format';\nimport type { PeriodData } from './period-data';\n\n/** A segment is the whole bar clipped to its share, so every segment glides to its new place together and keeps its round ends. */\nfunction insetOf(start: number, end: number) {\n  const left = start * 100;\n  const right = (1 - end) * 100;\n  return `inset(0 calc(${right}% + 1px) 0 calc(${left}% + 1px) round 6px)`;\n}\n\ntype Segment = {\n  id: string;\n  color: string;\n  start: number;\n  end: number;\n};\n\nfunction segmentsOf(leads: readonly number[], total: number) {\n  const segments: Segment[] = [];\n  let used = 0;\n  ORIGINS.forEach((origin, index) => {\n    const share = leads[index] / total;\n    const start = used;\n    used += share;\n    segments.push({\n      id: origin.id,\n      color: seriesColorOf(origin.series),\n      start,\n      end: used,\n    });\n  });\n  return segments;\n}\n\ntype LeadSplitProps = {\n  data: PeriodData;\n};\n\nexport function LeadSplit({ data }: LeadSplitProps) {\n  const segments = segmentsOf(data.leads, data.totalLeads);\n\n  return (\n    <ChartCard\n      title='Leads by origin'\n      section='leads'\n      description={\n        <p className='text-muted-foreground text-xs'>\n          Where each lead came from\n        </p>\n      }\n    >\n      <div className='flex flex-col gap-1'>\n        <p className='flex items-baseline gap-1.5'>\n          <MotionNumber\n            value={data.totalLeads}\n            format={COUNT_FORMAT}\n            className='text-2xl leading-8 font-semibold'\n          />\n          <span className='text-muted-foreground text-[13px]'>leads</span>\n        </p>\n        <Swap\n          swapKey={data.leadsChange}\n          className='text-muted-foreground text-xs'\n        >\n          {data.leadsChange}\n        </Swap>\n      </div>\n      <div\n        aria-hidden='true'\n        className='bg-foreground/[0.06] relative h-3 rounded-full'\n      >\n        {segments.map((segment) => (\n          <span\n            key={segment.id}\n            className='absolute inset-0 transition-[clip-path] duration-500 ease-(--ease-out-strong)'\n            style={{\n              backgroundColor: segment.color,\n              clipPath: insetOf(segment.start, segment.end),\n            }}\n          />\n        ))}\n      </div>\n      <ul\n        aria-label='Leads by origin'\n        className='grid gap-x-6 gap-y-2 @md/card:grid-cols-2'\n      >\n        {ORIGINS.map((origin, index) => (\n          <li key={origin.id} className='flex items-center gap-2 text-[13px]'>\n            <span\n              aria-hidden='true'\n              className='size-2 shrink-0 rounded-full'\n              style={{ backgroundColor: seriesColorOf(origin.series) }}\n            />\n            <span className='text-muted-foreground min-w-0 flex-1 truncate'>\n              {origin.name}\n            </span>\n            <MotionNumber\n              value={data.leads[index]}\n              format={COUNT_FORMAT}\n              className='font-medium'\n            />\n            <MotionNumber\n              value={percentOf(data.leads[index] / data.totalLeads)}\n              format={COUNT_FORMAT}\n              suffix='%'\n              className='text-muted-foreground w-10 justify-end text-xs'\n            />\n          </li>\n        ))}\n      </ul>\n    </ChartCard>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/lead-split.tsx"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/morph-path.tsx",
      "content": "'use client';\n\nimport { motion, type Transition } from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { EASE_OUT_STRONG, INSTANT } from '@/registry/ndeko/lib/motion-presets';\n\nconst MORPH: Transition = { duration: 0.5, ease: EASE_OUT_STRONG };\n\nfunction transitionOf(shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return INSTANT;\n  }\n  return MORPH;\n}\n\ntype MorphPathProps = {\n  d: string;\n  className?: string;\n  style?: React.CSSProperties;\n};\n\n/** A shape that glides to its new outline when the data changes, as long as both outlines have the same number of points. */\nexport function MorphPath({ d, className, style }: MorphPathProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n\n  return (\n    <motion.path\n      initial={false}\n      animate={{ d }}\n      transition={transitionOf(shouldReduceMotion)}\n      vectorEffect='non-scaling-stroke'\n      className={className}\n      style={style}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/morph-path.tsx"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/page-header.tsx",
      "content": "'use client';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport { MenuIcon } from '@/registry/ndeko/lib/icons';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\nimport { Segments } from '@/registry/ndeko/ui/segments';\n\nimport { PERIODS, type PeriodId } from './data';\nimport { dataOf } from './period-data';\n\nconst RANGE_LABELS = PERIODS.map((period) => dataOf(period.value).rangeLabel);\n\ntype PageHeaderProps = {\n  period: PeriodId;\n  canReplay: boolean;\n  onPeriodChange: (period: PeriodId) => void;\n  onReplay: () => void;\n  onOpenMenu: () => void;\n};\n\nexport function PageHeader({\n  period,\n  canReplay,\n  onPeriodChange,\n  onReplay,\n  onOpenMenu,\n}: PageHeaderProps) {\n  const { rangeLabel } = dataOf(period);\n\n  return (\n    <header className='flex shrink-0 flex-wrap items-center gap-x-3 gap-y-2 px-3 py-2'>\n      <div className='flex min-w-0 flex-1 items-center gap-2'>\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          data-menu-open\n          aria-label='Open the sections'\n          aria-haspopup='dialog'\n          onClick={onOpenMenu}\n          className='text-muted-foreground @3xl:hidden'\n        >\n          <MenuIcon />\n        </Button>\n        <div className='flex min-w-0 flex-col ps-1 leading-tight'>\n          <h1 className='text-sm font-medium'>Marketing</h1>\n          <p className='text-muted-foreground text-xs'>\n            <WordRoll text={rangeLabel} labels={RANGE_LABELS} />\n          </p>\n        </div>\n        <Badge variant='secondary'>Illustrative data</Badge>\n      </div>\n      <div className='flex items-center gap-2'>\n        <ReplayButton isShown={canReplay} onReplay={onReplay} label='Replay' />\n        <Segments\n          value={period}\n          segments={PERIODS}\n          onValueChange={onPeriodChange}\n          label='Period'\n        />\n      </div>\n    </header>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/page-header.tsx"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/period-data.ts",
      "content": "import {\n  CAMPAIGNS,\n  CHANNELS,\n  GOALS,\n  periodOf,\n  STAGES,\n  type Campaign,\n  type ChannelId,\n  type GoalId,\n  type PeriodId,\n} from './data';\nimport { changeWordsOf, percentChangeOf } from './format';\n\n/** Twenty-four whole months, November 2024 to October 2026, drawn from fixed seeds: nothing is random between two renders. */\nconst HISTORY_MONTHS = 24;\n\n/** The bar chart always holds twelve month slots; a shorter period fills the last ones. */\nexport const BAR_SLOTS = 12;\n\nexport const TRAFFIC_POINTS = 90;\n\nconst DAY_MS = 86_400_000;\n\nconst HISTORY_START = Date.UTC(2024, 10, 1);\n\n/** 1 November 2024 is a Friday, the fifth day of a week that starts on Monday. */\nconst FIRST_WEEKDAY = 4;\n\nfunction seededRandom(seed: number) {\n  let state = seed;\n  return function next() {\n    state = (state + 0x6d2b79f5) | 0;\n    let mixed = Math.imul(state ^ (state >>> 15), 1 | state);\n    mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed;\n    return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\nfunction monthStartDayOf(month: number) {\n  const start = Date.UTC(2024, 10 + month, 1);\n  return Math.round((start - HISTORY_START) / DAY_MS);\n}\n\nconst MONTH_STARTS = Array.from({ length: HISTORY_MONTHS + 1 }, (_, month) =>\n  monthStartDayOf(month)\n);\n\nconst TOTAL_DAYS = MONTH_STARTS[HISTORY_MONTHS];\n\nconst SHORT_MONTH = new Intl.DateTimeFormat('en-US', {\n  month: 'short',\n  timeZone: 'UTC',\n});\n\nconst SHORT_DAY = new Intl.DateTimeFormat('en-US', {\n  month: 'short',\n  day: 'numeric',\n  timeZone: 'UTC',\n});\n\nconst YEAR = new Intl.DateTimeFormat('en-US', {\n  year: 'numeric',\n  timeZone: 'UTC',\n});\n\nfunction monthDate(month: number) {\n  return new Date(Date.UTC(2024, 10 + month, 1));\n}\n\nfunction monthLabelOf(month: number) {\n  return SHORT_MONTH.format(monthDate(month));\n}\n\nfunction dayDate(day: number) {\n  return new Date(HISTORY_START + day * DAY_MS);\n}\n\nfunction dayLabelOf(day: number) {\n  return SHORT_DAY.format(dayDate(day));\n}\n\n/** Saturday and Sunday bring about a quarter fewer visits. */\nfunction rhythmOf(weekday: number) {\n  if (weekday >= 5) {\n    return 0.74;\n  }\n  return 1;\n}\n\nfunction visitsOfDay(day: number, next: () => number) {\n  const trend = 1380 + day * 1.15;\n  const yearTurn = (day / 365) * Math.PI * 2;\n  const season = 1 + 0.08 * Math.sin(yearTurn - 0.6);\n  const weekday = (day + FIRST_WEEKDAY) % 7;\n  const rhythm = rhythmOf(weekday);\n  const noise = 0.9 + next() * 0.2;\n  return Math.round(trend * season * rhythm * noise);\n}\n\nfunction dailyVisits() {\n  const next = seededRandom(7);\n  return Array.from({ length: TOTAL_DAYS }, (_, day) => visitsOfDay(day, next));\n}\n\nconst DAILY_VISITS = dailyVisits();\n\ntype Growth = {\n  base: number;\n  growth: number;\n  swing: number;\n  seed: number;\n};\n\nconst CHANNEL_GROWTH: Record<ChannelId, Growth> = {\n  search: { base: 9200, growth: 0.021, swing: 0.07, seed: 11 },\n  social: { base: 5400, growth: 0.03, swing: 0.12, seed: 23 },\n  email: { base: 3900, growth: 0.014, swing: 0.06, seed: 37 },\n};\n\nfunction monthlySeries(growth: Growth, phase: number) {\n  const next = seededRandom(growth.seed);\n  return Array.from({ length: HISTORY_MONTHS }, (_, month) => {\n    const trend = growth.base * (1 + growth.growth) ** month;\n    const yearTurn = (month / 12) * Math.PI * 2;\n    const season = 1 + 0.06 * Math.sin(yearTurn - phase);\n    const noise = 1 + (next() - 0.5) * 2 * growth.swing;\n    return Math.round(trend * season * noise);\n  });\n}\n\nconst CLICKS: Record<ChannelId, number[]> = {\n  search: monthlySeries(CHANNEL_GROWTH.search, 0.8),\n  social: monthlySeries(CHANNEL_GROWTH.social, 1.6),\n  email: monthlySeries(CHANNEL_GROWTH.email, 0.2),\n};\n\nconst ORIGIN_GROWTH: Growth[] = [\n  { base: 230, growth: 0.006, swing: 0.08, seed: 41 },\n  { base: 64, growth: 0.045, swing: 0.12, seed: 43 },\n  { base: 98, growth: 0.004, swing: 0.07, seed: 47 },\n  { base: 38, growth: 0.034, swing: 0.1, seed: 53 },\n  { base: 52, growth: 0, swing: 0.4, seed: 59 },\n];\n\nconst LEADS_BY_ORIGIN = ORIGIN_GROWTH.map((growth) =>\n  monthlySeries(growth, 0.4)\n);\n\ntype CampaignMonths = {\n  spend: number[];\n  clicks: number[];\n  leads: number[];\n};\n\n/** A campaign that has not started contributes nothing; one that has just started ramps up. */\nfunction scaleOf(isRunning: boolean, ramp: number, noise: number) {\n  if (!isRunning) {\n    return 0;\n  }\n  return ramp * noise;\n}\n\nfunction campaignMonthsOf(campaign: Campaign, index: number): CampaignMonths {\n  const next = seededRandom(101 + index * 7);\n  const firstMonth = HISTORY_MONTHS - campaign.ageMonths;\n  const spend: number[] = [];\n  const clicks: number[] = [];\n  const leads: number[] = [];\n  for (let month = 0; month < HISTORY_MONTHS; month += 1) {\n    const isRunning = month >= firstMonth;\n    const age = month - firstMonth;\n    const ramp = Math.min(0.55 + age * 0.15, 1);\n    const maturity = Math.max(age, 0);\n    const noise = 0.9 + next() * 0.2;\n    const scale = scaleOf(isRunning, ramp, noise);\n    const spendGrowth = 1 + maturity * 0.006;\n    const clickGrowth = 1 + maturity * 0.014;\n    const leadGrowth = 1 + maturity * 0.022;\n    spend.push(Math.round(campaign.monthlySpend * scale * spendGrowth));\n    clicks.push(Math.round(campaign.monthlyClicks * scale * clickGrowth));\n    leads.push(Math.round(campaign.monthlyLeads * scale * leadGrowth));\n  }\n  return { spend, clicks, leads };\n}\n\nconst CAMPAIGN_MONTHS = new Map(\n  CAMPAIGNS.map((campaign, index) => [\n    campaign.id,\n    campaignMonthsOf(campaign, index),\n  ])\n);\n\nfunction sumOf(values: readonly number[]) {\n  let total = 0;\n  for (const value of values) {\n    total += value;\n  }\n  return total;\n}\n\n/** The months a period holds, counted back from the last one: [first, end). */\nfunction windowOf(months: number, shift = 0) {\n  const end = HISTORY_MONTHS - shift;\n  return { first: end - months, end };\n}\n\nfunction monthsSumOf(series: readonly number[], months: number, shift = 0) {\n  const { first, end } = windowOf(months, shift);\n  return sumOf(series.slice(first, end));\n}\n\nfunction dayRangeOf(months: number, shift = 0) {\n  const { first, end } = windowOf(months, shift);\n  return { from: MONTH_STARTS[first], to: MONTH_STARTS[end] };\n}\n\n/** The average of the days that fall in each of `count` equal parts of a span, so any period gives the same number of points. */\nfunction bucketsOf(days: readonly number[], count: number) {\n  return Array.from({ length: count }, (_, bucket) => {\n    const start = Math.floor((bucket * days.length) / count);\n    const rawEnd = Math.floor(((bucket + 1) * days.length) / count);\n    const end = Math.max(rawEnd, start + 1);\n    const part = days.slice(start, end);\n    return sumOf(part) / part.length;\n  });\n}\n\nexport type BarSlot = {\n  label: string;\n  isPresent: boolean;\n  values: number[];\n};\n\nexport type GoalResult = {\n  id: GoalId;\n  actual: number;\n  target: number;\n  share: number;\n};\n\nexport type CampaignTotals = {\n  spend: number;\n  clicks: number;\n  leads: number;\n  costPerLead: number;\n};\n\nfunction costPerLeadOf(spend: number, leads: number) {\n  if (leads === 0) {\n    return 0;\n  }\n  return spend / leads;\n}\n\nfunction totalsOf(\n  spend: number,\n  clicks: number,\n  leads: number\n): CampaignTotals {\n  const costPerLead = costPerLeadOf(spend, leads);\n  return { spend, clicks, leads, costPerLead };\n}\n\nexport type PeriodData = {\n  id: PeriodId;\n  months: number;\n  rangeLabel: string;\n  totalVisits: number;\n  visitsChange: string;\n  traffic: number[];\n  previousTraffic: number[];\n  bucketLabels: string[];\n  bars: BarSlot[];\n  largestBar: number;\n  leads: number[];\n  totalLeads: number;\n  leadsChange: string;\n  goals: GoalResult[];\n  funnel: number[];\n  campaigns: Record<string, CampaignTotals>;\n  groups: Record<ChannelId, CampaignTotals>;\n};\n\nconst FUNNEL_RATES: Record<PeriodId, number[]> = {\n  '3m': [0.49, 0.38, 0.34],\n  '6m': [0.45, 0.35, 0.31],\n  '12m': [0.41, 0.32, 0.28],\n};\n\nfunction barsOf(months: number): BarSlot[] {\n  const firstSlotMonth = HISTORY_MONTHS - BAR_SLOTS;\n  return Array.from({ length: BAR_SLOTS }, (_, slot) => {\n    const month = firstSlotMonth + slot;\n    const isPresent = slot >= BAR_SLOTS - months;\n    const values = CHANNELS.map((channel) => CLICKS[channel.id][month]);\n    return { label: monthLabelOf(month), isPresent, values };\n  });\n}\n\nfunction largestOf(values: readonly number[]) {\n  let largest = 0;\n  for (const value of values) {\n    largest = Math.max(largest, value);\n  }\n  return largest;\n}\n\nfunction rangeLabelOf(months: number) {\n  const first = monthDate(HISTORY_MONTHS - months);\n  const last = monthDate(HISTORY_MONTHS - 1);\n  const firstMonth = SHORT_MONTH.format(first);\n  const lastMonth = SHORT_MONTH.format(last);\n  const lastYear = YEAR.format(last);\n  const firstYear = YEAR.format(first);\n  if (firstYear === lastYear) {\n    return `${firstMonth} to ${lastMonth} ${lastYear}`;\n  }\n  return `${firstMonth} ${firstYear} to ${lastMonth} ${lastYear}`;\n}\n\nfunction goalResultsOf(\n  id: PeriodId,\n  months: number,\n  totalLeads: number,\n  demoShare: number,\n  signupShare: number\n): GoalResult[] {\n  const emailClicks = monthsSumOf(CLICKS.email, months);\n  const actuals: Record<GoalId, number> = {\n    leads: totalLeads,\n    demos: Math.round(totalLeads * demoShare),\n    signups: Math.round(emailClicks * signupShare),\n  };\n  return GOALS.map((goal) => {\n    const target = goal.targets[id];\n    const actual = actuals[goal.id];\n    return { id: goal.id, actual, target, share: actual / target };\n  });\n}\n\nconst DEMO_SHARE: Record<PeriodId, number> = {\n  '3m': 0.2,\n  '6m': 0.18,\n  '12m': 0.16,\n};\n\nconst SIGNUP_SHARE: Record<PeriodId, number> = {\n  '3m': 0.074,\n  '6m': 0.068,\n  '12m': 0.06,\n};\n\nfunction campaignTotalsOf(months: number) {\n  const campaigns: Record<string, CampaignTotals> = {};\n  for (const campaign of CAMPAIGNS) {\n    const series = CAMPAIGN_MONTHS.get(campaign.id);\n    const spend = monthsSumOf(series?.spend ?? [], months);\n    const clicks = monthsSumOf(series?.clicks ?? [], months);\n    const leads = monthsSumOf(series?.leads ?? [], months);\n    campaigns[campaign.id] = totalsOf(spend, clicks, leads);\n  }\n  return campaigns;\n}\n\nfunction groupTotalsOf(campaigns: Record<string, CampaignTotals>) {\n  const groups: Record<ChannelId, CampaignTotals> = {\n    search: totalsOf(0, 0, 0),\n    social: totalsOf(0, 0, 0),\n    email: totalsOf(0, 0, 0),\n  };\n  for (const channel of CHANNELS) {\n    const members = CAMPAIGNS.filter(\n      (campaign) => campaign.channel === channel.id\n    );\n    const spend = sumOf(members.map((member) => campaigns[member.id].spend));\n    const clicks = sumOf(members.map((member) => campaigns[member.id].clicks));\n    const leads = sumOf(members.map((member) => campaigns[member.id].leads));\n    groups[channel.id] = totalsOf(spend, clicks, leads);\n  }\n  return groups;\n}\n\nfunction funnelOf(totalLeads: number, rates: number[]) {\n  const counts = [totalLeads];\n  for (const rate of rates) {\n    const before = counts[counts.length - 1];\n    counts.push(Math.round(before * rate));\n  }\n  return counts.slice(0, STAGES.length);\n}\n\nfunction buildPeriodData(id: PeriodId): PeriodData {\n  const { months } = periodOf(id);\n  const current = dayRangeOf(months);\n  const before = dayRangeOf(months, months);\n  const currentDays = DAILY_VISITS.slice(current.from, current.to);\n  const previousDays = DAILY_VISITS.slice(before.from, before.to);\n  const totalVisits = sumOf(currentDays);\n  const previousVisits = sumOf(previousDays);\n  const visitsPercent = percentChangeOf(totalVisits, previousVisits);\n  const reference = `the ${months} months before`;\n  const bucketLabels = Array.from({ length: TRAFFIC_POINTS }, (_, bucket) => {\n    const offset = Math.floor((bucket * currentDays.length) / TRAFFIC_POINTS);\n    return dayLabelOf(current.from + offset);\n  });\n  const leads = LEADS_BY_ORIGIN.map((series) => monthsSumOf(series, months));\n  const previousLeads = sumOf(\n    LEADS_BY_ORIGIN.map((series) => monthsSumOf(series, months, months))\n  );\n  const totalLeads = sumOf(leads);\n  const leadsPercent = percentChangeOf(totalLeads, previousLeads);\n  const bars = barsOf(months);\n  const presentValues = bars.flatMap((slot) => {\n    if (slot.isPresent) {\n      return slot.values;\n    }\n    return [];\n  });\n  const campaigns = campaignTotalsOf(months);\n  return {\n    id,\n    months,\n    rangeLabel: rangeLabelOf(months),\n    totalVisits,\n    visitsChange: changeWordsOf(visitsPercent, reference),\n    traffic: bucketsOf(currentDays, TRAFFIC_POINTS),\n    previousTraffic: bucketsOf(previousDays, TRAFFIC_POINTS),\n    bucketLabels,\n    bars,\n    largestBar: largestOf(presentValues),\n    leads,\n    totalLeads,\n    leadsChange: changeWordsOf(leadsPercent, reference),\n    goals: goalResultsOf(\n      id,\n      months,\n      totalLeads,\n      DEMO_SHARE[id],\n      SIGNUP_SHARE[id]\n    ),\n    funnel: funnelOf(totalLeads, FUNNEL_RATES[id]),\n    campaigns,\n    groups: groupTotalsOf(campaigns),\n  };\n}\n\nconst CACHE = new Map<PeriodId, PeriodData>();\n\nexport function dataOf(id: PeriodId) {\n  const cached = CACHE.get(id);\n  if (cached) {\n    return cached;\n  }\n  const built = buildPeriodData(id);\n  CACHE.set(id, built);\n  return built;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/period-data.ts"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/roving.ts",
      "content": "/** The position an arrow key, Home or End moves to inside a row of items that share one tab stop. Null for any other key. */\nexport function rovingTargetOf(key: string, current: number, count: number) {\n  const last = count - 1;\n  if (key === 'ArrowRight' || key === 'ArrowDown') {\n    return Math.min(current + 1, last);\n  }\n  if (key === 'ArrowLeft' || key === 'ArrowUp') {\n    return Math.max(current - 1, 0);\n  }\n  if (key === 'Home') {\n    return 0;\n  }\n  if (key === 'End') {\n    return last;\n  }\n  return null;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/roving.ts"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/session.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\nimport { restingOf } from '@/registry/ndeko/lib/run-session';\n\nimport {\n  defaultDirectionOf,\n  sortSentenceOf,\n  type SortDirection,\n  type SortKey,\n} from './campaign-sort';\nimport { campaignOf, DEMO_CAMPAIGN, periodOf, type PeriodId } from './data';\n\nexport type MarketingState = {\n  period: PeriodId;\n  sortKey: SortKey;\n  sortDirection: SortDirection;\n  campaignId: string | null;\n  isSidebarOpen: boolean;\n  spoken: string;\n};\n\nexport type MarketingAction =\n  | { type: 'periodSet'; period: PeriodId }\n  | { type: 'sorted'; key: SortKey }\n  | { type: 'campaignSelected'; id: string | null }\n  | { type: 'sidebar'; isOpen: boolean };\n\ntype Step = SessionStep<MarketingState, MarketingAction>;\n\nexport const INITIAL: MarketingState = {\n  period: '6m',\n  sortKey: 'leads',\n  sortDirection: 'desc',\n  campaignId: null,\n  isSidebarOpen: false,\n  spoken: '',\n};\n\nfunction flippedOf(direction: SortDirection): SortDirection {\n  if (direction === 'asc') {\n    return 'desc';\n  }\n  return 'asc';\n}\n\n/** Pressing the column a table is sorted by turns it round; any other column starts with its own natural order. */\nfunction directionAfter(state: MarketingState, key: SortKey): SortDirection {\n  if (key === state.sortKey) {\n    return flippedOf(state.sortDirection);\n  }\n  return defaultDirectionOf(key);\n}\n\nfunction sorted(state: MarketingState, key: SortKey): MarketingState {\n  const sortDirection = directionAfter(state, key);\n  const spoken = sortSentenceOf(key, sortDirection);\n  return { ...state, sortKey: key, sortDirection, spoken };\n}\n\nfunction spokenSelectionOf(id: string | null) {\n  if (id === null) {\n    return 'Selection cleared';\n  }\n  const campaign = campaignOf(id);\n  return `${campaign.name} selected`;\n}\n\nexport function reducer(\n  state: MarketingState,\n  action: MarketingAction\n): MarketingState {\n  switch (action.type) {\n    case 'periodSet': {\n      const { months } = periodOf(action.period);\n      const spoken = `Showing the last ${months} months`;\n      return { ...state, period: action.period, spoken };\n    }\n    case 'sorted':\n      return sorted(state, action.key);\n    case 'campaignSelected': {\n      const spoken = spokenSelectionOf(action.id);\n      return { ...state, campaignId: action.id, spoken };\n    }\n    case 'sidebar':\n      return { ...state, isSidebarOpen: action.isOpen };\n  }\n}\n\nconst PERIOD_GAP_MS = 3400;\n\nfunction periodStep(after: number, period: PeriodId): Step {\n  return { after, by: 'demo', action: { type: 'periodSet', period } };\n}\n\nfunction sortStep(after: number, key: SortKey): Step {\n  return {\n    after,\n    by: 'demo',\n    press: `sort-${key}`,\n    action: { type: 'sorted', key },\n  };\n}\n\nexport const SCRIPT: Step[] = [\n  periodStep(2400, '12m'),\n  periodStep(PERIOD_GAP_MS, '3m'),\n  periodStep(PERIOD_GAP_MS, '6m'),\n  sortStep(2800, 'spend'),\n  sortStep(2400, 'cost'),\n  sortStep(2400, 'leads'),\n  {\n    after: 2200,\n    by: 'demo',\n    press: `campaign-${DEMO_CAMPAIGN}`,\n    action: { type: 'campaignSelected', id: DEMO_CAMPAIGN },\n  },\n];\n\nconst FINISHED = restingOf(INITIAL, SCRIPT, reducer);\n\n/** Under reduced motion the page rests on six months, sorted by leads, with one campaign found in the table. */\nexport const RESTING: MarketingState = { ...FINISHED, spoken: '' };\n\nexport const LOOP_AFTER_MS = 3500;\n",
      "type": "registry:component",
      "target": "components/templates/application-16/session.ts"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/traffic-line.tsx",
      "content": "'use client';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\n\nimport { ChartCard } from './chart-card';\nimport {\n  areaPathOf,\n  GRID_STEPS,\n  linePathOf,\n  niceScaleOf,\n  pointsOf,\n  shareOf,\n  VIEW_WIDTH,\n} from './chart-math';\nimport { COMPACT_FORMAT, COUNT_FORMAT, formatCount } from './format';\nimport { MorphPath } from './morph-path';\nimport { TRAFFIC_POINTS, type PeriodData } from './period-data';\nimport { useReading } from './use-reading';\n\nconst PLOT_HEIGHT = 176;\n\nconst MIDDLE_POINT = Math.floor(TRAFFIC_POINTS / 2);\n\nconst LINE_STROKE =\n  'fill-none stroke-2 [stroke-linecap:round] [stroke-linejoin:round]';\n\nfunction gridTopOf(step: number) {\n  const share = step / GRID_STEPS;\n  return PLOT_HEIGHT - share * PLOT_HEIGHT;\n}\n\nfunction readoutClassOf(isReading: boolean) {\n  if (isReading) {\n    return 'opacity-100';\n  }\n  return 'opacity-0';\n}\n\nconst GRID_STEP_LIST = Array.from(\n  { length: GRID_STEPS + 1 },\n  (_, step) => step\n);\n\nfunction readingCaptionOf(\n  isReading: boolean,\n  data: PeriodData,\n  label: string,\n  current: number,\n  previous: number\n) {\n  if (!isReading) {\n    return data.visitsChange;\n  }\n  return `${label}: ${formatCount(current)} a day, ${formatCount(previous)} before`;\n}\n\ntype TrafficLineProps = {\n  data: PeriodData;\n};\n\nexport function TrafficLine({ data }: TrafficLineProps) {\n  const reading = useReading(TRAFFIC_POINTS, 'point');\n  const largest = Math.max(...data.traffic, ...data.previousTraffic);\n  const scale = niceScaleOf(largest);\n  const currentPoints = pointsOf(data.traffic, scale.max, PLOT_HEIGHT);\n  const previousPoints = pointsOf(data.previousTraffic, scale.max, PLOT_HEIGHT);\n  const index = reading.shownIndex;\n  const current = Math.round(data.traffic[index]);\n  const previous = Math.round(data.previousTraffic[index]);\n  const label = data.bucketLabels[index];\n  const caption = readingCaptionOf(\n    reading.isReading,\n    data,\n    label,\n    current,\n    previous\n  );\n  const guideShare = index / (TRAFFIC_POINTS - 1);\n  const currentTop = PLOT_HEIGHT - shareOf(current, scale.max) * PLOT_HEIGHT;\n  const previousTop = PLOT_HEIGHT - shareOf(previous, scale.max) * PLOT_HEIGHT;\n  const spoken = `${label}, ${formatCount(current)} visits a day, ${formatCount(previous)} in the period before`;\n  const referenceLabel = `The ${data.months} months before`;\n\n  return (\n    <ChartCard\n      title='Traffic'\n      section='traffic'\n      description={\n        <p className='text-muted-foreground text-xs'>Average visits per day</p>\n      }\n    >\n      <div className='flex flex-col gap-1'>\n        <p className='flex items-baseline gap-1.5'>\n          <MotionNumber\n            value={data.totalVisits}\n            format={COUNT_FORMAT}\n            className='text-2xl leading-8 font-semibold'\n          />\n          <span className='text-muted-foreground text-[13px]'>visits</span>\n        </p>\n        {!reading.isReading && (\n          <Swap swapKey={caption} className='text-muted-foreground text-xs'>\n            {caption}\n          </Swap>\n        )}\n        {reading.isReading && (\n          <p className='text-muted-foreground text-xs'>{caption}</p>\n        )}\n      </div>\n      <div className='grid grid-cols-[auto_minmax(0,1fr)] gap-x-2'>\n        <div\n          aria-hidden='true'\n          className='relative w-9 shrink-0'\n          style={{ height: PLOT_HEIGHT }}\n        >\n          {GRID_STEP_LIST.map((step) => (\n            <span\n              key={step}\n              className='text-muted-foreground absolute right-0 -translate-y-1/2 text-[11px]'\n              style={{ top: gridTopOf(step) }}\n            >\n              <MotionNumber value={scale.ticks[step]} format={COMPACT_FORMAT} />\n            </span>\n          ))}\n        </div>\n        <div\n          role='slider'\n          tabIndex={0}\n          aria-label='Visits per day. The arrow keys read each point'\n          aria-orientation='horizontal'\n          aria-valuemin={0}\n          aria-valuemax={TRAFFIC_POINTS - 1}\n          aria-valuenow={index}\n          aria-valuetext={spoken}\n          className='focus-visible:ring-ring/25 @container relative touch-pan-y rounded-md outline-none focus-visible:ring-[3px]'\n          style={{ height: PLOT_HEIGHT }}\n          {...reading.handlers}\n        >\n          {GRID_STEP_LIST.map((step) => (\n            <span\n              key={step}\n              aria-hidden='true'\n              className='hairline-t border-border pointer-events-none absolute inset-x-0'\n              style={{ top: gridTopOf(step) }}\n            />\n          ))}\n          <svg\n            aria-hidden='true'\n            viewBox={`0 0 ${VIEW_WIDTH} ${PLOT_HEIGHT}`}\n            preserveAspectRatio='none'\n            className='pointer-events-none absolute inset-0 size-full overflow-visible'\n          >\n            <MorphPath\n              d={areaPathOf(currentPoints, PLOT_HEIGHT)}\n              className='fill-primary/10'\n            />\n            <MorphPath\n              d={linePathOf(previousPoints)}\n              className={cn(\n                LINE_STROKE,\n                'stroke-foreground/40 [stroke-dasharray:4_4]'\n              )}\n            />\n            <MorphPath\n              d={linePathOf(currentPoints)}\n              className={cn(LINE_STROKE, 'stroke-primary')}\n            />\n          </svg>\n          <div\n            aria-hidden='true'\n            className={cn(\n              'pointer-events-none absolute inset-y-0 left-0 w-0 transition-[opacity,transform] duration-150 ease-(--ease-out-strong)',\n              readoutClassOf(reading.isReading)\n            )}\n            style={{ transform: `translateX(${guideShare * 100}cqw)` }}\n          >\n            <span className='bg-foreground/15 absolute inset-y-0 w-px -translate-x-1/2' />\n            <span\n              className='bg-foreground/40 ring-card absolute size-2 -translate-x-1/2 -translate-y-1/2 rounded-full ring-2'\n              style={{ top: previousTop }}\n            />\n            <span\n              className='bg-primary ring-card absolute size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full ring-2'\n              style={{ top: currentTop }}\n            />\n          </div>\n        </div>\n        <div\n          aria-hidden='true'\n          className='text-muted-foreground col-start-2 mt-2 flex h-4 justify-between text-[11px] tabular-nums'\n        >\n          <Swap swapKey={data.bucketLabels[0]}>{data.bucketLabels[0]}</Swap>\n          <Swap swapKey={data.bucketLabels[MIDDLE_POINT]}>\n            {data.bucketLabels[MIDDLE_POINT]}\n          </Swap>\n          <Swap swapKey={data.bucketLabels[TRAFFIC_POINTS - 1]}>\n            {data.bucketLabels[TRAFFIC_POINTS - 1]}\n          </Swap>\n        </div>\n      </div>\n      <ul className='text-muted-foreground flex flex-wrap items-center gap-x-4 gap-y-1 text-xs'>\n        <li className='flex items-center gap-1.5'>\n          <span\n            aria-hidden='true'\n            className='bg-primary h-0.5 w-4 rounded-full'\n          />\n          This period\n        </li>\n        <li className='flex items-center gap-1.5'>\n          <span\n            aria-hidden='true'\n            className='border-foreground/40 w-4 border-t-2 border-dashed'\n          />\n          <Swap swapKey={referenceLabel}>{referenceLabel}</Swap>\n        </li>\n      </ul>\n    </ChartCard>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/traffic-line.tsx"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/use-reading.ts",
      "content": "'use client';\n\nimport { useState } from 'react';\n\nimport { clamp } from './chart-math';\nimport { rovingTargetOf } from './roving';\n\n/** A line has a point at each edge of its plot; bars have a column each, so a pointer lands on the column under it. */\nexport type ReadingMode = 'point' | 'column';\n\nfunction indexAtOf(ratio: number, count: number, mode: ReadingMode) {\n  const lastIndex = count - 1;\n  if (mode === 'point') {\n    return clamp(Math.round(ratio * lastIndex), 0, lastIndex);\n  }\n  return clamp(Math.floor(ratio * count), 0, lastIndex);\n}\n\n/**\n * What a plot reads out: the position under the pointer or the one the arrow keys reached, and the\n * last position when nobody reads. The plot is the one tab stop of its chart.\n */\nexport function useReading(count: number, mode: ReadingMode) {\n  const [reading, setReading] = useState<number | null>(null);\n  const lastIndex = Math.max(count - 1, 0);\n  const shownIndex = Math.min(reading ?? lastIndex, lastIndex);\n  const isReading = reading !== null;\n\n  function readFromPointer(event: React.PointerEvent<HTMLDivElement>) {\n    const box = event.currentTarget.getBoundingClientRect();\n    const ratio = (event.clientX - box.left) / box.width;\n    setReading(indexAtOf(ratio, count, mode));\n  }\n\n  function readFromKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (event.key === 'Escape') {\n      setReading(null);\n      return;\n    }\n    const next = rovingTargetOf(event.key, shownIndex, count);\n    if (next === null) {\n      return;\n    }\n    event.preventDefault();\n    setReading(next);\n  }\n\n  function stopReading() {\n    setReading(null);\n  }\n\n  return {\n    shownIndex,\n    isReading,\n    handlers: {\n      onPointerMove: readFromPointer,\n      onPointerLeave: stopReading,\n      onKeyDown: readFromKeys,\n      onBlur: stopReading,\n    },\n  };\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/use-reading.ts"
    },
    {
      "path": "registry/ndeko/templates/dashboards/application-16/week-strip.tsx",
      "content": "'use client';\n\nimport { seriesColorOf } from '@/registry/ndeko/lib/agent-run';\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\n\nimport { ChartCard } from './chart-card';\nimport {\n  campaignOf,\n  CAMPAIGNS,\n  channelOf,\n  TODAY_INDEX,\n  WEEK,\n  WEEK_RANGE,\n  type Campaign,\n} from './data';\n\ntype ChipStyle = React.CSSProperties & { '--chip': string };\n\ntype WeekItem = {\n  campaign: Campaign;\n  from: number;\n  to: number;\n  lane: number;\n};\n\ntype Span = {\n  from: number;\n  to: number;\n};\n\nfunction spanOf(campaign: Campaign): Span | null {\n  const { weekFrom, weekTo } = campaign;\n  if (weekFrom === undefined || weekTo === undefined) {\n    return null;\n  }\n  return { from: weekFrom, to: weekTo };\n}\n\n/** Each campaign takes the first row where the one before it has ended, so the strip is as short as it can be. */\nfunction itemsOfWeek() {\n  const items: WeekItem[] = [];\n  const laneEnds: number[] = [];\n  const running = CAMPAIGNS.flatMap((campaign) => {\n    const span = spanOf(campaign);\n    if (span === null) {\n      return [];\n    }\n    return [{ campaign, span }];\n  });\n  const ordered = running.sort((first, second) => {\n    const gap = first.span.from - second.span.from;\n    if (gap !== 0) {\n      return gap;\n    }\n    return second.span.to - first.span.to;\n  });\n  for (const { campaign, span } of ordered) {\n    let lane = laneEnds.findIndex((end) => end < span.from);\n    if (lane === -1) {\n      lane = laneEnds.length;\n    }\n    laneEnds[lane] = span.to;\n    items.push({ campaign, from: span.from, to: span.to, lane });\n  }\n  return items;\n}\n\nconst ITEMS = itemsOfWeek();\n\nconst LANE_COUNT = Math.max(...ITEMS.map((item) => item.lane)) + 1;\n\nfunction todayClassOf(isToday: boolean) {\n  if (isToday) {\n    return 'bg-primary text-primary-foreground';\n  }\n  return undefined;\n}\n\nfunction selectedClassOf(isSelected: boolean) {\n  if (isSelected) {\n    return 'outline-2 outline-offset-2 outline-primary';\n  }\n  return undefined;\n}\n\nfunction spanWordsOf(item: WeekItem) {\n  const first = WEEK[item.from].weekday;\n  const last = WEEK[item.to].weekday;\n  if (first === last) {\n    return first;\n  }\n  return `${first} to ${last}`;\n}\n\nfunction captionOf(selectedId: string | null) {\n  if (selectedId === null) {\n    return 'Select a campaign to find it in the table';\n  }\n  const campaign = campaignOf(selectedId);\n  const item = ITEMS.find((candidate) => candidate.campaign.id === selectedId);\n  const channel = channelOf(campaign.channel);\n  if (!item) {\n    return `${campaign.name}, ${channel.name}`;\n  }\n  return `${campaign.name}, ${channel.name}, ${spanWordsOf(item)}`;\n}\n\ntype WeekStripProps = {\n  selectedId: string | null;\n  pressed: string | null;\n  onSelect: (id: string) => void;\n};\n\nexport function WeekStrip({ selectedId, pressed, onSelect }: WeekStripProps) {\n  const caption = captionOf(selectedId);\n\n  return (\n    <ChartCard\n      title='Campaigns this week'\n      section='week'\n      description={\n        <p className='text-muted-foreground text-xs'>{WEEK_RANGE}</p>\n      }\n    >\n      <div className='relative -mx-1 overflow-x-auto px-1'>\n        <div\n          className='grid min-w-[28rem] grid-cols-7 gap-x-1 gap-y-1'\n          style={{ gridTemplateRows: `auto repeat(${LANE_COUNT}, 1.75rem)` }}\n        >\n          <span\n            aria-hidden='true'\n            className='bg-foreground/[0.04] rounded-lg'\n            style={{\n              gridColumn: TODAY_INDEX + 1,\n              gridRow: `1 / span ${LANE_COUNT + 1}`,\n            }}\n          />\n          {WEEK.map((day) => {\n            const isToday = day.index === TODAY_INDEX;\n            return (\n              <div\n                key={day.index}\n                className='text-muted-foreground relative flex flex-col items-center gap-0.5 py-1 text-xs'\n                style={{ gridColumn: day.index + 1, gridRow: 1 }}\n              >\n                <span>{day.weekday}</span>\n                <span\n                  className={cn(\n                    'inline-flex size-6 items-center justify-center rounded-full text-[13px] font-medium tabular-nums',\n                    todayClassOf(isToday)\n                  )}\n                >\n                  {day.dayOfMonth}\n                </span>\n              </div>\n            );\n          })}\n          {ITEMS.map((item) => {\n            const { campaign } = item;\n            const channel = channelOf(campaign.channel);\n            const isSelected = campaign.id === selectedId;\n            const isPressed = pressed === `campaign-${campaign.id}`;\n            const style: ChipStyle = {\n              '--chip': seriesColorOf(channel.series),\n              gridColumn: `${item.from + 1} / ${item.to + 2}`,\n              gridRow: item.lane + 2,\n            };\n            return (\n              <button\n                key={campaign.id}\n                type='button'\n                aria-pressed={isSelected}\n                aria-label={`${campaign.name}, ${channel.name}, ${spanWordsOf(item)}`}\n                onClick={() => onSelect(campaign.id)}\n                style={style}\n                className={cn(\n                  'chip-3d focus-visible:outline-ring relative flex h-7 min-w-0 cursor-pointer items-center rounded-md px-2 text-start text-xs font-medium transition-[scale] duration-150 ease-(--ease-out-strong) outline-none focus-visible:outline-2 focus-visible:outline-offset-2 active:scale-[0.97]',\n                  selectedClassOf(isSelected),\n                  pressedQuietOf(isPressed)\n                )}\n              >\n                <span className='truncate'>{campaign.name}</span>\n              </button>\n            );\n          })}\n        </div>\n      </div>\n      <Swap swapKey={caption} className='text-muted-foreground min-h-5 text-xs'>\n        {caption}\n      </Swap>\n    </ChartCard>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-16/week-strip.tsx"
    }
  ],
  "categories": [
    "templates",
    "dashboards"
  ],
  "type": "registry:block"
}