jengacore.shadcn registry · Tailwind v4 · Radix and Base UI
Components
Charts and graphs · @jengacore/gantt

Gantt

SVG timeline: bars, dependency arrows, a today line, week and month zoom, drag and arrow-key rescheduling through callbacks.

Drag a bar, or focus one and use the arrow keys.

Drag a bar to move it, or its ends to change the start or end date. With the keyboard: focus a bar, then arrows move it a day (Shift: a week), Alt+arrows change its end date. Enter opens it. Dependencies are arrows; a dashed red one is out of order.

  • Phase 1: Onboarding
  • Collect merchant documents
  • Risk review
  • Configure settlement account
  • Phase 2: Go-live
  • Pilot with ten agents
  • Training sessions
  • Full rollout
Phase 1: Onboarding: 12 Oct 2026 to 1 Nov 2026Collect merchant documents, Done: 12 Oct 2026 to 20 Oct 2026; dates lockedRisk review, In progress: 21 Oct 2026 to 27 Oct 2026; waits for Collect merchant documentsConfigure settlement account, Planned: 26 Oct 2026 to 1 Nov 2026; waits for Risk review; starts before Risk review endsPhase 2: Go-live: 2 Nov 2026 to 19 Nov 2026Pilot with ten agents, Planned: 2 Nov 2026 to 11 Nov 2026; waits for Configure settlement accountTraining sessions, Planned: 5 Nov 2026 to 13 Nov 2026; end date not set, estimatedFull rollout, Planned: 12 Nov 2026 to 19 Nov 2026; waits for Pilot with ten agents

Install

terminal
npx shadcn@latest add @jengacore/gantt

Without the namespace configured: npx shadcn@latest add https://ui.jengacore.com/r/<new-york-v4|base-nova>/gantt.json

Registry dependencies

Source

components/jc/gantt.tsx
"use client"

import * as React from "react"

import { cn } from "@/lib/utils"

/** A calendar day, "YYYY-MM-DD". Days, not instants: a bar never shifts with the reader's time zone. */
export type Day = string

export type GanttSpan = { start: Day; end: Day }

export type GanttZoom = "week" | "month"

export type GanttTask = {
  id: string
  title: string
  /** First day of the bar. */
  start: Day
  /** Last day of the bar, inclusive. An end before the start is drawn as one day at the start. */
  end: Day
  /** Ids of the tasks this one waits for: an arrow from the end of each to the start of this one. */
  dependsOn?: readonly string[]
  /** A summary row (a phase or a plan): lighter bar, muted row. */
  group?: boolean
  /** Indent the row label under the group above it. */
  level?: 0 | 1
  tone?: "primary" | "info" | "warning" | "muted"
  /** Read after the id in the bar's accessible name: "In progress". */
  status?: string
  /** Dates are history (done, cancelled): the bar cannot be moved, and says so when someone tries. */
  locked?: boolean
  /** The start was not set and is a fallback (e.g. the created date). */
  startEstimated?: boolean
  /** The end date was not set and is an estimate: the bar is drawn dashed. */
  endEstimated?: boolean
}

const ROW_H = 36
const HEADER_H = 44
const BAR_H = 18
const PX_PER_DAY: Record<GanttZoom, number> = { week: 28, month: 8 }
const EDGE = 7
const MS_PER_DAY = 86_400_000
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

const toTime = (day: Day) => Date.parse(`${day}T00:00:00Z`)
export const addDays = (day: Day, n: number): Day => new Date(toTime(day) + n * MS_PER_DAY).toISOString().slice(0, 10)
export const daysBetween = (from: Day, to: Day) => Math.round((toTime(to) - toTime(from)) / MS_PER_DAY)
/** "5 Oct 2026". */
export const formatDay = (day: Day) => `${Number(day.slice(8, 10))} ${MONTHS[Number(day.slice(5, 7)) - 1]} ${day.slice(0, 4)}`
const shortDay = (day: Day) => `${Number(day.slice(8, 10))} ${MONTHS[Number(day.slice(5, 7)) - 1]}`
const weekday = (day: Day) => new Date(`${day}T00:00:00Z`).getUTCDay()

