{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "timeline",
  "title": "Timeline",
  "description": "Primitives for timelines on recharts: a UTC date scale, week, month and quarter ticks, days between dates, done, in progress, planned and at risk statuses each with an icon and label, an axis tick, a today label, a chart of dated rows with tooltips, and a Gantt-style timeline with grouped rows and progress fills.",
  "dependencies": [
    "recharts"
  ],
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/chart.json",
    "https://www.dashboardblocks.com/r/radix/status-label.json",
    "https://www.dashboardblocks.com/r/radix/details.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/timeline.tsx",
      "content": "'use client'\n\nimport {\n  BlockStateRows,\n  useBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport {\n  ChartPlaceholder,\n  ChartTooltipFrame,\n  useChartId,\n  chartTimeGridProps,\n} from '@/registry/components/dashboardblocks/chart'\nimport { Details } from '@/registry/components/dashboardblocks/details'\nimport {\n  StatusLabel,\n  type StatusTone,\n} from '@/registry/components/dashboardblocks/status-label'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport {\n  formatDate,\n  formatDateRange,\n  formatPercent,\n} from '@/registry/lib/dashboardblocks/format'\nimport type { ReactNode } from 'react'\nimport {\n  Bar,\n  BarChart,\n  CartesianGrid,\n  ReferenceLine,\n  ResponsiveContainer,\n  Tooltip,\n  XAxis,\n  YAxis,\n} from 'recharts'\n\nimport { cn } from '@/lib/utils'\n\nconst DAY = 86_400_000\n\ntype TimelineUnit = 'week' | 'month' | 'quarter'\n\nfunction getTimelineScale(start: Date, end: Date) {\n  const from = start.getTime()\n  const span = Math.max(DAY, end.getTime() - from)\n  return (date: Date) =>\n    Math.min(100, Math.max(0, ((date.getTime() - from) / span) * 100))\n}\n\nfunction getTimelineTicks(start: Date, end: Date, unit: TimelineUnit) {\n  const ticks: Date[] = []\n  let cursor: Date\n  if (unit === 'week') {\n    const weekday = (start.getUTCDay() + 6) % 7\n    cursor = new Date(\n      Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate() - weekday),\n    )\n    if (cursor < start) cursor = new Date(cursor.getTime() + 7 * DAY)\n  } else {\n    const step = unit === 'quarter' ? 3 : 1\n    const month = Math.ceil(start.getUTCMonth() / step) * step\n    cursor = new Date(Date.UTC(start.getUTCFullYear(), month, 1))\n    if (cursor < start)\n      cursor = new Date(Date.UTC(start.getUTCFullYear(), month + step, 1))\n  }\n  while (cursor <= end) {\n    ticks.push(cursor)\n    cursor =\n      unit === 'week'\n        ? new Date(cursor.getTime() + 7 * DAY)\n        : new Date(\n            Date.UTC(\n              cursor.getUTCFullYear(),\n              cursor.getUTCMonth() + (unit === 'quarter' ? 3 : 1),\n              1,\n            ),\n          )\n  }\n  return ticks\n}\n\nfunction getDaysBetween(from: Date, to: Date) {\n  const utc = (date: Date) =>\n    Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate())\n  return Math.round((utc(to) - utc(from)) / DAY)\n}\n\nfunction formatTimelineDate(date: Date) {\n  return formatDate(date, 'day')\n}\n\nfunction formatTimelineRange(start: Date, end: Date) {\n  return formatDateRange({ end, start })\n}\n\ntype TimelineStatus = 'done' | 'in-progress' | 'planned' | 'at-risk'\n\nconst timelineStatusConfig: Record<\n  TimelineStatus,\n  { icon: ReactNode; label: string; tone: StatusTone }\n> = {\n  'at-risk': {\n    icon: (\n      <IconPlaceholder\n        lucide='TriangleAlertIcon'\n        tabler='IconAlertTriangle'\n        hugeicons='Alert02Icon'\n        phosphor='WarningIcon'\n        remixicon='RiErrorWarningLine'\n        aria-hidden\n      />\n    ),\n    label: 'At risk',\n    tone: 'warning',\n  },\n  done: {\n    icon: (\n      <IconPlaceholder\n        lucide='CircleCheckIcon'\n        tabler='IconCircleCheck'\n        hugeicons='CheckmarkCircle02Icon'\n        phosphor='CheckCircleIcon'\n        remixicon='RiCheckboxCircleLine'\n        aria-hidden\n      />\n    ),\n    label: 'Done',\n    tone: 'good',\n  },\n  'in-progress': {\n    icon: (\n      <IconPlaceholder\n        lucide='CircleDotIcon'\n        tabler='IconCircleDot'\n        hugeicons='RecordIcon'\n        phosphor='RecordIcon'\n        remixicon='RiRecordCircleLine'\n        aria-hidden\n      />\n    ),\n    label: 'In progress',\n    tone: 'info',\n  },\n  planned: {\n    icon: (\n      <IconPlaceholder\n        lucide='CircleDashedIcon'\n        tabler='IconCircleDashed'\n        hugeicons='DashedLineCircleIcon'\n        phosphor='CircleDashedIcon'\n        remixicon='RiLoaderLine'\n        aria-hidden\n      />\n    ),\n    label: 'Planned',\n    tone: 'neutral',\n  },\n}\n\nfunction TimelineStatusLabel({\n  className,\n  showLabel = false,\n  status,\n}: {\n  className?: string\n  showLabel?: boolean\n  status: TimelineStatus\n}) {\n  const config = timelineStatusConfig[status]\n  return (\n    <StatusLabel\n      className={cn(\n        'inline-flex items-center gap-1 text-xs [&_svg]:size-3.5 [&_svg]:shrink-0',\n        className,\n      )}\n      tone={config.tone}\n      variant='text'\n    >\n      {config.icon}\n      <span className={cn(!showLabel && 'sr-only')}>{config.label}</span>\n    </StatusLabel>\n  )\n}\n\nconst formatMonth = (date: Date) => formatDate(date, 'month')\n\nconst TIMELINE_AXIS_HEIGHT = 20\nconst TIMELINE_NOW_Z_INDEX = 550\n\ninterface TimelineAxisTickProps {\n  format?: (date: Date) => string\n  payload?: { value: number }\n  x?: number\n}\n\nfunction TimelineAxisTick({\n  format = formatMonth,\n  payload,\n  x = 0,\n}: TimelineAxisTickProps) {\n  if (!payload) return null\n  return (\n    <g>\n      <line stroke='var(--color-border)' x1={x} x2={x} y1={0} y2={TIMELINE_AXIS_HEIGHT} />\n      <text fill='var(--color-muted-foreground)' fontSize={11} x={x + 4} y={14}>\n        {format(new Date(payload.value))}\n      </text>\n    </g>\n  )\n}\n\ninterface TimelineNowLabelProps {\n  label: string\n  viewBox?: { x?: number }\n}\n\nfunction TimelineNowLabel({ label, viewBox }: TimelineNowLabelProps) {\n  const x = viewBox?.x ?? 0\n  const width = label.length * 6 + 8\n  return (\n    <g>\n      <rect\n        fill='var(--color-foreground)'\n        height={16}\n        rx={3}\n        width={width}\n        x={x - width / 2}\n        y={2}\n      />\n      <text\n        fill='var(--color-background)'\n        fontSize={10}\n        fontWeight={500}\n        textAnchor='middle'\n        x={x}\n        y={13}\n      >\n        {label}\n      </text>\n    </g>\n  )\n}\n\ninterface TimelineBand {\n  active: boolean\n  height: number\n  index: number\n  /** Maps a date to its position across the chart, in pixels. */\n  x: (date: Date) => number\n  y: number\n}\n\ninterface TimelineChartProps<Row> {\n  className?: string\n  end: Date\n  /** @default month names, e.g. \"Sep\" */\n  formatTick?: (date: Date) => string\n  now?: Date\n  /** @default 'Today' */\n  nowLabel?: string\n  /** Draws a row's bars inside its band, in SVG. */\n  renderRow: (row: Row, band: TimelineBand) => ReactNode\n  /** In pixels; match it in any column drawn beside the chart. */\n  rowHeight: number\n  rows: Row[]\n  start: Date\n  ticks: Date[]\n  /** The hovered row's tooltip, or `null` for none. */\n  tooltip: (row: Row) => ReactNode\n}\n\ninterface TimelineBarShapeProps {\n  height?: number\n  index?: number\n  payload?: { row: unknown }\n  width?: number\n  x?: number\n  y?: number\n}\n\nfunction TimelineChart<Row>({\n  className,\n  end,\n  formatTick,\n  now,\n  nowLabel = 'Today',\n  renderRow,\n  rowHeight,\n  rows,\n  start,\n  ticks,\n  tooltip,\n}: TimelineChartProps<Row>) {\n  const from = start.getTime()\n  const to = Math.max(from + DAY, end.getTime())\n  const data = rows.map((row, index) => ({ index, range: [from, to], row }))\n  const shape =\n    (active: boolean) =>\n    ({\n      height = 0,\n      index = 0,\n      payload,\n      width = 0,\n      x = 0,\n      y = 0,\n    }: TimelineBarShapeProps) => (\n      <g>\n        {payload &&\n          renderRow(payload.row as Row, {\n            active,\n            height,\n            index,\n            x: (date) => x + ((date.getTime() - from) / (to - from)) * width,\n            y,\n          })}\n      </g>\n    )\n\n  return (\n    <div\n      aria-hidden\n      className={cn('w-full', className)}\n      style={{ height: TIMELINE_AXIS_HEIGHT + rows.length * rowHeight }}\n    >\n      <ResponsiveContainer height='100%' width='100%'>\n        <BarChart\n          accessibilityLayer={false}\n          barCategoryGap={0}\n          data={data}\n          layout='vertical'\n          margin={{ bottom: 0, left: 0, right: 0, top: 0 }}\n        >\n          <CartesianGrid {...chartTimeGridProps} />\n          <XAxis\n            allowDataOverflow\n            axisLine={false}\n            domain={[from, to]}\n            height={TIMELINE_AXIS_HEIGHT}\n            interval={0}\n            orientation='top'\n            tick={<TimelineAxisTick format={formatTick} />}\n            tickLine={false}\n            ticks={ticks.map((tick) => tick.getTime())}\n            type='number'\n          />\n          <YAxis dataKey='index' hide type='category' />\n          <Tooltip\n            content={({ active, payload }) => {\n              const row = payload?.[0]?.payload?.row as Row | undefined\n              const body = active && row !== undefined ? tooltip(row) : null\n              return body ? <ChartTooltipFrame>{body}</ChartTooltipFrame> : null\n            }}\n            cursor={false}\n          />\n          <Bar\n            activeBar={shape(true)}\n            dataKey='range'\n            isAnimationActive={false}\n            shape={shape(false)}\n          />\n          {now && now >= start && now <= end && (\n            <ReferenceLine\n              ifOverflow='hidden'\n              label={<TimelineNowLabel label={nowLabel} />}\n              stroke='var(--color-foreground)'\n              x={now.getTime()}\n              zIndex={TIMELINE_NOW_Z_INDEX}\n            />\n          )}\n        </BarChart>\n      </ResponsiveContainer>\n    </div>\n  )\n}\n\ninterface TimelineItem {\n  /** @default 'var(--color-chart-2)' */\n  color?: string\n  end: Date\n  /** Names a group; consecutive items with the same group sit under one heading. */\n  group?: string\n  id: string\n  label: string\n  /** Share done, 0–1. */\n  progress?: number\n  start: Date\n  status?: TimelineStatus\n}\n\ninterface TimelineProps {\n  /** A note under the chart. */\n  children?: ReactNode\n  className?: string\n  describe?: (item: TimelineItem) => string\n  end: Date\n  formatTick?: (date: Date) => string\n  items: TimelineItem[]\n  /** Names the sideways scroll region `minWidth` adds. @default 'Timeline' */\n  label?: string\n  /** Keeps bars legible in narrow containers: below this width the track scrolls sideways. */\n  minWidth?: string\n  now?: Date\n  /** How many rows to sketch while loading. @default 6 */\n  placeholderRows?: number\n  start: Date\n  /** @default 'month' */\n  unit?: TimelineUnit\n}\n\nconst TIMELINE_ROW_HEIGHT = 32\nconst TIMELINE_BAR_INSET = 6\nconst TIMELINE_MIN_BAR_WIDTH = 6\n\nconst formatProgress = (share: number) =>\n  formatPercent(share, { maximumFractionDigits: 0 })\n\ntype TimelineRow = { group: string; kind: 'group' } | { item: TimelineItem; kind: 'item' }\n\nfunction TimelineItemTooltip({ item }: { item: TimelineItem }) {\n  return (\n    <>\n      <span className='font-medium'>{item.label}</span>\n      <span className='text-muted-foreground tabular-nums'>\n        {formatTimelineRange(item.start, item.end)}\n      </span>\n      {(item.status || item.progress !== undefined) && (\n        <Details>\n          {item.status && <TimelineStatusLabel showLabel status={item.status} />}\n          {item.progress !== undefined && (\n            <span className='tabular-nums'>{formatProgress(item.progress)} done</span>\n          )}\n        </Details>\n      )}\n    </>\n  )\n}\n\nfunction Timeline({\n  children,\n  className,\n  describe,\n  end,\n  formatTick,\n  items,\n  label = 'Timeline',\n  minWidth,\n  now,\n  placeholderRows = 6,\n  start,\n  unit = 'month',\n}: TimelineProps) {\n  const id = useChartId()\n  const state = useBlockState()\n\n  if (state) {\n    return (\n      <div className={cn('flex flex-col gap-3', className)}>\n        {state === 'loading' ? (\n          <ChartPlaceholder\n            height={TIMELINE_AXIS_HEIGHT + placeholderRows * TIMELINE_ROW_HEIGHT}\n          />\n        ) : (\n          <BlockStateRows />\n        )}\n        {state === 'loading' && children && (\n          <p className='text-muted-foreground text-sm'>{children}</p>\n        )}\n      </div>\n    )\n  }\n\n  const ticks = getTimelineTicks(start, end, unit)\n  const describeItem =\n    describe ??\n    ((item: TimelineItem) =>\n      [\n        `${item.label}: ${formatTimelineRange(item.start, item.end)}`,\n        item.status && timelineStatusConfig[item.status].label.toLowerCase(),\n        item.progress !== undefined && `${formatProgress(item.progress)} done`,\n      ]\n        .filter(Boolean)\n        .join(', '))\n  const rows = items.flatMap<TimelineRow>((item, index) =>\n    item.group && item.group !== items[index - 1]?.group\n      ? [\n          { group: item.group, kind: 'group' },\n          { item, kind: 'item' },\n        ]\n      : [{ item, kind: 'item' }],\n  )\n\n  return (\n    <div className={cn('flex flex-col gap-3', className)}>\n      <div\n        role={minWidth ? 'region' : undefined}\n        aria-label={minWidth ? label : undefined}\n        // oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- a scrolling region must be focusable so keyboard users can reach the columns that don't fit\n        tabIndex={minWidth ? 0 : undefined}\n        className={cn(\n          minWidth &&\n            'focus-visible:ring-ring/50 -my-1 overflow-x-auto py-1 rounded-sm outline-none [scrollbar-width:thin] focus-visible:ring-3',\n        )}\n      >\n        <div\n          className='grid grid-cols-[minmax(6rem,11rem)_minmax(0,1fr)] gap-x-3'\n          style={{ minWidth }}\n        >\n          <ul\n            className={cn(\n              'flex flex-col',\n              minWidth && 'bg-background sticky left-0 z-20',\n            )}\n          >\n            <li aria-hidden style={{ height: TIMELINE_AXIS_HEIGHT }} />\n            {rows.map((row) =>\n              row.kind === 'group' ? (\n                <li\n                  key={`group-${row.group}`}\n                  className='text-muted-foreground flex items-end pb-1 text-xs font-medium'\n                  style={{ height: TIMELINE_ROW_HEIGHT }}\n                >\n                  {row.group}\n                </li>\n              ) : (\n                <li\n                  key={row.item.id}\n                  className='flex min-w-0 items-center gap-1.5 text-sm'\n                  style={{ height: TIMELINE_ROW_HEIGHT }}\n                >\n                  {row.item.status && <TimelineStatusLabel status={row.item.status} />}\n                  <span className='truncate'>{row.item.label}</span>\n                  <span className='sr-only'>, {describeItem(row.item)}</span>\n                </li>\n              ),\n            )}\n          </ul>\n          <TimelineChart\n            end={end}\n            formatTick={formatTick}\n            now={now}\n            renderRow={(row, band) => {\n              if (row.kind === 'group') return null\n              const { item } = row\n              const color = item.color ?? 'var(--color-chart-2)'\n              const planned = item.status === 'planned'\n              const left = band.x(item.start)\n              const width = Math.max(TIMELINE_MIN_BAR_WIDTH, band.x(item.end) - left)\n              const top = band.y + TIMELINE_BAR_INSET\n              const height = band.height - 2 * TIMELINE_BAR_INSET\n              const progress = Math.min(1, Math.max(0, item.progress ?? 0))\n              const key = `${id}-${band.index}`\n              return (\n                <>\n                  <defs>\n                    <clipPath id={`${key}-clip`}>\n                      <rect height={height} rx={6} width={width} x={left} y={top} />\n                    </clipPath>\n                    <linearGradient id={`${key}-fill`} x1='0' x2='1' y1='0' y2='0'>\n                      <stop\n                        offset='0%'\n                        style={{\n                          stopColor: `color-mix(in oklab, ${color} 55%, var(--color-background))`,\n                        }}\n                      />\n                      <stop offset='100%' style={{ stopColor: color }} />\n                    </linearGradient>\n                  </defs>\n                  <rect\n                    height={height}\n                    rx={6}\n                    style={{\n                      fill: `color-mix(in oklab, ${color} ${planned ? 10 : 22}%, var(--color-background))`,\n                      stroke: planned ? 'var(--color-border)' : 'none',\n                    }}\n                    strokeDasharray={planned ? '3 3' : undefined}\n                    width={width}\n                    x={left}\n                    y={top}\n                  />\n                  {progress > 0 && (\n                    <rect\n                      clipPath={`url(#${key}-clip)`}\n                      fill={`url(#${key}-fill)`}\n                      height={height}\n                      width={width * progress}\n                      x={left}\n                      y={top}\n                    />\n                  )}\n                  {band.active && (\n                    <rect\n                      fill='none'\n                      height={height + 4}\n                      rx={8}\n                      stroke='var(--color-foreground)'\n                      strokeWidth={2}\n                      width={width + 4}\n                      x={left - 2}\n                      y={top - 2}\n                    />\n                  )}\n                </>\n              )\n            }}\n            rowHeight={TIMELINE_ROW_HEIGHT}\n            rows={rows}\n            start={start}\n            ticks={ticks}\n            tooltip={(row) =>\n              row.kind === 'group' ? null : describe ? (\n                describe(row.item)\n              ) : (\n                <TimelineItemTooltip item={row.item} />\n              )\n            }\n          />\n        </div>\n      </div>\n      {children && <p className='text-muted-foreground text-sm'>{children}</p>}\n    </div>\n  )\n}\n\nexport {\n  Timeline,\n  TimelineAxisTick,\n  TimelineChart,\n  TimelineNowLabel,\n  TimelineStatusLabel,\n  TIMELINE_AXIS_HEIGHT,\n  TIMELINE_NOW_Z_INDEX,\n  formatTimelineDate,\n  formatTimelineRange,\n  getDaysBetween,\n  getTimelineScale,\n  getTimelineTicks,\n  timelineStatusConfig,\n}\n\nexport type {\n  TimelineAxisTickProps,\n  TimelineBand,\n  TimelineChartProps,\n  TimelineNowLabelProps,\n  TimelineItem,\n  TimelineProps,\n  TimelineStatus,\n  TimelineUnit,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/timeline.tsx"
    }
  ],
  "type": "registry:component"
}
