{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "gantt-chart",
  "type": "registry:component",
  "title": "Gantt Chart",
  "description": "Tasks as bars along a time axis, one row each, under optional group headings: how far each has got, which must finish before another starts (arrows), milestones as diamonds and a line for today, with Up and Down reading each task.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-scale"
  ],
  "devDependencies": [
    "@types/d3-scale"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/gantt-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/gantt-chart.tsx",
      "content": "\"use client\";\n/**\n * @name gantt-chart\n * @category viz\n * @description Tasks as bars along a time axis, one row each, under optional group headings: how far each has got, which must finish before another starts (arrows), milestones as diamonds and a line for today, with Up and Down reading each task.\n * @when Planning or reporting work over time: a project plan, a release schedule, a timeline of events with lengths. For events without length use timeline (a list) or a line-chart annotation; for a calendar of single days use calendar or calendar-heatmap.\n * @example\n * <GanttChart\n *   label=\"Launch plan\"\n *   tasks={[\n *     { id: \"design\", label: \"Design\", start: \"2026-03-02\", end: \"2026-03-13\", group: \"Product\", progress: 1 },\n *     { id: \"build\", label: \"Build\", start: \"2026-03-09\", end: \"2026-04-03\", group: \"Product\", progress: 0.4, dependsOn: [\"design\"] },\n *     { id: \"launch\", label: \"Launch\", start: \"2026-04-06\", end: \"2026-04-06\", group: \"Marketing\", milestone: true, dependsOn: [\"build\"] },\n *   ]}\n *   today=\"2026-03-20\"\n * />\n */\nimport { scaleUtc } from \"d3-scale\";\nimport { useMemo, type ComponentProps, type KeyboardEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { ChartContainer, ChartEmpty, ChartGrid, chartSeries, ChartSvg, ChartTooltip, dateFormatter, fitText, formatNumber, useChartCursor, widestText, type ChartFormat } from \"@/components/viz/chart\";\n\nexport type GanttTask = {\n  id: string;\n  label: string;\n  /** \"YYYY-MM-DD\", or \"YYYY-MM-DDTHH:mm\" for times (read as UTC unless it carries a zone). */\n  start: string;\n  /** The same form. A day-only end includes that whole day. */\n  end: string;\n  /** Tasks with the same group sit together under its name, in one colour. */\n  group?: string;\n  /** How much is done, 0 to 1. */\n  progress?: number;\n  /** Ids of tasks that must finish before this one starts. */\n  dependsOn?: readonly string[];\n  /** A moment rather than a span: a diamond at `start`. */\n  milestone?: boolean;\n};\n\nexport type GanttChartLabels = {\n  task: string;\n  group: string;\n  start: string;\n  end: string;\n  progress: string;\n  length: (days: number, formatted: string) => string;\n  today: string;\n  after: string;\n  milestone: string;\n};\n\nexport type GanttChartProps = Omit<ComponentProps<\"div\">, \"children\"> &\n  ChartFormat & {\n    tasks: readonly GanttTask[];\n    /** What the chart shows, for assistive technology. */\n    label: string;\n    /** \"YYYY-MM-DD\": a line for today. Left out, none is drawn (the server and the browser may not agree on the date). */\n    today?: string;\n    /** The height of a row in pixels. Default 32. */\n    rowHeight?: number;\n    labels?: Partial<GanttChartLabels>;\n    emptyLabel?: string;\n  };\n\nconst LABELS: GanttChartLabels = {\n  task: \"Task\",\n  group: \"Group\",\n  start: \"Start\",\n  end: \"End\",\n  progress: \"Done\",\n  length: (days, formatted) => `${formatted} ${days === 1 ? \"day\" : \"days\"}`,\n  today: \"Today\",\n  after: \"After\",\n  milestone: \"Milestone\",\n};\nconst DAY = 86400000;\nconst ROUND = \"[rx:min(var(--radius),4px)] [ry:min(var(--radius),4px)]\";\n\nfunction parseMoment(text: string, end: boolean): number | null {\n  if (/^\\d{4}-\\d{2}-\\d{2}$/.test(text)) {\n    const at = Date.parse(`${text}T00:00:00Z`);\n    return Number.isFinite(at) ? at + (end ? DAY : 0) : null;\n  }\n  const at = Date.parse(/[zZ]|[+-]\\d{2}:?\\d{2}$/.test(text) ? text : `${text}Z`);\n  return Number.isFinite(at) ? at : null;\n}\n\ntype Row = { kind: \"group\"; name: string; colour: number } | { kind: \"task\"; task: GanttTask; index: number; from: number; to: number; colour: number };\n\nexport function GanttChart({ tasks, label, today, rowHeight = 32, labels: given, emptyLabel, locale = \"en-US\", timeZone = \"UTC\", className, ...props }: GanttChartProps) {\n  const labels = { ...LABELS, ...given };\n  const model = useMemo(() => {\n    const groups = [...new Set(tasks.map((task) => task.group ?? \"\"))];\n    const rows: Row[] = [];\n    const placed: Extract<Row, { kind: \"task\" }>[] = [];\n    for (const [g, name] of groups.entries()) {\n      const colour = g < 5 ? g : -1;\n      if (name) rows.push({ kind: \"group\", name, colour });\n      for (const task of tasks.filter((item) => (item.group ?? \"\") === name)) {\n        const from = parseMoment(task.start, false);\n        const to = task.milestone ? from : parseMoment(task.end, true);\n        if (from === null || to === null) continue;\n        const row: Extract<Row, { kind: \"task\" }> = { kind: \"task\", task, index: placed.length, from, to: Math.max(from, to), colour };\n        rows.push(row);\n        placed.push(row);\n      }\n    }\n    return { rows, placed };\n  }, [tasks]);\n  const { rows, placed } = model;\n  const cursor = useChartCursor(placed.length);\n  const span = placed.length > 0 ? Math.max(...placed.map((row) => row.to)) - Math.min(...placed.map((row) => row.from)) : 0;\n  const fullDate = dateFormatter(Math.min(span, 300 * DAY), \"full\", locale, timeZone);\n  const axisDate = dateFormatter(span, \"axis\", locale, timeZone);\n  const hasTime = tasks.some((task) => task.start.includes(\"T\") || task.end.includes(\"T\"));\n  const dateText = (at: number, end: boolean): string => fullDate(hasTime || !end ? at : at - DAY);\n  const percent = (share: number): string => formatNumber(share, locale, { style: \"percent\", maximumFractionDigits: 0 });\n  const lengthText = (row: Extract<Row, { kind: \"task\" }>): string => {\n    const days = Math.round(((row.to - row.from) / DAY) * 10) / 10;\n    return labels.length(days, formatNumber(days, locale));\n  };\n  const nameOf = (id: string): string => tasks.find((task) => task.id === id)?.label ?? id;\n  const describe = (row: Extract<Row, { kind: \"task\" }>): { label: string; value: string }[] => [\n    ...(row.task.milestone\n      ? [{ label: labels.milestone, value: dateText(row.from, false) }]\n      : [\n          { label: labels.start, value: dateText(row.from, false) },\n          { label: labels.end, value: dateText(row.to, true) },\n          { label: \"\", value: lengthText(row) },\n        ]),\n    ...(row.task.progress !== undefined ? [{ label: labels.progress, value: percent(row.task.progress) }] : []),\n    ...(row.task.dependsOn && row.task.dependsOn.length > 0 ? [{ label: labels.after, value: row.task.dependsOn.map(nameOf).join(\", \") }] : []),\n  ];\n  const table = {\n    caption: label,\n    columns: [labels.task, labels.group, labels.start, labels.end, labels.progress, labels.after],\n    rows: placed.map((row) => [\n      row.task.label,\n      row.task.group ?? \"\",\n      dateText(row.from, false),\n      row.task.milestone ? labels.milestone : dateText(row.to, true),\n      row.task.progress === undefined ? \"\" : percent(row.task.progress),\n      (row.task.dependsOn ?? []).map(nameOf).join(\", \"),\n    ]),\n  };\n  const current = cursor.active === null ? undefined : placed[cursor.active];\n  const todayAt = today ? parseMoment(today, false) : null;\n  const onKeyDown = (event: KeyboardEvent<SVGSVGElement>): void => {\n    // Rows run down the page, so Up and Down read them; Left and Right do the same for one-handed use.\n    if (event.key === \"ArrowDown\") {\n      event.preventDefault();\n      cursor.select(cursor.active === null ? 0 : cursor.active + 1);\n    } else if (event.key === \"ArrowUp\") {\n      event.preventDefault();\n      cursor.select(cursor.active === null ? placed.length - 1 : cursor.active - 1);\n    } else cursor.svgProps.onKeyDown(event);\n  };\n  const axis = 26;\n  const plotHeight = rows.length * rowHeight + axis + 4;\n\n  return (\n    <div data-slot=\"gantt-chart\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      <ChartContainer\n        height={Math.max(80, plotHeight)}\n        table={table}\n        announcement={\n          cursor.keyboard && current\n            ? `${current.task.label}: ${describe(current)\n                .map((item) => `${item.label} ${item.value}`.trim())\n                .join(\", \")}`\n            : \"\"\n        }\n      >\n        {({ width, height: measured }) => {\n          if (placed.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const left = Math.min(Math.round(width * 0.34), widestText(placed.map((row) => row.task.label)) + 16);\n          const right = 12;\n          const first = Math.min(...placed.map((row) => row.from), ...(todayAt === null ? [] : [todayAt]));\n          const last = Math.max(...placed.map((row) => row.to), ...(todayAt === null ? [] : [todayAt]));\n          const sx = scaleUtc()\n            .domain([first, last === first ? first + DAY : last])\n            .range([left, width - right])\n            .nice();\n          const ticks = sx.ticks(Math.max(2, Math.floor((width - left) / 90)));\n          const yOf = (rowIndex: number): number => axis + rowIndex * rowHeight;\n          const bar = Math.min(18, rowHeight - 10);\n          const rowIndexOf = new Map(placed.map((row) => [row.task.id, rows.indexOf(row)]));\n          const shownRow = current ? rows.indexOf(current) : -1;\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={measured} interactive {...cursor.svgProps} onKeyDown={onKeyDown}>\n                <ChartGrid offsets={ticks.map((tick) => sx(tick))} from={axis} to={measured - 4} vertical />\n                <g aria-hidden=\"true\" className=\"fill-muted-foreground tabular-nums\">\n                  {ticks.map((tick) => (\n                    <text key={tick.getTime()} x={sx(tick)} y={axis - 10} textAnchor=\"middle\">\n                      {axisDate(tick)}\n                    </text>\n                  ))}\n                </g>\n                <g aria-hidden=\"true\">\n                  {rows.map((row, rowIndex) =>\n                    row.kind === \"group\" ? (\n                      <g key={`g:${row.name}`}>\n                        <line x1={0} x2={width} y1={yOf(rowIndex)} y2={yOf(rowIndex)} className=\"stroke-border\" shapeRendering=\"crispEdges\" />\n                        <text x={0} y={yOf(rowIndex) + rowHeight / 2} dy=\"0.32em\" className=\"fill-foreground text-xs font-medium\">\n                          {fitText(row.name, width)}\n                        </text>\n                      </g>\n                    ) : (\n                      <g\n                        key={row.task.id}\n                        onPointerEnter={() => cursor.point(row.index)}\n                        className={cn(\"transition-opacity duration-instant motion-reduce:transition-none\", current && current !== row && \"opacity-55\")}\n                      >\n                        <rect x={0} y={yOf(rowIndex)} width={width} height={rowHeight} fill=\"transparent\" />\n                        <text x={8} y={yOf(rowIndex) + rowHeight / 2} dy=\"0.32em\" className=\"fill-muted-foreground text-xs\">\n                          {fitText(row.task.label, left - 16)}\n                        </text>\n                        {row.task.milestone ? (\n                          <path\n                            d={`M0,${-bar / 2} L${bar / 2},0 L0,${bar / 2} L${-bar / 2},0 Z`}\n                            transform={`translate(${sx(row.from)},${yOf(rowIndex) + rowHeight / 2})`}\n                            className={cn(chartSeries(row.colour).fill, \"stroke-background\")}\n                            strokeWidth={2}\n                          />\n                        ) : (\n                          <>\n                            <rect\n                              x={sx(row.from)}\n                              y={yOf(rowIndex) + (rowHeight - bar) / 2}\n                              width={Math.max(2, sx(row.to) - sx(row.from))}\n                              height={bar}\n                              className={cn(chartSeries(row.colour).fill, ROUND)}\n                              fillOpacity={0.3}\n                            />\n                            <rect\n                              x={sx(row.from)}\n                              y={yOf(rowIndex) + (rowHeight - bar) / 2}\n                              width={Math.max(row.task.progress ? 2 : 0, (sx(row.to) - sx(row.from)) * Math.max(0, Math.min(1, row.task.progress ?? 0)))}\n                              height={bar}\n                              className={cn(chartSeries(row.colour).fill, ROUND)}\n                            />\n                          </>\n                        )}\n                      </g>\n                    ),\n                  )}\n                  {placed.flatMap((row) =>\n                    (row.task.dependsOn ?? []).flatMap((id) => {\n                      const before = placed.find((other) => other.task.id === id);\n                      const fromRow = rowIndexOf.get(id);\n                      const toRow = rowIndexOf.get(row.task.id);\n                      if (!before || fromRow === undefined || toRow === undefined) return [];\n                      const x1 = sx(before.to);\n                      const y1 = yOf(fromRow) + rowHeight / 2;\n                      const x2 = sx(row.from) - (row.task.milestone ? bar / 2 : 0);\n                      const y2 = yOf(toRow) + rowHeight / 2;\n                      const bend = Math.max(x1 + 6, Math.min(x2 - 6, x1 + 10));\n                      return [\n                        <g key={`${id}>${row.task.id}`} className=\"stroke-muted-foreground\" fill=\"none\" strokeWidth={1.25}>\n                          <path d={`M${x1},${y1} H${bend} V${y2} H${x2 - 1}`} />\n                          <path d={`M${x2 - 6},${y2 - 4} L${x2 - 1},${y2} L${x2 - 6},${y2 + 4}`} />\n                        </g>,\n                      ];\n                    }),\n                  )}\n                  {todayAt !== null ? (\n                    <g>\n                      <line x1={sx(todayAt)} x2={sx(todayAt)} y1={axis - 4} y2={measured - 4} className=\"stroke-foreground\" strokeDasharray=\"3 3\" />\n                      <text x={sx(todayAt) + 4} y={measured - 8} className=\"fill-foreground text-xs\">\n                        {labels.today}\n                      </text>\n                    </g>\n                  ) : null}\n                  {current && shownRow >= 0 ? (\n                    <rect x={1} y={yOf(shownRow) + 1} width={width - 2} height={rowHeight - 2} fill=\"none\" className={cn(\"stroke-foreground\", ROUND)} strokeWidth={2} />\n                  ) : null}\n                </g>\n              </ChartSvg>\n              {current && shownRow >= 0 ? (\n                <ChartTooltip\n                  x={Math.min(width - 20, sx(current.to))}\n                  y={yOf(shownRow) + rowHeight / 2}\n                  side={sx(current.to) > width * 0.6 ? \"left\" : \"right\"}\n                  title={current.task.label}\n                  rows={describe(current)}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Planning or reporting work over time: a project plan, a release schedule, a timeline of events with lengths. For events without length use timeline (a list) or a line-chart annotation; for a calendar of single days use calendar or calendar-heatmap.",
    "example": "<GanttChart\n  label=\"Launch plan\"\n  tasks={[\n    { id: \"design\", label: \"Design\", start: \"2026-03-02\", end: \"2026-03-13\", group: \"Product\", progress: 1 },\n    { id: \"build\", label: \"Build\", start: \"2026-03-09\", end: \"2026-04-03\", group: \"Product\", progress: 0.4, dependsOn: [\"design\"] },\n    { id: \"launch\", label: \"Launch\", start: \"2026-04-06\", end: \"2026-04-06\", group: \"Marketing\", milestone: true, dependsOn: [\"build\"] },\n  ]}\n  today=\"2026-03-20\"\n/>",
    "client": true
  }
}