/** Today as a local calendar day: the line sits on the day the reader is living. */
const localToday = (): Day => {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`
}

const spanOfTask = (t: GanttTask): GanttSpan => ({ start: t.start, end: t.end >= t.start ? t.end : t.start })

type Drag = { id: string; mode: "move" | "start" | "end"; x0: number; delta: number; base: GanttSpan }

const FILL: Record<NonNullable<GanttTask["tone"]>, string> = {
  primary: "var(--primary)",
  info: "var(--info)",
  warning: "var(--warning)",
  muted: "var(--muted-foreground)",
}

/**
 * A Gantt timeline in SVG: bars from start to end, dependency arrows (a dashed red one is out of order), a today line,
 * week or month zoom, and rescheduling by drag or keyboard. Dates only: `onReschedule` decides, and a change it
 * refuses (returns or resolves false) springs back. Keyboard: focus a bar, then arrows move it a day (Shift: a week),
 * Alt+arrows change its end date, Enter calls `onOpen`. Keyboard moves are saved after a short pause, so holding an
 * arrow sends one change, not twenty.
 */
export function Gantt({
  tasks,
  zoom = "week",
  today: todayProp,
  readOnly = false,
  onReschedule,
  onOpen,
  renderLabel,
  label = "Timeline",
  commitDelay = 700,
  className,
}: {
  tasks: readonly GanttTask[]
  zoom?: GanttZoom
  /** Pins the today line (tests, screenshots, another time zone). Defaults to the reader's local day, set after mount. */
  today?: Day
  /** No dragging, no keyboard moves: the bars are still focusable and announce their dates. */
  readOnly?: boolean
  onReschedule?: (task: GanttTask, span: GanttSpan) => boolean | void | Promise<boolean | void>
  onOpen?: (task: GanttTask) => void
  /** The row label left of the chart; defaults to the title. */
  renderLabel?: (task: GanttTask) => React.ReactNode
  /** Accessible name of the timeline region. */
  label?: string
  commitDelay?: number
  className?: string
}) {
  const uid = React.useId().replace(/[^a-zA-Z0-9_-]/g, "")
  const helpId = `gantt-help-${uid}`
  const [localDay, setLocalDay] = React.useState<Day | null>(null)
  React.useEffect(() => setLocalDay(localToday()), [])
  const today = todayProp ?? localDay
  const [overrides, setOverrides] = React.useState<ReadonlyMap<string, GanttSpan>>(new Map())
  // New tasks from the owner settle the optimistic changes they now contain; the others (still saving) stay.
  React.useEffect(
    () =>
      setOverrides((m) => {
        if (m.size === 0) return m
        const byId = new Map(tasks.map((t) => [t.id, spanOfTask(t)]))
        const next = new Map([...m].filter(([id, span]) => {
          const now = byId.get(id)
          return now !== undefined && (now.start !== span.start || now.end !== span.end)
        }))
        return next.size === m.size ? m : next
      }),
    [tasks]
  )
  const [drag, setDrag] = React.useState<Drag | null>(null)
  const [message, setMessage] = React.useState("")
  const scroller = React.useRef<HTMLElement>(null)
  const pending = React.useRef(new Map<string, ReturnType<typeof setTimeout>>())
  // The latest change per task: a late answer to an older change never undoes a newer one.
  const seq = React.useRef(new Map<string, number>())
  React.useEffect(() => {
    const timers = pending.current
    return () => timers.forEach((t) => clearTimeout(t))
  }, [])

  const movable = (t: GanttTask) => !readOnly && !t.locked && Boolean(onReschedule)

  const spanOf = React.useCallback(
    (t: GanttTask): GanttSpan => {
      const base = overrides.get(t.id) ?? spanOfTask(t)
      if (drag?.id !== t.id || drag.delta === 0) return base
      const { delta } = drag
      if (drag.mode === "move") return { start: addDays(drag.base.start, delta), end: addDays(drag.base.end, delta) }
      if (drag.mode === "start") {
        const start = addDays(drag.base.start, delta)
        return { start: start > drag.base.end ? drag.base.end : start, end: drag.base.end }
      }
      const end = addDays(drag.base.end, delta)
      return { start: drag.base.start, end: end < drag.base.start ? drag.base.start : end }
    },
    [overrides, drag]
  )

  const px = PX_PER_DAY[zoom]
  const spans = tasks.map(spanOf)
  const anchor = today ?? spans[0]?.start ?? "2026-01-01"
  const first = addDays([anchor, ...spans.map((s) => s.start)].sort()[0] ?? anchor, zoom === "week" ? -3 : -10)
  const last = addDays([anchor, ...spans.map((s) => s.end)].sort().at(-1) ?? anchor, zoom === "week" ? 6 : 21)
  const days = daysBetween(first, last) + 1
  const width = days * px
  const height = HEADER_H + tasks.length * ROW_H
  const x = (day: Day) => daysBetween(first, day) * px
  const rowIndex = new Map(tasks.map((t, i) => [t.id, i]))
  const range = (s: GanttSpan) => `${formatDay(s.start)} to ${formatDay(s.end)}`

  const commit = React.useCallback(
    async (task: GanttTask, span: GanttSpan) => {
      const before = spanOfTask(task)
      if (span.start === before.start && span.end === before.end) {
        setOverrides((m) => {
          const next = new Map(m)
          next.delete(task.id)
          return next
        })
        return
      }
      setOverrides((m) => new Map(m).set(task.id, span))
      const mine = (seq.current.get(task.id) ?? 0) + 1
      seq.current.set(task.id, mine)
      let ok: boolean | void = true
      try {
        ok = await onReschedule?.(task, span)
      } catch {
        ok = false
      }
      if (ok === false && seq.current.get(task.id) === mine) {
        setOverrides((m) => {
          const next = new Map(m)
          next.delete(task.id)
          return next
        })
        setMessage(`${task.title}: not rescheduled, back to ${range(before)}.`)
      }
    },
    [onReschedule]
  )

  const onPointerDown = (event: React.PointerEvent, task: GanttTask, mode: Drag["mode"]) => {
    // A click focuses the bar, so the arrow keys then move it instead of scrolling the chart.
    ;(event.currentTarget.closest("g[role=button]") as SVGGElement | null)?.focus()
    if (event.button !== 0) return
    if (!movable(task)) {
      if (task.locked) setMessage(`${task.title} is ${task.status?.toLowerCase() ?? "locked"}: its dates are history.`)
      return
    }
    event.preventDefault()
    try {
      ;(event.currentTarget as Element).setPointerCapture(event.pointerId)
    } catch {
      // A pointer the browser no longer tracks: the drag still follows the moves the svg receives.
    }
    setDrag({ id: task.id, mode, x0: event.clientX, delta: 0, base: spanOf(task) })
  }
  const onPointerMove = (event: React.PointerEvent) => {
    if (!drag) return
    const delta = Math.round((event.clientX - drag.x0) / px)
    if (delta !== drag.delta) setDrag({ ...drag, delta })
  }
  const onPointerUp = () => {
    if (!drag) return
    const task = tasks.find((t) => t.id === drag.id)
    setDrag(null)
    if (!task) return
    const span = spanOf(task)
    if (drag.delta !== 0) {
      setMessage(`${task.title}: ${range(span)}.`)
      void commit(task, span)
    }
  }

  /** A cancelled pointer (touch cancel, lost capture) or Escape drops the drag without saving. */
  const cancelDrag = () => {
    if (drag) setDrag(null)
  }

  const onKeyDown = (event: React.KeyboardEvent, task: GanttTask) => {
    if (event.key === "Escape" && drag) {
      event.preventDefault()
      cancelDrag()
      return
    }
    if (event.key === "Enter" && onOpen) {
      event.preventDefault()
      onOpen(task)
      return
    }
    if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return
    event.preventDefault()
    if (!movable(task)) {
      setMessage(task.locked ? `${task.title} is ${task.status?.toLowerCase() ?? "locked"}: its dates are history.` : `${task.title}: ${range(spanOf(task))}. Read only.`)
      return
    }
    const step = (event.key === "ArrowRight" ? 1 : -1) * (event.shiftKey ? 7 : 1)
    const now = overrides.get(task.id) ?? spanOfTask(task)
    const end = addDays(now.end, step)
    const next = event.altKey ? { start: now.start, end: end < now.start ? now.start : end } : { start: addDays(now.start, step), end }
    setOverrides((m) => new Map(m).set(task.id, next))
    setMessage(`${task.title}: ${range(next)}. Saving when you stop.`)
    clearTimeout(pending.current.get(task.id))
    pending.current.set(
      task.id,
      setTimeout(() => {
        pending.current.delete(task.id)
        void commit(task, next)
      }, commitDelay)
    )
  }

  // Open on today, not on the oldest bar. Only when today or the zoom changes: a drag that widens the range must
  // not yank the view back.
  const firstRef = React.useRef(first)
  firstRef.current = first
  React.useEffect(() => {
    if (scroller.current && today) scroller.current.scrollLeft = Math.max(0, daysBetween(firstRef.current, today) * px - 7 * px)
  }, [today, zoom, px])

  if (tasks.length === 0) return null

  const markerId = (bad: boolean) => `gantt-arrow-${bad ? "bad-" : ""}${uid}`

  return (
    <div data-slot="gantt" className={cn("flex flex-col gap-2", className)}>
      <p id={helpId} className="text-[12px] text-muted-foreground">
        {readOnly || !onReschedule
          ? "Read only. Focus a bar to hear its dates."
          : "Drag a bar to move it, or its ends to change the start or end date. With the keyboard: focus a bar, then arrows move it a day (Shift: a week), Alt+arrows change its end date."}
        {onOpen ? " Enter opens it." : ""} Dependencies are arrows; a dashed red one is out of order.
      </p>
      <div className="grid grid-cols-[minmax(160px,280px)_minmax(0,1fr)] overflow-hidden rounded-lg border border-border bg-card contrast:border-input">
        <ul aria-label={`${label}: tasks`} className="border-r border-border" style={{ paddingTop: HEADER_H }}>
          {tasks.map((t) => (
            <li
              key={t.id}
              className={cn("flex items-center gap-2 truncate border-t border-border px-3 text-[13px]", t.group && "bg-muted/60 font-medium", t.level === 1 && "pl-7")}
              style={{ height: ROW_H }}
            >
              {renderLabel ? renderLabel(t) : <span className="truncate">{t.title}</span>}
            </li>
          ))}
        </ul>
        {/* A scrolling region must be reachable by keyboard (axe scrollable-region-focusable). */}
        <section ref={scroller} className="relative overflow-x-auto focus-ring [--focus-offset:-2px] dark:[color-scheme:dark]" tabIndex={0} aria-label={`${label} from ${formatDay(first)} to ${formatDay(last)}`}>
          <svg width={width} height={height} className="block select-none" onPointerMove={onPointerMove}
            onPointerUp={onPointerUp}
            onPointerCancel={cancelDrag}
            onLostPointerCapture={cancelDrag}
            role="group" aria-label={`${label}: bars`}>
            <defs>
              <marker id={markerId(false)} viewBox="0 0 8 8" refX="7" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
                <path d="M0,0 L8,4 L0,8 z" fill="var(--muted-foreground)" />
              </marker>
              <marker id={markerId(true)} viewBox="0 0 8 8" refX="7" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
                <path d="M0,0 L8,4 L0,8 z" fill="var(--destructive)" />
              </marker>
            </defs>
            <Grid first={first} days={days} zoom={zoom} width={width} height={height} rows={tasks.length} px={px} />
            <g aria-hidden>
              {tasks.flatMap((t, i) =>
                (t.dependsOn ?? []).flatMap((dep) => {
                  const j = rowIndex.get(dep)
                  const depTask = j === undefined ? undefined : tasks[j]
                  if (j === undefined || !depTask) return []
                  const from = spans[j] ?? spanOf(depTask)
                  const to = spans[i] ?? spanOf(t)
                  const x1 = x(from.end) + px
                  const y1 = HEADER_H + j * ROW_H + ROW_H / 2
                  const x2 = x(to.start)
                  const y2 = HEADER_H + i * ROW_H + ROW_H / 2
                  const bad = to.start <= from.end
                  const elbow = Math.max(x1 + 6, Math.min(x2 - 6, x1 + 10))
                  return [
                    <path
                      key={`${dep}>${t.id}`}
                      d={`M${x1},${y1} H${elbow} V${y2} H${x2 - 1}`}
                      fill="none"
                      stroke={bad ? "var(--destructive)" : "var(--muted-foreground)"}
                      strokeWidth={1.25}
                      strokeDasharray={bad ? "4 3" : undefined}
                      markerEnd={`url(#${markerId(bad)})`}
                    />,
                  ]
                })
              )}
            </g>
            {tasks.map((t, i) => {
              const span = spans[i] ?? spanOf(t)
              const left = x(span.start)
              const w = (daysBetween(span.start, span.end) + 1) * px
              const y = HEADER_H + i * ROW_H + (ROW_H - BAR_H) / 2
              const canMove = movable(t)
              const fill = FILL[t.locked ? "muted" : (t.tone ?? (t.group ? "info" : "primary"))]
              const waits = (t.dependsOn ?? [])
                .map((d) => tasks[rowIndex.get(d) ?? -1])
                .filter((d): d is GanttTask => Boolean(d))
              const late = waits.filter((d) => (spans[rowIndex.get(d.id) ?? -1]?.end ?? "") >= span.start)
              const name = [
                `${t.title}${t.status ? `, ${t.status}` : ""}: ${range(span)}`,
                t.startEstimated ? "start date not set, estimated" : "",
                t.endEstimated ? "end date not set, estimated" : "",
                waits.length ? `waits for ${waits.map((d) => d.title).join(", ")}` : "",
                late.length ? `starts before ${late.map((d) => d.title).join(", ")} ends` : "",
                !canMove && onReschedule && !readOnly ? "dates locked" : "",
              ]
                .filter(Boolean)
                .join("; ")
              return (
                <g
                  key={t.id}
                  role="button"
                  tabIndex={0}
                  aria-label={name}
                  aria-describedby={helpId}
                  onKeyDown={(e) => onKeyDown(e, t)}
                  onDoubleClick={onOpen ? () => onOpen(t) : undefined}
                  className="outline-none [&:focus-visible>rect.bar]:stroke-foreground [&:focus-visible>rect.bar]:stroke-[3px]"
                >
                  <title>{name}</title>
                  <rect
                    className="bar"
                    x={left}
                    y={y}
                    width={w}
                    height={BAR_H}
                    rx={4}
                    fill={fill}
                    fillOpacity={t.group ? 0.25 : t.locked ? 0.35 : 0.8}
                    stroke={fill}
                    strokeWidth={1}
                    strokeDasharray={t.endEstimated ? "3 2" : undefined}
                    style={{ cursor: canMove ? (drag ? "grabbing" : "grab") : "default", touchAction: canMove ? "none" : undefined }}
                    onPointerDown={(e) => onPointerDown(e, t, "move")}
                   
                  />
                  {canMove && w >= EDGE * 3 ? (
                    <>
                      <rect x={left - 2} y={y} width={EDGE} height={BAR_H} fill="transparent" style={{ cursor: "ew-resize", touchAction: "none" }} onPointerDown={(e) => onPointerDown(e, t, "start")} />
                      <rect x={left + w - EDGE + 2} y={y} width={EDGE} height={BAR_H} fill="transparent" style={{ cursor: "ew-resize", touchAction: "none" }} onPointerDown={(e) => onPointerDown(e, t, "end")} />
                    </>
                  ) : null}
                  {w > 70 || zoom === "week" ? (
                    <text x={left + w + 6} y={y + BAR_H - 5} fontSize={11} fill="var(--muted-foreground)" pointerEvents="none" aria-hidden>
                      {drag?.id === t.id ? range(span) : t.title.length > 48 ? `${t.title.slice(0, 47)}…` : t.title}
                    </text>
                  ) : null}
                </g>
              )
            })}
            {today && today >= first && today <= last ? (
              <g pointerEvents="none" aria-hidden>
                <line x1={x(today) + px / 2} x2={x(today) + px / 2} y1={20} y2={height} stroke="var(--destructive)" strokeWidth={1.5} />
                <text x={x(today) + px / 2 + 4} y={26} fontSize={11} fontWeight={600} fill="var(--destructive)">
                  Today
                </text>
              </g>
            ) : null}
          </svg>
        </section>
      </div>
      <div role="status" aria-live="polite" className="sr-only">
        {message}
      </div>
    </div>
  )
}

/**
 * The day grid and the month and day labels. Memoised: it depends only on the range and the zoom, so a drag, which
 * re-renders the bars every few pixels, does not redraw hundreds of ticks.
 */
const Grid = React.memo(function Grid({
  first,
  days,
  zoom,
  width,
  height,
  rows,
  px,
}: {
  first: Day
  days: number
  zoom: GanttZoom
  width: number
  height: number
  rows: number
  px: number
}) {
  const x = (day: Day) => daysBetween(first, day) * px
  return (
    <g aria-hidden>
      {Array.from({ length: days }, (_, i) => addDays(first, i)).map((day) => {
        const weekend = weekday(day) === 0 || weekday(day) === 6
        const monthStart = day.endsWith("-01")
        const showLabel = zoom === "week" || weekday(day) === 1
        return (
          <g key={day}>
            {zoom === "week" && weekend ? <rect x={x(day)} y={HEADER_H} width={px} height={height - HEADER_H} fill="var(--muted)" opacity={0.6} /> : null}
            <line
              x1={x(day)}
              x2={x(day)}
              y1={monthStart ? 0 : 26}
              y2={showLabel || monthStart ? height : HEADER_H}
              stroke="var(--border)"
              strokeWidth={monthStart ? 1.25 : 0.75}
              opacity={showLabel || monthStart ? 1 : 0.5}
            />
            {monthStart || day === first ? (
              <text x={x(day) + 4} y={14} fontSize={11.5} fontWeight={600} fill="var(--foreground)">
                {MONTHS[Number(day.slice(5, 7)) - 1]} {day.slice(0, 4)}
              </text>
            ) : null}
            {showLabel ? (
              <text x={x(day) + (zoom === "week" ? px / 2 : 3)} y={38} fontSize={11} textAnchor={zoom === "week" ? "middle" : "start"} fill="var(--muted-foreground)">
                {zoom === "week" ? Number(day.slice(8)) : shortDay(day)}
              </text>
            ) : null}
          </g>
        )
      })}
      <line x1={0} x2={width} y1={HEADER_H} y2={HEADER_H} stroke="var(--border)" />
      {Array.from({ length: rows }, (_, i) => HEADER_H + (i + 1) * ROW_H).map((y) => (
        <line key={y} x1={0} x2={width} y1={y} y2={y} stroke="var(--border)" opacity={0.6} />
      ))}
    </g>
  )
})