{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "gantt-timeline",
  "title": "Gantt Timeline",
  "author": "ilinxa",
  "description": "Editable Gantt timeline — per-task bars, collapsible summary rows, milestone diamonds, continuous zoom from hours to quarters, and a today line.",
  "dependencies": [
    "lucide-react@^1.11.0",
    "@tanstack/react-virtual@^3.13.24",
    "@dnd-kit/core@^6.3.1"
  ],
  "registryDependencies": [
    "avatar",
    "badge",
    "button",
    "context-menu",
    "input",
    "separator",
    "skeleton",
    "@ilinxa/task-card"
  ],
  "files": [
    {
      "path": "src/registry/components/data/gantt-timeline/gantt-timeline.tsx",
      "content": "\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport type { GanttTimelineHandle, GanttTimelineProps } from \"./types\";\nimport { GanttTimelineRoot } from \"./parts/gantt-timeline-root\";\nimport { GanttTimelineToolbar } from \"./parts/gantt-timeline-toolbar\";\nimport { GanttTimelineAxis } from \"./parts/gantt-timeline-axis\";\nimport { GanttTimelineGutter } from \"./parts/gantt-timeline-gutter\";\nimport { GanttTimelineBody } from \"./parts/gantt-timeline-body\";\n\n/**\n * Tier A — batteries-included assembly. `Root` + the parts gated by `showToolbar`.\n * Contains no logic the parts don't; a hand-assembly (Root + any subset of parts)\n * gets identical behavior.\n */\nexport const GanttTimeline = forwardRef<\n  GanttTimelineHandle,\n  GanttTimelineProps\n>(function GanttTimeline(props, ref) {\n  const { showToolbar = true, className, data, ...rest } = props;\n\n  if (!data || data.length === 0) {\n    return (\n      <div\n        className={cn(\n          \"flex h-80 flex-col items-center justify-center gap-2 rounded-lg border border-border bg-card px-6 text-center\",\n          className,\n        )}\n      >\n        <p className=\"text-sm font-medium text-foreground\">No tasks to schedule</p>\n        <p className=\"text-xs text-muted-foreground\">\n          Pass a <code className=\"font-mono\">TaskItem[]</code> to{\" \"}\n          <code className=\"font-mono\">data</code> to render the timeline.\n        </p>\n      </div>\n    );\n  }\n\n  return (\n    <GanttTimelineRoot\n      ref={ref}\n      data={data}\n      {...rest}\n      className={cn(\n        \"overflow-hidden rounded-lg border border-border bg-card\",\n        className,\n      )}\n    >\n      {showToolbar ? <GanttTimelineToolbar /> : null}\n      <GanttTimelineAxis />\n      <div className=\"flex h-[clamp(280px,52vh,560px)]\">\n        <GanttTimelineGutter />\n        <GanttTimelineBody />\n      </div>\n    </GanttTimelineRoot>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/gantt-timeline.tsx"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/index.ts",
      "content": "// Assembly (Tier A)\nexport { GanttTimeline } from \"./gantt-timeline\";\n\n// Headless provider + context parts (Tier B) — flat exports, never a namespace\nexport { GanttTimelineRoot } from \"./parts/gantt-timeline-root\";\nexport { GanttTimelineToolbar } from \"./parts/gantt-timeline-toolbar\";\nexport { GanttTimelineAxis } from \"./parts/gantt-timeline-axis\";\nexport { GanttTimelineGutter } from \"./parts/gantt-timeline-gutter\";\nexport { GanttTimelineBody } from \"./parts/gantt-timeline-body\";\n\n// Standalone primitives (Tier C)\nexport {\n  GanttBar,\n  SummaryBar,\n  MilestoneDiamond,\n  TodayLine,\n  BarTooltip,\n} from \"./parts/gantt-bars\";\nexport { AxisHeader } from \"./parts/gantt-timeline-axis\";\nexport { GutterRow } from \"./parts/gantt-timeline-gutter\";\nexport { GanttTimelineSkeleton } from \"./parts/gantt-timeline-skeleton\";\nexport { GanttFullCardTooltip } from \"./parts/bar-tooltip-full\";\n\n// Editing (v0.2.0)\nexport { GanttContextMenu } from \"./parts/gantt-context-menu\";\nexport { GanttEditPopover } from \"./parts/gantt-edit-popover\";\n// Quick-create composer (v0.5.0)\nexport { GanttQuickComposer } from \"./parts/gantt-quick-composer\";\n\n// Hook\nexport { useGanttTimeline } from \"./hooks/use-gantt-context\";\n\n// Public types (+ the consumed task-card data language, re-exported)\nexport type {\n  // `useGanttTimeline()` is exported above and returns GanttContextValue;\n  // GanttRenderItem is the element type of its `renderItems`. Both were\n  // unreachable from this barrel (validate:barrel-exports, 2026-08-17) —\n  // \"internal\" in types.ts means \"constructed by the Root\", not \"private\".\n  GanttContextValue,\n  GanttRenderItem,\n  GanttTimelineProps,\n  GanttTimelineRootProps,\n  GanttTimelineHandle,\n  GanttZoom,\n  GanttTimeUnit,\n  GanttViewport,\n  GanttRow,\n  GanttBarGeometry,\n  GanttBarColor,\n  GanttColorResolver,\n  GanttTooltipRenderer,\n  GanttStatusTone,\n  GanttSnap,\n  GanttEditAction,\n  GanttComposerTarget,\n  GanttQuickComposerRenderer,\n  TaskItem,\n  TaskPerson,\n  TaskStatusOption,\n  TaskPriorityOption,\n  TaskLabelOption,\n  TaskColorRamp,\n  TaskPermissions,\n  TaskPermissionRule,\n  TaskItemAddedEvent,\n  TaskItemRemovedEvent,\n  TaskItemMovedEvent,\n  TaskFieldEditedEvent,\n  TaskStatusChangedEvent,\n} from \"./types\";\n\n// @ilinxa/gantt-timeline 0.7.2\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/index.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/types.ts",
      "content": "/**\n * Public + internal types for the gantt-timeline pro-component.\n *\n * v0.1.0 surface — read-only, fully-navigable project timeline over the\n * canonical `TaskItem[]`. Bars from effective start→end, WBS summary rows from\n * `children`, milestone diamonds, continuous-zoom two-tier axis, pan/swipe/zoom\n * canvas, filled status/urgency bars (ramp imported from task-card).\n *\n * Architecture: shadcn-style compound (Root provider + flat parts + Tier-C\n * primitives + assembly). State model architected so v2 drag-to-reschedule\n * drops in additively. See docs/procomps/gantt-timeline-procomp/.\n */\n\nimport type { ReactNode, RefObject } from \"react\";\nimport type {\n  TaskItem,\n  TaskPerson,\n  TaskStatusOption,\n  TaskPriorityOption,\n  TaskLabelOption,\n  TaskColorRamp,\n  TaskPermissions,\n  TaskPermissionRule,\n  TaskPermissionReason,\n  TaskItemAddedEvent,\n  TaskItemRemovedEvent,\n  TaskItemMovedEvent,\n  TaskFieldEditedEvent,\n  TaskStatusChangedEvent,\n} from \"../task-card\";\n\n// Re-export the consumed data + editing language (v0.2.0) so a consumer importing\n// the gantt gets the item, option, permission, and event types without a second\n// import (same-category barrel import; rewriter-safe).\nexport type {\n  TaskItem,\n  TaskPerson,\n  TaskStatusOption,\n  TaskPriorityOption,\n  TaskLabelOption,\n  TaskColorRamp,\n  TaskPermissions,\n  TaskPermissionRule,\n  TaskPermissionReason,\n  TaskItemAddedEvent,\n  TaskItemRemovedEvent,\n  TaskItemMovedEvent,\n  TaskFieldEditedEvent,\n  TaskStatusChangedEvent,\n};\n\n/* ───────── zoom + time ───────── */\n\nexport type GanttZoom = \"hour\" | \"day\" | \"week\" | \"month\" | \"quarter\";\n\nexport type GanttTimeUnit =\n  | \"hour\"\n  | \"day\"\n  | \"week\"\n  | \"month\"\n  | \"quarter\"\n  | \"year\";\n\n/** Linear map epoch-ms → x-pixels: `x(t) = (t - originMs) * pxPerMs`. */\nexport type GanttViewport = { originMs: number; pxPerMs: number };\n\nexport type GanttStatusTone = \"active\" | \"done\" | \"blocked\";\n\n/* ───────── editing (v0.2.0) ───────── */\n\n/** Snap granularity for drag / resize / create; default `\"minor\"` (active axis unit). */\nexport type GanttSnap = \"minor\" | \"hour\" | \"day\" | \"week\" | \"off\" | number;\n\n/** The edit actions the permission matrix gates. */\nexport type GanttEditAction =\n  | \"move\"\n  | \"resize\"\n  | \"delete\"\n  | \"create\"\n  | \"editDetails\";\n\n/**\n * v0.5.0 — a pending quick-create. Set when a double-click on an empty row area\n * requests a new task; the composer floats at (x,y) until commit/cancel.\n */\nexport type GanttComposerTarget = {\n  /** Anchor start (epoch-ms) for the new task. */\n  startMs: number;\n  /** Default end (epoch-ms); the composer seeds `expireAt` from it. */\n  endMs?: number;\n  /** Insert under this parent (null = root). */\n  parentId: string | null;\n  /** Insert index among siblings. */\n  index: number;\n  /** Pointer anchor for the floating panel. */\n  x?: number;\n  y?: number;\n};\n\n/** v0.5.0 — override the quick-composer UI (parity with calendar). */\nexport type GanttQuickComposerRenderer = (args: {\n  startMs: number;\n  endMs?: number;\n  commit: (seed?: Partial<TaskItem>) => void;\n  cancel: () => void;\n  openFull: () => void;\n}) => ReactNode;\n\n/* ───────── derived row + geometry ───────── */\n\n/** A flattened, currently-visible row (respects collapse). */\nexport type GanttRow = {\n  item: TaskItem;\n  /** 0 = top-level. */\n  depth: number;\n  parentId: string | null;\n  hasChildren: boolean;\n  /** A parent renders a summary bar. */\n  isSummary: boolean;\n  collapsed: boolean;\n  /** 1-based position among same-parent siblings (for `aria-posinset`). */\n  posInSet: number;\n  /** Sibling count under the same parent (for `aria-setsize`). */\n  setSize: number;\n};\n\n/** Resolved bar geometry for one item. `endMs === null` ⇒ milestone. */\nexport type GanttBarGeometry = {\n  startMs: number;\n  endMs: number | null;\n  isMilestone: boolean;\n  isOverdue: boolean;\n};\n\n/** Resolved fill for a bar. */\nexport type GanttBarColor = {\n  fill: string;\n  tone: GanttStatusTone;\n  isOverdue: boolean;\n};\n\nexport type GanttColorResolver = (item: TaskItem) => GanttBarColor;\n\nexport type GanttTooltipRenderer = (item: TaskItem) => ReactNode;\n\n/* ───────── component props ───────── */\n\nexport type GanttTimelineProps = {\n  /** The tasks to lay out. The canonical `TaskItem[]` the card/tree render. */\n  data: TaskItem[];\n\n  // Color + label language (shared with task-card)\n  statusOptions?: TaskStatusOption[];\n  priorityOptions?: TaskPriorityOption[];\n  labelOptions?: TaskLabelOption[];\n  /** Same urgency ramp the card uses; default `\"default\"`. */\n  colorRamp?: TaskColorRamp;\n  /** ms; default 60_000; 0 disables the refresh tick. */\n  colorRefreshIntervalMs?: number;\n\n  // Time axis (continuous zoom; named levels are header-scale buckets)\n  zoom?: GanttZoom; // controlled (nearest named level)\n  defaultZoom?: GanttZoom; // uncontrolled (default \"week\")\n  onZoomChange?: (zoom: GanttZoom) => void;\n  /** Clamp the continuous zoom; default span hour…quarter. */\n  minZoom?: GanttZoom;\n  maxZoom?: GanttZoom;\n  /** Fires (rAF-throttled) when the viewport pans/zooms. */\n  onViewportChange?: (window: { from: string; to: string }) => void;\n  /** Opt out of gesture nav; +/−/fit buttons + keyboard still work. */\n  disableGestures?: boolean;\n  /** Initial visible window; defaults to fit-all-bars + padding. */\n  range?: { from: string; to: string };\n  /** Frozen clock for SSR/testing; drives the \"now\" line + urgency. */\n  now?: Date | (() => Date);\n\n  // Layout\n  rowHeight?: number; // px; default 36\n  gutterWidth?: number; // px; default 280\n  showWeekendShading?: boolean; // default false\n  showToolbar?: boolean; // assembly toggle; default true\n\n  // Collapse (UI-only)\n  defaultCollapsedIds?: string[];\n  collapsedIds?: string[]; // controlled\n  onCollapsedChange?: (ids: string[]) => void;\n\n  // Read-only interactions\n  selectedId?: string | null;\n  onSelect?: (itemId: string | null) => void;\n  onTaskClick?: (item: TaskItem) => void;\n  /** Override the hover tooltip; default = lightweight summary. */\n  renderTooltip?: GanttTooltipRenderer;\n\n  // ── Editing (v0.2.0) — all opt-in; default surface is the v1 read-only Gantt ──\n  /** Master switch. Default false → byte-identical v1 read-only behavior. */\n  editable?: boolean;\n  /** The full mutated forest after ANY edit; controlled consumer echoes into `data`. */\n  onChange?: (data: TaskItem[]) => void;\n  /** Snap granularity for drags/resizes/create; default \"minor\"; Alt = free-drag. */\n  snap?: GanttSnap;\n\n  /**\n   * v0.5.0 — when true (default while editable), double-clicking an empty row area\n   * opens a quick mini-composer; false → creates immediately + opens the full editor.\n   */\n  quickCompose?: boolean;\n  /** v0.5.0 — override the quick-composer UI. */\n  renderQuickComposer?: GanttQuickComposerRenderer;\n\n  /** Bar move/resize sugar — kept from v1; fires alongside onChange/onFieldEdited. */\n  onTaskReschedule?: (next: {\n    itemId: string;\n    startAt: string;\n    expireAt?: string;\n  }) => void;\n\n  // CRUD + field events (shapes reused from task-card)\n  onItemAdded?: (event: TaskItemAddedEvent) => void;\n  onItemRemoved?: (event: TaskItemRemovedEvent) => void;\n  onItemMoved?: (event: TaskItemMovedEvent) => void;\n  onFieldEdited?: (event: TaskFieldEditedEvent) => void;\n  onStatusChanged?: (event: TaskStatusChangedEvent) => void;\n\n  // Permissions (reused from task-card; mirrors task-tree)\n  permissions?: TaskPermissions;\n  canMoveItem?: (id: string) => boolean;\n  canResizeItem?: (id: string) => boolean;\n  canDeleteItem?: (id: string) => boolean;\n  canCreateChild?: (id: string) => boolean;\n  canEditItem?: (id: string) => boolean;\n  onPermissionDenied?: (\n    action: keyof TaskPermissionRule,\n    itemId: string,\n    reason: TaskPermissionReason,\n  ) => void;\n\n  className?: string;\n  \"aria-label\"?: string;\n};\n\n/** Headless provider props = assembly props minus the assembly-only toggle. */\nexport type GanttTimelineRootProps = Omit<GanttTimelineProps, \"showToolbar\"> & {\n  children: ReactNode;\n};\n\n/* ───────── imperative handle ───────── */\n\nexport type GanttTimelineHandle = {\n  scrollToDate(date: string): void;\n  scrollToItem(itemId: string): void;\n  scrollToToday(): void;\n  expandAll(): void;\n  collapseAll(): void;\n  setZoom(zoom: GanttZoom): void;\n  /** Multiply the continuous zoom (focal = viewport center). */\n  zoomBy(factor: number): void;\n  /** Frame all bars + padding. */\n  zoomToFit(): void;\n\n  // Editing (v0.2.0) — no-ops when `editable` is false / permission denied.\n  /** Create a task under `parentId` (null = root); a partial seeds the rest. */\n  addTask(parentId: string | null, item?: Partial<TaskItem>): void;\n  deleteTask(itemId: string): void;\n  /** Open the detail editor (embedded card) for an item. */\n  editTask(itemId: string): void;\n  /** Start inline rename of a gutter row. */\n  beginRename(itemId: string): void;\n  /**\n   * v0.3.0 — group-move a summary's whole subtree by `deltaMs` (signed epoch-ms).\n   * No-op unless `editable` and the group is movable (summary + every leaf).\n   */\n  shiftTaskGroup(summaryId: string, deltaMs: number): void;\n};\n\n/* ───────── context (internal; constructed in the Root) ───────── */\n\n/** One render slot — either a virtualizer item or a plain row offset. */\nexport type GanttRenderItem = { index: number; start: number };\n\nexport type GanttContextValue = {\n  // data + rows\n  rows: GanttRow[];\n  renderItems: GanttRenderItem[];\n  totalSize: number;\n  rowHeight: number;\n  gutterWidth: number;\n\n  // scroll refs / vertical sync\n  bodyScrollRef: RefObject<HTMLDivElement | null>;\n  gutterTrackRef: RefObject<HTMLDivElement | null>;\n  onBodyScroll: (scrollTop: number) => void;\n  measureRows: () => void;\n\n  // viewport + scale\n  viewport: GanttViewport;\n  bodyWidth: number;\n  setBodyWidth: (w: number) => void;\n  dataExtent: { startMs: number; endMs: number };\n\n  // gestures\n  disableGestures: boolean;\n  onPan: (deltaPx: number) => void;\n  onZoomAt: (factor: number, focalPx: number) => void;\n  beginPan: () => void;\n  endPanWithVelocity: (velocityPxPerMs: number) => void;\n\n  // zoom helpers / named\n  namedZoom: GanttZoom;\n  setZoomLevel: (z: GanttZoom) => void;\n  zoomBy: (factor: number) => void;\n  zoomToFit: () => void;\n  scrollToToday: () => void;\n  scrollToItemId: (id: string) => void;\n  pageBy: (dir: -1 | 1) => void;\n\n  // color + time + geometry\n  nowMs: number;\n  showTodayLine: boolean;\n  resolveColor: GanttColorResolver;\n  geometryFor: (item: TaskItem) => GanttBarGeometry;\n  summarySpanFor: (item: TaskItem) => { startMs: number; endMs: number } | null;\n\n  // display config\n  statusOptions?: TaskStatusOption[];\n  priorityOptions?: TaskPriorityOption[];\n  labelOptions?: TaskLabelOption[];\n  showWeekendShading: boolean;\n\n  // collapse + selection + focus\n  isCollapsed: (id: string) => boolean;\n  toggleCollapse: (id: string) => void;\n  selectedId: string | null;\n  select: (id: string | null) => void;\n  onTaskClick?: (item: TaskItem) => void;\n  renderTooltip?: GanttTooltipRenderer;\n  focusedId: string | null;\n  setFocusedId: (id: string | null) => void;\n\n  // ── editing (v0.2.0) — always present; dispatchers are no-ops when !editable ──\n  editable: boolean;\n  snap: GanttSnap;\n  /**\n   * v0.4.0 — draw mode. When true, dragging a task row's empty area draws a new\n   * bar; when false (default) that drag pans the dates. Toolbar-toggled; only\n   * meaningful while `editable`.\n   */\n  drawMode: boolean;\n  setDrawMode: (on: boolean) => void;\n  /** The raw permission matrix (threaded into the embedded edit card). */\n  permissions?: TaskPermissions;\n  /** Look up any item in the forest by id (incl. collapsed). */\n  getItem: (id: string) => TaskItem | undefined;\n  /** Effective permission for an action on an item (matrix + can* predicate + locked). */\n  can: (action: GanttEditAction, item: TaskItem) => boolean;\n  /**\n   * v0.3.0 — can this summary's whole subtree be group-moved? Atomic: the summary\n   * must be movable AND every descendant leaf must pass `can(\"move\")`. Drives both\n   * the bracket-drag gate and the grab cursor.\n   */\n  canGroupMove: (item: TaskItem) => boolean;\n  /** parentId / index / level lookup over the current forest. */\n  nodeInfo: (\n    id: string,\n  ) => { parentId: string | null; index: number; level: number } | undefined;\n\n  // mutation dispatchers — compute the next forest, fire the typed event + onChange\n  rescheduleItem: (\n    id: string,\n    patch: { startAt?: string; expireAt?: string; duration?: number },\n    kind: \"move\" | \"resize\",\n  ) => void;\n  createItem: (\n    parentId: string | null,\n    seed?: Partial<TaskItem>,\n    index?: number,\n    opts?: { openEditor?: boolean },\n  ) => void;\n  deleteItem: (id: string) => void;\n  renameItemAction: (id: string, name: string) => void;\n  moveItemAction: (\n    id: string,\n    newParentId: string | null,\n    newIndex: number,\n  ) => void;\n  /** v0.3.0 — group-move: shift a summary's whole subtree by `deltaMs` (atomic-gated). */\n  moveSubtree: (id: string, deltaMs: number) => void;\n  changeStatus: (id: string, status: string) => void;\n  /** v0.5.0 — set priority (mutate + onChange only; \"priority\" is not a typed field). */\n  changePriority: (id: string, priority: string) => void;\n\n  // detail editor (popover) target\n  editingId: string | null;\n  openEditor: (id: string) => void;\n  closeEditor: () => void;\n  /** Splice an edited subtree (same root id) back into the forest. */\n  applyEditedSubtree: (next: TaskItem) => void;\n\n  // inline rename (gutter) target\n  renamingId: string | null;\n  beginRename: (id: string) => void;\n  endRename: () => void;\n\n  // ── quick-create composer (v0.5.0) ──\n  quickCompose: boolean;\n  renderQuickComposer?: GanttQuickComposerRenderer;\n  composerTarget: GanttComposerTarget | null;\n  openComposer: (target: GanttComposerTarget) => void;\n  closeComposer: () => void;\n\n  // ── cross-surface clipboard (v0.5.0) — copy/cut programmatic; paste from a parsed envelope ──\n  /** Copy an item's subtree to the OS clipboard (shared `ilinxa/task` envelope). */\n  copyItem: (id: string) => void;\n  /** Copy then delete (gated on delete). */\n  cutItem: (id: string) => void;\n  /** Insert pasted tasks (re-id'd) under `parentId` at `index` (append if omitted). */\n  pasteTasks: (\n    items: TaskItem[],\n    parentId: string | null,\n    index?: number,\n  ) => void;\n};\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/types.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/lib/color.ts",
      "content": "/**\n * Bar color resolution. The OKLCH urgency ramp is IMPORTED from task-card\n * (`RAMPS`) — not re-derived — so the timeline matches the card exactly. Only\n * the done/blocked tones are adapted to filled bars (gray / red), per the\n * procomp description §9.\n *\n * `RAMPS` must be the FIRST `from`-import so the meta-deps audit registers the\n * task-card dependency (blackboard / content-composer lesson).\n */\n\nimport { RAMPS } from \"../../task-card\";\nimport type {\n  GanttStatusTone,\n  TaskColorRamp,\n  TaskItem,\n  TaskStatusOption,\n} from \"../types\";\nimport { effEndMs, effStartMs } from \"./geometry\";\n\nexport function toneFor(\n  item: TaskItem,\n  statusOptions?: TaskStatusOption[],\n): GanttStatusTone {\n  const opt = statusOptions?.find((o) => o.value === item.status);\n  return opt?.tone ?? \"active\";\n}\n\n/** Resolve a `TaskColorRamp` (preset name | custom fn) into a callable. */\nexport function resolveRamp(\n  ramp: TaskColorRamp | undefined,\n): (t: number) => string {\n  if (ramp == null) return RAMPS.default;\n  if (typeof ramp === \"function\") return ramp;\n  return RAMPS[ramp] ?? RAMPS.default;\n}\n\n/** Fraction 0..1 of the item's window that has elapsed at `nowMs`. */\nexport function elapsedFraction(item: TaskItem, nowMs: number): number {\n  const s = effStartMs(item);\n  const e = effEndMs(item);\n  if (e == null || e <= s) return 0;\n  const f = (nowMs - s) / (e - s);\n  return f < 0 ? 0 : f > 1 ? 1 : f;\n}\n\n/**\n * Final fill for a bar:\n *   borderColor override  → that color (skips the engine)\n *   tone \"done\"           → gray\n *   tone \"blocked\"        → red\n *   tone \"active\"         → time-urgency ramp (green → red)\n */\nexport function barFill(\n  item: TaskItem,\n  nowMs: number,\n  ramp: (t: number) => string,\n  statusOptions?: TaskStatusOption[],\n): { fill: string; tone: GanttStatusTone } {\n  const tone = toneFor(item, statusOptions);\n  if (item.borderColor) return { fill: item.borderColor, tone };\n  if (tone === \"done\") return { fill: \"var(--muted-foreground)\", tone };\n  if (tone === \"blocked\") return { fill: \"var(--destructive)\", tone };\n  return { fill: ramp(elapsedFraction(item, nowMs)), tone };\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/lib/color.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/lib/flatten.ts",
      "content": "/**\n * Tree → visible rows (depth-first; skips descendants of collapsed nodes).\n * The gutter + body consume the SAME row array so they stay vertically aligned.\n * Pure; framework-free.\n */\n\nimport type { GanttRow, TaskItem } from \"../types\";\n\nexport function flatten(\n  data: TaskItem[],\n  isCollapsed: (id: string) => boolean,\n): GanttRow[] {\n  const out: GanttRow[] = [];\n  const walk = (\n    item: TaskItem,\n    depth: number,\n    parentId: string | null,\n    posInSet: number,\n    setSize: number,\n  ) => {\n    const hasChildren = !!item.children && item.children.length > 0;\n    const collapsed = hasChildren && isCollapsed(item.id);\n    out.push({\n      item,\n      depth,\n      parentId,\n      hasChildren,\n      isSummary: hasChildren,\n      collapsed,\n      posInSet,\n      setSize,\n    });\n    if (hasChildren && !collapsed) {\n      const kids = item.children!;\n      kids.forEach((child, i) =>\n        walk(child, depth + 1, item.id, i + 1, kids.length),\n      );\n    }\n  };\n  data.forEach((item, i) => walk(item, 0, null, i + 1, data.length));\n  return out;\n}\n\n/** Flat id → item index over the whole forest (for scrollToItem etc.). */\nexport function indexById(data: TaskItem[]): Map<string, TaskItem> {\n  const map = new Map<string, TaskItem>();\n  const walk = (item: TaskItem) => {\n    map.set(item.id, item);\n    item.children?.forEach(walk);\n  };\n  data.forEach(walk);\n  return map;\n}\n\n/** All ancestor ids that must be expanded for `id` to be visible. */\nexport function ancestorsOf(data: TaskItem[], id: string): string[] {\n  const path: string[] = [];\n  const found = { hit: false };\n  const walk = (item: TaskItem, trail: string[]) => {\n    if (found.hit) return;\n    if (item.id === id) {\n      found.hit = true;\n      path.push(...trail);\n      return;\n    }\n    item.children?.forEach((c) => walk(c, [...trail, item.id]));\n  };\n  data.forEach((d) => walk(d, []));\n  return path;\n}\n\n/** Every id that has children (for expandAll/collapseAll). */\nexport function parentIds(data: TaskItem[]): string[] {\n  const ids: string[] = [];\n  const walk = (item: TaskItem) => {\n    if (item.children && item.children.length > 0) {\n      ids.push(item.id);\n      item.children.forEach(walk);\n    }\n  };\n  data.forEach(walk);\n  return ids;\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/lib/flatten.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/lib/geometry.ts",
      "content": "/**\n * Effective-window + hierarchy math. Pure; framework-free.\n *\n * Deterministic resolution (locked in the procomp description §4):\n *   effectiveStart = startAt ?? setAt\n *   effectiveEnd   = expireAt ?? (duration != null ? start + duration : null)\n *   isMilestone    = effectiveEnd == null      → diamond at effectiveStart\n *   isOverdue      = end != null && end < now && tone !== \"done\"\n */\n\nimport type { GanttBarGeometry, GanttStatusTone, TaskItem } from \"../types\";\n\nconst DATE_ONLY_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/**\n * Parse a TaskItem ISO date value. A bare calendar date (`YYYY-MM-DD`, no `T`)\n * is the family's all-day form and parses as a FLOATING LOCAL date — NOT via\n * `Date.parse`, which per spec reads \"2026-06-22\" as UTC midnight and renders\n * the bar a day early in negative-UTC offsets (family convention; matches\n * event-calendar's `parseDateValue`). Full timestamps go through `Date.parse`\n * unchanged. Returns NaN for missing/unparseable input.\n */\nexport function parseGanttDate(value: string | undefined): number {\n  if (!value) return NaN;\n  if (DATE_ONLY_RE.test(value)) {\n    const [y, m, d] = value.split(\"-\").map(Number);\n    return new Date(y, m - 1, d).getTime();\n  }\n  return Date.parse(value);\n}\n\n/** True for the family's bare `YYYY-MM-DD` all-day form. */\nexport function isGanttDateOnly(value: string | undefined): boolean {\n  return typeof value === \"string\" && DATE_ONLY_RE.test(value);\n}\n\n/**\n * Serialize an epoch-ms instant back to a stored field whose ORIGINAL value\n * may have been date-only. When the original was `YYYY-MM-DD` AND the instant\n * still sits on a floating-local midnight (a whole-day move), the date-only\n * form is representable — keep it, so an edit never silently converts an\n * all-day value into a UTC timestamp. Anything else serializes as full ISO.\n */\nexport function serializeGanttDate(ms: number, original: string | undefined): string {\n  if (original !== undefined && DATE_ONLY_RE.test(original)) {\n    const d = new Date(ms);\n    if (\n      d.getHours() === 0 &&\n      d.getMinutes() === 0 &&\n      d.getSeconds() === 0 &&\n      d.getMilliseconds() === 0\n    ) {\n      const pad = (n: number) => String(n).padStart(2, \"0\");\n      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;\n    }\n  }\n  return new Date(ms).toISOString();\n}\n\nexport function effStartMs(item: TaskItem): number {\n  return parseGanttDate(item.startAt ?? item.setAt);\n}\n\nexport function effEndMs(item: TaskItem): number | null {\n  if (item.expireAt) return parseGanttDate(item.expireAt);\n  if (item.duration != null) return effStartMs(item) + item.duration;\n  return null;\n}\n\nexport function geometryFor(\n  item: TaskItem,\n  nowMs: number,\n  tone: GanttStatusTone,\n): GanttBarGeometry {\n  const startMs = effStartMs(item);\n  const endMs = effEndMs(item);\n  const isMilestone = endMs == null;\n  const isOverdue = endMs != null && endMs < nowMs && tone !== \"done\";\n  return { startMs, endMs, isMilestone, isOverdue };\n}\n\n/**\n * Summary span for a parent = min(descendant starts) → max(descendant ends),\n * treating a milestone descendant as a point. Returns null for a leaf.\n */\nexport function summarySpan(\n  item: TaskItem,\n): { startMs: number; endMs: number } | null {\n  if (!item.children || item.children.length === 0) return null;\n  let start = Infinity;\n  let end = -Infinity;\n  const walk = (n: TaskItem) => {\n    const s = effStartMs(n);\n    const e = effEndMs(n) ?? s; // milestone → point\n    if (s < start) start = s;\n    if (e > end) end = e;\n    n.children?.forEach(walk);\n  };\n  item.children.forEach(walk);\n  if (start === Infinity) return null;\n  return { startMs: start, endMs: end };\n}\n\n/** Min start / max end across the whole forest (milestones as points). */\nexport function dataExtent(data: TaskItem[]): { startMs: number; endMs: number } {\n  let start = Infinity;\n  let end = -Infinity;\n  const walk = (n: TaskItem) => {\n    const s = effStartMs(n);\n    const e = effEndMs(n) ?? s;\n    if (Number.isFinite(s) && s < start) start = s;\n    if (Number.isFinite(e) && e > end) end = e;\n    n.children?.forEach(walk);\n  };\n  data.forEach(walk);\n  if (start === Infinity || end === -Infinity) {\n    // Empty / unparseable — a neutral one-month window keeps the axis sane.\n    const base = 0;\n    return { startMs: base, endMs: base + 30 * 86_400_000 };\n  }\n  if (start === end) {\n    // Single instant — pad to a day so a bar/diamond has room.\n    return { startMs: start - 43_200_000, endMs: end + 43_200_000 };\n  }\n  return { startMs: start, endMs: end };\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/lib/geometry.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/lib/time-scale.ts",
      "content": "/**\n * Continuous time scale: a linear map epoch-ms ↔ x-pixels, plus the two-tier\n * header scale selection (with a wide hysteresis band) and calendar-aware tick\n * generation. Pure; framework-free. No date library — epoch-ms + `Intl`.\n */\n\nimport type { GanttTimeUnit, GanttViewport, GanttZoom } from \"../types\";\n\nexport const MS = {\n  minute: 60_000,\n  hour: 3_600_000,\n  day: 86_400_000,\n  week: 604_800_000,\n} as const;\n\n/** Approximate unit lengths — used ONLY for scale anchoring, never for labels. */\nconst APPROX_MS: Record<GanttTimeUnit, number> = {\n  hour: MS.hour,\n  day: MS.day,\n  week: MS.week,\n  month: 2_629_800_000, // 30.44 d\n  quarter: 7_889_400_000,\n  year: 31_557_600_000,\n};\n\nexport function x(vp: GanttViewport, t: number): number {\n  return (t - vp.originMs) * vp.pxPerMs;\n}\n\nexport function timeAt(vp: GanttViewport, px: number): number {\n  return vp.originMs + px / vp.pxPerMs;\n}\n\n/* ───────── named-level anchors ───────── */\n\n/** The minor (cell) unit each named zoom level targets. */\nconst ZOOM_MINOR: Record<GanttZoom, GanttTimeUnit> = {\n  hour: \"hour\",\n  day: \"day\",\n  week: \"day\",\n  month: \"week\",\n  quarter: \"month\",\n};\n\n/** A named-zoom level renders its minor cell about this wide. */\nconst ANCHOR_CELL_PX = 56;\n\nexport function pxPerMsForZoom(zoom: GanttZoom): number {\n  return ANCHOR_CELL_PX / APPROX_MS[ZOOM_MINOR[zoom]];\n}\n\n/** Nearest named level for a given pxPerMs (for the controlled `zoom` echo). */\nexport function zoomForPxPerMs(pxPerMs: number): GanttZoom {\n  const levels: GanttZoom[] = [\"hour\", \"day\", \"week\", \"month\", \"quarter\"];\n  let best: GanttZoom = \"week\";\n  let bestDist = Infinity;\n  for (const lvl of levels) {\n    const d = Math.abs(Math.log(pxPerMsForZoom(lvl) / pxPerMs));\n    if (d < bestDist) {\n      bestDist = d;\n      best = lvl;\n    }\n  }\n  return best;\n}\n\n/* ───────── two-tier scale selection ───────── */\n\nconst SCALE_LADDER: { minor: GanttTimeUnit; major: GanttTimeUnit }[] = [\n  { minor: \"hour\", major: \"day\" },\n  { minor: \"day\", major: \"week\" },\n  { minor: \"day\", major: \"month\" },\n  { minor: \"week\", major: \"month\" },\n  { minor: \"month\", major: \"quarter\" },\n  { minor: \"month\", major: \"year\" },\n  { minor: \"quarter\", major: \"year\" },\n];\n\n// One cutoff over a multiplicatively-spaced ladder: each rung's minor unit is\n// ~3–7× the previous, so a single MIN_CELL_PX threshold yields wide, stable\n// pxPerMs bands per level and the header doesn't thrash near a boundary. (Band\n// stability comes from the rung spacing — not state-dependent hysteresis.)\nconst MIN_CELL_PX = 40;\n\n/** Pick the finest ladder entry whose minor cell renders ≥ MIN_CELL_PX. */\nexport function pickScales(pxPerMs: number): {\n  minor: GanttTimeUnit;\n  major: GanttTimeUnit;\n} {\n  for (const entry of SCALE_LADDER) {\n    if (APPROX_MS[entry.minor] * pxPerMs >= MIN_CELL_PX) return entry;\n  }\n  return SCALE_LADDER[SCALE_LADDER.length - 1];\n}\n\n/* ───────── calendar boundaries (local time, single display tz) ───────── */\n\nexport function startOfUnit(unit: GanttTimeUnit, ms: number): number {\n  const d = new Date(ms);\n  switch (unit) {\n    case \"hour\":\n      d.setMinutes(0, 0, 0);\n      return d.getTime();\n    case \"day\":\n      d.setHours(0, 0, 0, 0);\n      return d.getTime();\n    case \"week\": {\n      d.setHours(0, 0, 0, 0);\n      const monday = (d.getDay() + 6) % 7; // Monday = 0\n      d.setDate(d.getDate() - monday);\n      return d.getTime();\n    }\n    case \"month\":\n      d.setHours(0, 0, 0, 0);\n      d.setDate(1);\n      return d.getTime();\n    case \"quarter\":\n      d.setHours(0, 0, 0, 0);\n      d.setDate(1);\n      d.setMonth(Math.floor(d.getMonth() / 3) * 3);\n      return d.getTime();\n    case \"year\":\n      d.setHours(0, 0, 0, 0);\n      d.setMonth(0, 1);\n      return d.getTime();\n  }\n}\n\nexport function addUnit(unit: GanttTimeUnit, ms: number, n = 1): number {\n  const d = new Date(ms);\n  switch (unit) {\n    case \"hour\":\n      d.setHours(d.getHours() + n);\n      break;\n    case \"day\":\n      d.setDate(d.getDate() + n);\n      break;\n    case \"week\":\n      d.setDate(d.getDate() + 7 * n);\n      break;\n    case \"month\":\n      d.setMonth(d.getMonth() + n);\n      break;\n    case \"quarter\":\n      d.setMonth(d.getMonth() + 3 * n);\n      break;\n    case \"year\":\n      d.setFullYear(d.getFullYear() + n);\n      break;\n  }\n  return d.getTime();\n}\n\n/** Aligned cell-boundary timestamps within [fromMs, toMs], capped for safety. */\nexport function ticks(\n  unit: GanttTimeUnit,\n  fromMs: number,\n  toMs: number,\n  cap = 800,\n): number[] {\n  const out: number[] = [];\n  let t = startOfUnit(unit, fromMs);\n  let guard = 0;\n  while (t <= toMs && guard < cap) {\n    out.push(t);\n    t = addUnit(unit, t);\n    guard += 1;\n  }\n  return out;\n}\n\n/* ───────── labels ───────── */\n\nfunction fmt(ms: number, opts: Intl.DateTimeFormatOptions): string {\n  return new Intl.DateTimeFormat(undefined, opts).format(new Date(ms));\n}\n\nexport function minorLabel(unit: GanttTimeUnit, ms: number): string {\n  switch (unit) {\n    case \"hour\":\n      return fmt(ms, { hour: \"2-digit\", minute: \"2-digit\" });\n    case \"day\":\n      return fmt(ms, { day: \"numeric\" });\n    case \"week\":\n      return fmt(ms, { month: \"short\", day: \"numeric\" });\n    case \"month\":\n      return fmt(ms, { month: \"short\" });\n    case \"quarter\":\n      return `Q${Math.floor(new Date(ms).getMonth() / 3) + 1}`;\n    case \"year\":\n      return fmt(ms, { year: \"numeric\" });\n  }\n}\n\nexport function majorLabel(unit: GanttTimeUnit, ms: number): string {\n  switch (unit) {\n    case \"hour\":\n      return fmt(ms, { weekday: \"short\", month: \"short\", day: \"numeric\" });\n    case \"day\":\n      return fmt(ms, { month: \"short\", day: \"numeric\" });\n    case \"week\":\n      return fmt(ms, { month: \"long\", year: \"numeric\" });\n    case \"month\":\n      return fmt(ms, { month: \"long\", year: \"numeric\" });\n    case \"quarter\":\n      return `Q${Math.floor(new Date(ms).getMonth() / 3) + 1} ${new Date(ms).getFullYear()}`;\n    case \"year\":\n      return fmt(ms, { year: \"numeric\" });\n  }\n}\n\n/** Is this timestamp inside a Sat/Sun day? (for weekend shading) */\nexport function isWeekend(ms: number): boolean {\n  const day = new Date(ms).getDay();\n  return day === 0 || day === 6;\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/lib/time-scale.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/lib/edit-mutations.ts",
      "content": "/**\n * Pure forest mutations over `TaskItem[]` — the editing layer (v0.2.0).\n *\n * The array analogue of task-card's reducer mutations: every function\n * returns a NEW forest with structural sharing and NEVER mutates in place, so\n * the controlled consumer can diff/echo and stack undo for free. Framework-free;\n * Vitest-ready. Hierarchy is nested `children` (no parentId on TaskItem), so the\n * index here is what callers use to locate a splice point.\n */\n\nimport type { TaskItem } from \"../types\";\nimport {\n  effEndMs,\n  effStartMs,\n  isGanttDateOnly,\n  parseGanttDate,\n  serializeGanttDate,\n} from \"./geometry\";\n\n/** Minimum bar span (ms) so a resize/drag can't collapse a bar to zero width. */\nexport const MIN_DURATION_MS = 60_000;\n\nexport type ForestNodeInfo = {\n  item: TaskItem;\n  parentId: string | null;\n  index: number;\n  /** 1 = root. */\n  level: number;\n};\n\n/** Flat `id → { item, parentId, index, level }` over the whole forest. */\nexport function buildIndex(data: TaskItem[]): Map<string, ForestNodeInfo> {\n  const map = new Map<string, ForestNodeInfo>();\n  const walk = (items: TaskItem[], parentId: string | null, level: number) => {\n    items.forEach((item, index) => {\n      map.set(item.id, { item, parentId, index, level });\n      if (item.children?.length) walk(item.children, item.id, level + 1);\n    });\n  };\n  walk(data, null, 1);\n  return map;\n}\n\n/** Replace the matching item via `fn`; returns the same ref when nothing changed. */\nfunction replace(\n  data: TaskItem[],\n  id: string,\n  fn: (item: TaskItem) => TaskItem,\n): TaskItem[] {\n  let changed = false;\n  const next = data.map((item) => {\n    if (item.id === id) {\n      changed = true;\n      return fn(item);\n    }\n    if (item.children?.length) {\n      const kids = replace(item.children, id, fn);\n      if (kids !== item.children) {\n        changed = true;\n        return { ...item, children: kids };\n      }\n    }\n    return item;\n  });\n  return changed ? next : data;\n}\n\nexport function renameItem(\n  data: TaskItem[],\n  id: string,\n  name: string,\n): TaskItem[] {\n  return replace(data, id, (item) => ({ ...item, name }));\n}\n\n/**\n * Apply a window patch (reschedule / resize / milestone-move), enforcing the\n * geometry invariant `end ≥ start + MIN_DURATION_MS`. Respects the v1 precedence:\n * an `expireAt`-driven bar keeps writing `expireAt`; a `duration`-driven bar\n * keeps writing `duration`.\n */\nexport function setWindow(\n  data: TaskItem[],\n  id: string,\n  patch: { startAt?: string; expireAt?: string; duration?: number },\n): TaskItem[] {\n  return replace(data, id, (item) => {\n    const next: TaskItem = { ...item, ...patch };\n    const startMs = parseGanttDate(next.startAt ?? next.setAt);\n    // Date-only (all-day) preservation: when the ORIGINAL field was a bare\n    // YYYY-MM-DD and the patched instant still sits on a local midnight (a\n    // whole-day move), keep the date-only form instead of silently converting\n    // it to a UTC timestamp. Non-date-only originals keep the patch verbatim.\n    if (\n      patch.startAt != null &&\n      isGanttDateOnly(item.startAt) &&\n      Number.isFinite(startMs)\n    ) {\n      next.startAt = serializeGanttDate(startMs, item.startAt);\n    }\n    if (next.expireAt != null) {\n      let endMs = parseGanttDate(next.expireAt);\n      if (\n        Number.isFinite(startMs) &&\n        Number.isFinite(endMs) &&\n        endMs < startMs + MIN_DURATION_MS\n      ) {\n        endMs = startMs + MIN_DURATION_MS;\n      }\n      // Guard: an unparseable date would make `new Date(NaN).toISOString()`\n      // throw. Leave a bad `expireAt` untouched rather than crashing the commit.\n      if (Number.isFinite(endMs)) {\n        next.expireAt = serializeGanttDate(endMs, item.expireAt);\n      }\n    } else if (next.duration != null) {\n      next.duration = Math.max(MIN_DURATION_MS, next.duration);\n    }\n    return next;\n  });\n}\n\n/** True when `maybeAncestorId` is an ancestor of `id` (circular-drop guard). */\nexport function isAncestor(\n  data: TaskItem[],\n  maybeAncestorId: string,\n  id: string,\n): boolean {\n  const idx = buildIndex(data);\n  let cur = idx.get(id)?.parentId ?? null;\n  while (cur != null) {\n    if (cur === maybeAncestorId) return true;\n    cur = idx.get(cur)?.parentId ?? null;\n  }\n  return false;\n}\n\n/** Insert `item` under `parentId` (null = root) at `index` (default = append). */\nexport function addItem(\n  data: TaskItem[],\n  parentId: string | null,\n  item: TaskItem,\n  index?: number,\n): TaskItem[] {\n  if (parentId == null) {\n    const next = [...data];\n    next.splice(index ?? next.length, 0, item);\n    return next;\n  }\n  return replace(data, parentId, (parent) => {\n    const kids = parent.children ? [...parent.children] : [];\n    kids.splice(index ?? kids.length, 0, item);\n    return { ...parent, children: kids };\n  });\n}\n\n/** Remove an item; returns the new forest + the removed subtree + its old parent. */\nexport function removeItem(\n  data: TaskItem[],\n  id: string,\n): { next: TaskItem[]; removed: TaskItem | null; parentId: string | null } {\n  const info = buildIndex(data).get(id);\n  if (!info) return { next: data, removed: null, parentId: null };\n  const prune = (items: TaskItem[]): TaskItem[] =>\n    items\n      .filter((it) => it.id !== id)\n      .map((it) =>\n        it.children?.length ? { ...it, children: prune(it.children) } : it,\n      );\n  return { next: prune(data), removed: info.item, parentId: info.parentId };\n}\n\n/**\n * Move an item to `newParentId` (null = root) at `newIndex`. The caller guards\n * circular drops (`isAncestor`); `newIndex` is interpreted against the target\n * parent's children AFTER the source has been removed (task-tree semantics).\n */\nexport function moveItem(\n  data: TaskItem[],\n  id: string,\n  newParentId: string | null,\n  newIndex: number,\n): TaskItem[] {\n  const { next: pruned, removed } = removeItem(data, id);\n  if (!removed) return data;\n  return addItem(pruned, newParentId, removed, newIndex);\n}\n\n/* ───────── group-move (v0.3.0) ───────── */\n\n/**\n * The scheduled LEAF descendants of `root`. Derived summaries — `root` itself and\n * any nested parent — are never returned; only leaves carry a real schedule.\n * Walks `root.children` directly (no index rebuild), so it's cheap enough for the\n * render-hot `canGroupMove` path. A leaf root yields `[]`.\n */\nexport function subtreeLeaves(root: TaskItem): TaskItem[] {\n  const out: TaskItem[] = [];\n  const walk = (n: TaskItem) => {\n    if (n.children?.length) n.children.forEach(walk);\n    else out.push(n);\n  };\n  root.children?.forEach(walk); // a summary root ⇒ recurses, never pushes itself\n  return out;\n}\n\n/**\n * Rigidly shift a subtree by `deltaMs` (group-move). Every LEAF descendant's\n * window translates by the same delta; derived summaries (the root + any nested\n * parent) keep their own latent dates and re-derive their brackets from the moved\n * leaves (WBS-consistent — the gantt ignores a parent's own window). Writes\n * `startAt` (+ `expireAt` for expireAt-driven leaves); `duration`/`setAt`\n * untouched; milestones shift `startAt` only. The span is invariant under a rigid\n * shift, so no MIN_DURATION clamp is needed. Structural sharing; returns the same\n * ref when `deltaMs` is 0 / non-finite.\n */\nexport function shiftSubtree(\n  data: TaskItem[],\n  rootId: string,\n  deltaMs: number,\n): TaskItem[] {\n  if (!Number.isFinite(deltaMs) || deltaMs === 0) return data;\n  const shiftLeaf = (item: TaskItem): TaskItem => {\n    const s = effStartMs(item);\n    // Unparseable start — can't translate it; leave the leaf untouched rather\n    // than emitting `new Date(NaN).toISOString()` (which throws).\n    if (!Number.isFinite(s)) return item;\n    const next: TaskItem = {\n      ...item,\n      // Date-only originals keep the YYYY-MM-DD form on whole-day shifts\n      // (serializeGanttDate); anything else serializes as full ISO, as before.\n      startAt: serializeGanttDate(s + deltaMs, item.startAt),\n    };\n    if (item.expireAt != null) {\n      const e = effEndMs(item);\n      const base = e != null && Number.isFinite(e) ? e : s;\n      next.expireAt = serializeGanttDate(base + deltaMs, item.expireAt);\n    }\n    return next;\n  };\n  const shiftDeep = (item: TaskItem): TaskItem =>\n    item.children?.length\n      ? { ...item, children: item.children.map(shiftDeep) }\n      : shiftLeaf(item);\n  return replace(data, rootId, shiftDeep);\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/lib/edit-mutations.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/lib/edit-permissions.ts",
      "content": "/**\n * Gantt edit-permission resolver. Mirrors task-tree/lib/permissions.ts: maps the\n * gantt's edit actions onto task-card's `TaskPermissionRule` keys and\n * resolves against the shared `TaskPermissions` matrix (+ `item.locked`). Keeping\n * the matrix shape identical across card / tree / gantt means one mental model\n * for consumers. Framework-free; Vitest-ready.\n */\n\nimport type {\n  GanttEditAction,\n  TaskItem,\n  TaskPermissionRule,\n  TaskPermissions,\n} from \"../types\";\n\n/** Gantt actions piggy-back on the most natural existing rule key. */\nconst ACTION_TO_RULE: Record<GanttEditAction, keyof TaskPermissionRule> = {\n  move: \"drag\",\n  resize: \"drag\",\n  delete: \"remove\",\n  create: \"addChildren\",\n  editDetails: \"edit\",\n};\n\n/**\n * Effective allow/deny for one action on `item` at `level` (1 = root). Hard lock\n * (`item.locked`) denies everything. Lookup order byItem → byLevel → default,\n * then a `true` fallback; `inherit !== false` ascends on undefined keys.\n */\nexport function evalGanttPermission(\n  permissions: TaskPermissions | undefined,\n  action: GanttEditAction,\n  item: TaskItem,\n  level: number,\n): boolean {\n  if (item.locked) return false;\n  if (!permissions) return true;\n\n  const key = ACTION_TO_RULE[action];\n  const inherit = permissions.inherit !== false;\n\n  const byItem = permissions.byItem?.[item.id]?.[key];\n  if (byItem !== undefined) return byItem;\n  if (!inherit && permissions.byItem?.[item.id]) return true;\n\n  const byLevel = permissions.byLevel?.[level]?.[key];\n  if (byLevel !== undefined) return byLevel;\n  if (!inherit && permissions.byLevel?.[level]) return true;\n\n  const def = permissions.default?.[key];\n  if (def !== undefined) return def;\n\n  return true;\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/lib/edit-permissions.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/hooks/use-color-tick.ts",
      "content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * A counter that increments every `intervalMs` (0 disables). SSR-safe: stays 0\n * on the server + first client render, the interval starts only after mount.\n * Drives the periodic re-resolution of the \"now\" line + urgency color.\n */\nexport function useColorTick(intervalMs: number): number {\n  const [tick, setTick] = useState(0);\n  useEffect(() => {\n    if (!intervalMs || intervalMs <= 0) return;\n    const id = setInterval(() => setTick((t) => t + 1), intervalMs);\n    return () => clearInterval(id);\n  }, [intervalMs]);\n  return tick;\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/hooks/use-color-tick.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/hooks/use-gantt-context.ts",
      "content": "\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport type { GanttContextValue } from \"../types\";\n\nexport const GanttContext = createContext<GanttContextValue | null>(null);\n\n/** Read the gantt context. Throws if used outside `<GanttTimelineRoot>`. */\nexport function useGanttTimeline(): GanttContextValue {\n  const ctx = useContext(GanttContext);\n  if (!ctx) {\n    throw new Error(\"useGanttTimeline must be used within <GanttTimelineRoot>\");\n  }\n  return ctx;\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/hooks/use-gantt-context.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/hooks/use-gantt-viewport.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { GanttViewport, GanttZoom } from \"../types\";\nimport { parseGanttDate } from \"../lib/geometry\";\nimport { MS, pxPerMsForZoom, timeAt, zoomForPxPerMs } from \"../lib/time-scale\";\n\ntype Args = {\n  dataExtent: { startMs: number; endMs: number };\n  bodyWidth: number;\n  defaultZoom: GanttZoom;\n  controlledZoom?: GanttZoom;\n  onZoomChange?: (z: GanttZoom) => void;\n  minZoom: GanttZoom;\n  maxZoom: GanttZoom;\n  onViewportChange?: (w: { from: string; to: string }) => void;\n  range?: { from: string; to: string };\n  nowMs: number;\n};\n\nconst FRICTION = 0.94;\nconst MIN_VELOCITY = 0.012; // px/ms\n\n/** Client-only; momentum honors the user's reduced-motion preference (plan §9/§10). */\nfunction prefersReducedMotion(): boolean {\n  return (\n    typeof window !== \"undefined\" &&\n    typeof window.matchMedia === \"function\" &&\n    window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n  );\n}\n\nexport type GanttViewportApi = {\n  viewport: GanttViewport;\n  minPxPerMs: number;\n  maxPxPerMs: number;\n  namedZoom: GanttZoom;\n  onPan: (deltaPx: number) => void;\n  onZoomAt: (factor: number, focalPx: number) => void;\n  zoomBy: (factor: number) => void;\n  setZoomLevel: (z: GanttZoom) => void;\n  zoomToFit: () => void;\n  scrollToMs: (ms: number) => void;\n  scrollToToday: () => void;\n  pageBy: (dir: -1 | 1) => void;\n  beginPan: () => void;\n  endPanWithVelocity: (velocityPxPerMs: number) => void;\n};\n\nexport function useGanttViewport(args: Args): GanttViewportApi {\n  const {\n    dataExtent,\n    bodyWidth,\n    defaultZoom,\n    controlledZoom,\n    onZoomChange,\n    minZoom,\n    maxZoom,\n    onViewportChange,\n    range,\n    nowMs,\n  } = args;\n\n  // hour = most zoomed-in (largest pxPerMs); quarter = most zoomed-out.\n  const maxPxPerMs = pxPerMsForZoom(minZoom);\n  const minPxPerMs = pxPerMsForZoom(maxZoom);\n\n  const [viewport, setViewport] = useState<GanttViewport>(() => ({\n    originMs: dataExtent.startMs,\n    pxPerMs: pxPerMsForZoom(defaultZoom),\n  }));\n\n  const clampPx = useCallback(\n    (px: number) => Math.min(maxPxPerMs, Math.max(minPxPerMs, px)),\n    [maxPxPerMs, minPxPerMs],\n  );\n\n  const clampOrigin = useCallback(\n    (originMs: number, px: number, soft: boolean): number => {\n      const visMs = bodyWidth / px;\n      const pad = visMs * 0.5;\n      const min = dataExtent.startMs - pad;\n      const max = dataExtent.endMs + pad - visMs;\n      if (max < min) {\n        // Data narrower than the viewport — center it.\n        return (dataExtent.startMs + dataExtent.endMs) / 2 - visMs / 2;\n      }\n      if (originMs < min) return soft ? min + (originMs - min) * 0.25 : min;\n      if (originMs > max) return soft ? max + (originMs - max) * 0.25 : max;\n      return originMs;\n    },\n    [bodyWidth, dataExtent.startMs, dataExtent.endMs],\n  );\n\n  /* ── momentum ── */\n  const velRef = useRef(0);\n  const rafRef = useRef<number | null>(null);\n  const lastTsRef = useRef(0);\n  const vcRafRef = useRef<number | null>(null);\n\n  const onPan = useCallback(\n    (deltaPx: number) => {\n      setViewport((vp) => {\n        const proposed = vp.originMs - deltaPx / vp.pxPerMs;\n        return { ...vp, originMs: clampOrigin(proposed, vp.pxPerMs, true) };\n      });\n    },\n    [clampOrigin],\n  );\n\n  const stopMomentum = useCallback(() => {\n    if (rafRef.current != null) cancelAnimationFrame(rafRef.current);\n    rafRef.current = null;\n    velRef.current = 0;\n  }, []);\n\n  const beginPan = useCallback(() => stopMomentum(), [stopMomentum]);\n\n  const endPanWithVelocity = useCallback(\n    (velocityPxPerMs: number) => {\n      stopMomentum();\n      // No inertia fling when the user prefers reduced motion (plan §9/§10).\n      if (prefersReducedMotion()) return;\n      if (Math.abs(velocityPxPerMs) < MIN_VELOCITY) return;\n      velRef.current = velocityPxPerMs;\n      lastTsRef.current = 0;\n      // hoisted declaration so the rAF loop can self-reference without a TDZ read\n      function tick(ts: number) {\n        const dt = lastTsRef.current ? ts - lastTsRef.current : 16;\n        lastTsRef.current = ts;\n        const v = velRef.current;\n        if (Math.abs(v) < MIN_VELOCITY) {\n          rafRef.current = null;\n          return;\n        }\n        onPan(v * dt);\n        velRef.current = v * FRICTION;\n        rafRef.current = requestAnimationFrame(tick);\n      }\n      rafRef.current = requestAnimationFrame(tick);\n    },\n    [onPan, stopMomentum],\n  );\n\n  useEffect(() => () => stopMomentum(), [stopMomentum]);\n\n  /* ── zoom ── */\n  const onZoomAt = useCallback(\n    (factor: number, focalPx: number) => {\n      setViewport((vp) => {\n        const focalTime = timeAt(vp, focalPx);\n        const newPx = clampPx(vp.pxPerMs * factor);\n        const newOrigin = focalTime - focalPx / newPx;\n        return { originMs: clampOrigin(newOrigin, newPx, false), pxPerMs: newPx };\n      });\n    },\n    [clampPx, clampOrigin],\n  );\n\n  const zoomBy = useCallback(\n    (factor: number) => onZoomAt(factor, bodyWidth / 2),\n    [onZoomAt, bodyWidth],\n  );\n\n  const setZoomLevel = useCallback(\n    (z: GanttZoom) => {\n      setViewport((vp) => {\n        const newPx = clampPx(pxPerMsForZoom(z));\n        const centerTime = timeAt(vp, bodyWidth / 2);\n        const newOrigin = centerTime - bodyWidth / 2 / newPx;\n        return { originMs: clampOrigin(newOrigin, newPx, false), pxPerMs: newPx };\n      });\n      onZoomChange?.(z);\n    },\n    [clampPx, clampOrigin, bodyWidth, onZoomChange],\n  );\n\n  const zoomToFit = useCallback(() => {\n    const dataSpan = dataExtent.endMs - dataExtent.startMs;\n    const pad = dataSpan * 0.04 || MS.day;\n    const span = dataSpan + pad * 2;\n    const px = clampPx(bodyWidth / Math.max(span, 1));\n    setViewport({\n      originMs: clampOrigin(dataExtent.startMs - pad, px, false),\n      pxPerMs: px,\n    });\n  }, [clampPx, clampOrigin, bodyWidth, dataExtent.startMs, dataExtent.endMs]);\n\n  const scrollToMs = useCallback(\n    (ms: number) => {\n      setViewport((vp) => {\n        const origin = ms - bodyWidth / 2 / vp.pxPerMs;\n        return { ...vp, originMs: clampOrigin(origin, vp.pxPerMs, false) };\n      });\n    },\n    [clampOrigin, bodyWidth],\n  );\n\n  const scrollToToday = useCallback(() => scrollToMs(nowMs), [scrollToMs, nowMs]);\n\n  const pageBy = useCallback(\n    (dir: -1 | 1) => onPan(-dir * bodyWidth * 0.9),\n    [onPan, bodyWidth],\n  );\n\n  /* ── first-paint fit (cap zoom-in at defaultZoom; honor explicit range) ── */\n  const initializedRef = useRef(false);\n  useEffect(() => {\n    if (bodyWidth <= 0 || initializedRef.current) return;\n    initializedRef.current = true;\n    if (range) {\n      // Same parser as the bars: date-only range bounds are floating-local.\n      const from = parseGanttDate(range.from);\n      const to = parseGanttDate(range.to);\n      if (Number.isFinite(from) && Number.isFinite(to) && to > from) {\n        // eslint-disable-next-line react-hooks/set-state-in-effect\n        setViewport({ originMs: from, pxPerMs: clampPx(bodyWidth / (to - from)) });\n        return;\n      }\n    }\n    const dataSpan = dataExtent.endMs - dataExtent.startMs;\n    const pad = dataSpan * 0.04 || MS.day;\n    const span = dataSpan + pad * 2;\n    const fitPx = span > 0 ? bodyWidth / span : pxPerMsForZoom(defaultZoom);\n    const px = clampPx(Math.min(pxPerMsForZoom(defaultZoom), fitPx));\n    const visMs = bodyWidth / px;\n    const origin =\n      visMs >= dataSpan\n        ? (dataExtent.startMs + dataExtent.endMs) / 2 - visMs / 2\n        : dataExtent.startMs - pad;\n    setViewport({ originMs: origin, pxPerMs: px });\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [bodyWidth]);\n\n  /* ── controlled zoom sync ── */\n  useEffect(() => {\n    if (controlledZoom == null) return;\n    // eslint-disable-next-line react-hooks/set-state-in-effect\n    setViewport((vp) => {\n      const newPx = clampPx(pxPerMsForZoom(controlledZoom));\n      if (Math.abs(newPx - vp.pxPerMs) < 1e-12) return vp;\n      const centerTime = timeAt(vp, bodyWidth / 2);\n      return { originMs: centerTime - bodyWidth / 2 / newPx, pxPerMs: newPx };\n    });\n  }, [controlledZoom, clampPx, bodyWidth]);\n\n  /* ── viewport-change echo (rAF-throttled: coalesce multiple commits per frame) ── */\n  useEffect(() => {\n    if (!onViewportChange || bodyWidth <= 0) return;\n    if (vcRafRef.current != null) cancelAnimationFrame(vcRafRef.current);\n    vcRafRef.current = requestAnimationFrame(() => {\n      vcRafRef.current = null;\n      onViewportChange({\n        from: new Date(timeAt(viewport, 0)).toISOString(),\n        to: new Date(timeAt(viewport, bodyWidth)).toISOString(),\n      });\n    });\n    return () => {\n      if (vcRafRef.current != null) {\n        cancelAnimationFrame(vcRafRef.current);\n        vcRafRef.current = null;\n      }\n    };\n  }, [viewport, bodyWidth, onViewportChange]);\n\n  const namedZoom = controlledZoom ?? zoomForPxPerMs(viewport.pxPerMs);\n\n  return {\n    viewport,\n    minPxPerMs,\n    maxPxPerMs,\n    namedZoom,\n    onPan,\n    onZoomAt,\n    zoomBy,\n    setZoomLevel,\n    zoomToFit,\n    scrollToMs,\n    scrollToToday,\n    pageBy,\n    beginPan,\n    endPanWithVelocity,\n  };\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/hooks/use-gantt-viewport.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/hooks/use-gantt-virtual.ts",
      "content": "\"use client\";\n\nimport { useVirtualizer } from \"@tanstack/react-virtual\";\nimport type { RefObject } from \"react\";\nimport type { GanttRenderItem } from \"../types\";\n\n/**\n * Row virtualization (mirrors task-tree's `use-tree-virtual`). Virtualizes when\n * the row count crosses `threshold` AND a scroll element exists; otherwise\n * returns every row at its natural offset (the gutter-only / small-list\n * fallback). Both the gutter and the body consume the returned `renderItems`,\n * so they share one source of truth and stay vertically aligned.\n */\nexport function useGanttVirtual(args: {\n  count: number;\n  scrollRef: RefObject<HTMLDivElement | null>;\n  rowHeight: number;\n  threshold?: number;\n}): { renderItems: GanttRenderItem[]; totalSize: number; measure: () => void } {\n  const { count, scrollRef, rowHeight, threshold = 60 } = args;\n  const active = count >= threshold;\n\n  const virtualizer = useVirtualizer<HTMLDivElement, HTMLDivElement>({\n    count,\n    getScrollElement: () => scrollRef.current,\n    estimateSize: () => rowHeight,\n    overscan: 8,\n    enabled: active,\n  });\n\n  if (active) {\n    const renderItems: GanttRenderItem[] = virtualizer\n      .getVirtualItems()\n      .map((vi) => ({ index: vi.index, start: vi.start }));\n    return {\n      renderItems,\n      totalSize: virtualizer.getTotalSize(),\n      measure: () => virtualizer.measure(),\n    };\n  }\n\n  const renderItems: GanttRenderItem[] = Array.from(\n    { length: count },\n    (_, index) => ({ index, start: index * rowHeight }),\n  );\n  return { renderItems, totalSize: count * rowHeight, measure: () => {} };\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/hooks/use-gantt-virtual.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/hooks/use-gantt-edit.ts",
      "content": "\"use client\";\n\n/**\n * The editing state machine (v0.2.0). Owns the transient edit-UI targets\n * (detail-editor + inline-rename) and the mutation dispatchers. Every dispatcher\n * is a single chokepoint: re-check permission (veto-before-dispatch), compute the\n * NEXT forest from `data` via the pure `edit-mutations`, fire the typed\n * task-card-shaped event, then `onChange(next)`. No internal copy of `data`\n * — the controlled consumer echoes. When `editable` is false, `can()` returns\n * false so every dispatcher no-ops (the v1 read-only guarantee).\n */\n\nimport { useCallback, useMemo, useState } from \"react\";\nimport type {\n  GanttComposerTarget,\n  GanttEditAction,\n  GanttSnap,\n  TaskFieldEditedEvent,\n  TaskItem,\n  TaskItemAddedEvent,\n  TaskItemMovedEvent,\n  TaskItemRemovedEvent,\n  TaskPermissionReason,\n  TaskPermissionRule,\n  TaskPermissions,\n  TaskStatusChangedEvent,\n  TaskStatusOption,\n} from \"../types\";\nimport {\n  addItem,\n  buildIndex,\n  isAncestor,\n  moveItem,\n  removeItem,\n  renameItem,\n  setWindow,\n  shiftSubtree,\n  subtreeLeaves,\n} from \"../lib/edit-mutations\";\nimport { parseGanttDate } from \"../lib/geometry\";\nimport { evalGanttPermission } from \"../lib/edit-permissions\";\nimport {\n  copyTasksToClipboard,\n  reassignTaskIds,\n} from \"../../task-card/lib/clipboard\";\n\ntype Args = {\n  data: TaskItem[];\n  editable: boolean;\n  snap: GanttSnap;\n  statusOptions?: TaskStatusOption[];\n  onChange?: (data: TaskItem[]) => void;\n  onTaskReschedule?: (next: {\n    itemId: string;\n    startAt: string;\n    expireAt?: string;\n  }) => void;\n  onItemAdded?: (e: TaskItemAddedEvent) => void;\n  onItemRemoved?: (e: TaskItemRemovedEvent) => void;\n  onItemMoved?: (e: TaskItemMovedEvent) => void;\n  onFieldEdited?: (e: TaskFieldEditedEvent) => void;\n  onStatusChanged?: (e: TaskStatusChangedEvent) => void;\n  permissions?: TaskPermissions;\n  canMoveItem?: (id: string) => boolean;\n  canResizeItem?: (id: string) => boolean;\n  canDeleteItem?: (id: string) => boolean;\n  canCreateChild?: (id: string) => boolean;\n  canEditItem?: (id: string) => boolean;\n  onPermissionDenied?: (\n    action: keyof TaskPermissionRule,\n    itemId: string,\n    reason: TaskPermissionReason,\n  ) => void;\n};\n\nconst ACTION_RULE: Record<GanttEditAction, keyof TaskPermissionRule> = {\n  move: \"drag\",\n  resize: \"drag\",\n  delete: \"remove\",\n  create: \"addChildren\",\n  editDetails: \"edit\",\n};\n\nfunction freshId(): string {\n  if (typeof crypto !== \"undefined\" && \"randomUUID\" in crypto) {\n    return `gt-${crypto.randomUUID()}`;\n  }\n  return `gt-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;\n}\n\nexport function useGanttEdit(args: Args) {\n  const {\n    data,\n    editable,\n    snap,\n    statusOptions,\n    onChange,\n    onTaskReschedule,\n    onItemAdded,\n    onItemRemoved,\n    onItemMoved,\n    onFieldEdited,\n    onStatusChanged,\n    permissions,\n    canMoveItem,\n    canResizeItem,\n    canDeleteItem,\n    canCreateChild,\n    canEditItem,\n    onPermissionDenied,\n  } = args;\n\n  const index = useMemo(() => buildIndex(data), [data]);\n  const [editingId, setEditingId] = useState<string | null>(null);\n  const [renamingId, setRenamingId] = useState<string | null>(null);\n  const [composerTarget, setComposerTarget] =\n    useState<GanttComposerTarget | null>(null);\n\n  const nodeInfo = useCallback(\n    (id: string) => {\n      const info = index.get(id);\n      return info\n        ? { parentId: info.parentId, index: info.index, level: info.level }\n        : undefined;\n    },\n    [index],\n  );\n\n  const predicateFor = useCallback(\n    (action: GanttEditAction): ((id: string) => boolean) | undefined => {\n      switch (action) {\n        case \"move\":\n          return canMoveItem;\n        case \"resize\":\n          return canResizeItem;\n        case \"delete\":\n          return canDeleteItem;\n        case \"create\":\n          return canCreateChild;\n        case \"editDetails\":\n          return canEditItem;\n      }\n    },\n    [canMoveItem, canResizeItem, canDeleteItem, canCreateChild, canEditItem],\n  );\n\n  const can = useCallback(\n    (action: GanttEditAction, item: TaskItem): boolean => {\n      if (!editable) return false;\n      const level = index.get(item.id)?.level ?? 1;\n      if (!evalGanttPermission(permissions, action, item, level)) return false;\n      const pred = predicateFor(action);\n      if (pred && !pred(item.id)) return false;\n      return true;\n    },\n    [editable, index, permissions, predicateFor],\n  );\n\n  /** Guard a dispatch: return the item if allowed, else report denial + null. */\n  const guard = useCallback(\n    (action: GanttEditAction, id: string): TaskItem | null => {\n      const item = index.get(id)?.item;\n      if (!item) return null;\n      if (can(action, item)) return item;\n      const reason: TaskPermissionReason = item.locked\n        ? \"locked\"\n        : predicateFor(action)?.(id) === false\n          ? \"predicate\"\n          : \"default\";\n      onPermissionDenied?.(ACTION_RULE[action], id, reason);\n      return null;\n    },\n    [index, can, predicateFor, onPermissionDenied],\n  );\n\n  const rescheduleItem = useCallback(\n    (\n      id: string,\n      patch: { startAt?: string; expireAt?: string; duration?: number },\n      kind: \"move\" | \"resize\",\n    ) => {\n      const item = guard(kind, id);\n      if (!item) return;\n      const next = setWindow(data, id, patch);\n      if (next === data) return;\n      const updated = buildIndex(next).get(id)?.item;\n      if (!updated) return;\n      // Each field event is gated on the patch actually touching that key AND on\n      // the value really changing. `setWindow` re-serializes `expireAt` whenever\n      // the item has one (even on a start-only resize), so compare by instant —\n      // a non-canonical stored date (e.g. `+03:00` offset) must not fire a phantom\n      // event whose old/new are the same moment.\n      if (\n        patch.startAt != null &&\n        parseGanttDate(updated.startAt) !== parseGanttDate(item.startAt)\n      ) {\n        onFieldEdited?.({\n          itemId: id,\n          key: \"startAt\",\n          oldValue: item.startAt,\n          newValue: updated.startAt,\n        });\n      }\n      if (\n        patch.expireAt != null &&\n        parseGanttDate(updated.expireAt) !== parseGanttDate(item.expireAt)\n      ) {\n        onFieldEdited?.({\n          itemId: id,\n          key: \"expireAt\",\n          oldValue: item.expireAt,\n          newValue: updated.expireAt,\n        });\n      }\n      if (patch.duration != null && updated.duration !== item.duration) {\n        onFieldEdited?.({\n          itemId: id,\n          key: \"duration\",\n          oldValue: item.duration,\n          newValue: updated.duration,\n        });\n      }\n      onTaskReschedule?.({\n        itemId: id,\n        startAt: updated.startAt ?? updated.setAt,\n        expireAt: updated.expireAt,\n      });\n      onChange?.(next);\n    },\n    [data, guard, onFieldEdited, onTaskReschedule, onChange],\n  );\n\n  const createItem = useCallback(\n    (\n      parentId: string | null,\n      seed?: Partial<TaskItem>,\n      at?: number,\n      opts?: { openEditor?: boolean },\n    ) => {\n      // Root create gates on `editable` only; child create gates the PARENT's\n      // addChildren rule.\n      if (!editable) return;\n      if (parentId != null && !guard(\"create\", parentId)) return;\n      const nowIso = seed?.setAt ?? new Date().toISOString();\n      const item: TaskItem = {\n        id: seed?.id ?? freshId(),\n        name: seed?.name ?? \"New task\",\n        status: seed?.status ?? statusOptions?.[0]?.value ?? \"todo\",\n        active: seed?.active ?? true,\n        setAt: nowIso,\n        ...seed,\n      };\n      const next = addItem(data, parentId, item, at);\n      onItemAdded?.({ parentId: parentId ?? \"\", item });\n      onChange?.(next);\n      // v0.5.0 — quick-composer \"More options\" opens the detail editor on the new item.\n      if (opts?.openEditor) setEditingId(item.id);\n    },\n    [editable, guard, statusOptions, data, onItemAdded, onChange],\n  );\n\n  const deleteItem = useCallback(\n    (id: string) => {\n      if (!guard(\"delete\", id)) return;\n      const { next, removed, parentId } = removeItem(data, id);\n      if (!removed) return;\n      onItemRemoved?.({ itemId: id, removed, parentId: parentId ?? \"\" });\n      onChange?.(next);\n      if (editingId === id) setEditingId(null);\n      if (renamingId === id) setRenamingId(null);\n    },\n    [data, guard, onItemRemoved, onChange, editingId, renamingId],\n  );\n\n  const renameItemAction = useCallback(\n    (id: string, name: string) => {\n      const item = guard(\"editDetails\", id);\n      if (!item || name === item.name) return;\n      const next = renameItem(data, id, name);\n      onFieldEdited?.({\n        itemId: id,\n        key: \"name\",\n        oldValue: item.name,\n        newValue: name,\n      });\n      onChange?.(next);\n    },\n    [data, guard, onFieldEdited, onChange],\n  );\n\n  const moveItemAction = useCallback(\n    (id: string, newParentId: string | null, newIndex: number) => {\n      const item = guard(\"move\", id);\n      if (!item) return;\n      // Circular drop is a structural invalid, not a permission denial — no-op.\n      if (newParentId != null && (newParentId === id || isAncestor(data, id, newParentId)))\n        return;\n      const from = index.get(id);\n      // Same-parent move-down: removing the source shifts indices, so the drop\n      // index is one too far. (task-tree semantics.)\n      let targetIndex = newIndex;\n      if (from && (from.parentId ?? null) === newParentId && from.index < newIndex) {\n        targetIndex = newIndex - 1;\n      }\n      const next = moveItem(data, id, newParentId, targetIndex);\n      if (next === data) return;\n      onItemMoved?.({\n        itemId: id,\n        oldParentId: from?.parentId ?? \"\",\n        newParentId: newParentId ?? \"\",\n        oldIndex: from?.index ?? 0,\n        newIndex: targetIndex,\n      });\n      onChange?.(next);\n    },\n    [data, guard, index, onItemMoved, onChange],\n  );\n\n  /* ── group-move (v0.3.0) ── */\n\n  /** Atomic gate: the summary is movable AND every descendant leaf is movable. */\n  const canGroupMove = useCallback(\n    (item: TaskItem): boolean => {\n      if (!editable || !can(\"move\", item)) return false;\n      const leaves = subtreeLeaves(item);\n      return leaves.length > 0 && leaves.every((l) => can(\"move\", l));\n    },\n    [editable, can],\n  );\n\n  /** Shift a summary's whole subtree by `deltaMs` — single-move applied per leaf. */\n  const moveSubtree = useCallback(\n    (id: string, deltaMs: number) => {\n      const summary = guard(\"move\", id); // reports denial if the summary itself is blocked\n      if (!summary) return;\n      const leaves = subtreeLeaves(summary);\n      if (leaves.length === 0) return;\n      // Atomic (D23): a single blocked leaf vetoes the whole group; report + abort.\n      for (const leaf of leaves) {\n        if (!can(\"move\", leaf)) {\n          const reason: TaskPermissionReason = leaf.locked\n            ? \"locked\"\n            : canMoveItem?.(leaf.id) === false\n              ? \"predicate\"\n              : \"default\";\n          onPermissionDenied?.(\"drag\", leaf.id, reason);\n          return;\n        }\n      }\n      if (deltaMs === 0) return;\n      const next = shiftSubtree(data, id, deltaMs);\n      if (next === data) return;\n      const nextIndex = buildIndex(next);\n      // D25 — per-leaf field events (parity with single-move) + one onChange (= one undo step).\n      for (const leaf of leaves) {\n        const updated = nextIndex.get(leaf.id)?.item;\n        if (!updated) continue;\n        onFieldEdited?.({\n          itemId: leaf.id,\n          key: \"startAt\",\n          oldValue: leaf.startAt,\n          newValue: updated.startAt,\n        });\n        if (updated.expireAt !== leaf.expireAt) {\n          onFieldEdited?.({\n            itemId: leaf.id,\n            key: \"expireAt\",\n            oldValue: leaf.expireAt,\n            newValue: updated.expireAt,\n          });\n        }\n        onTaskReschedule?.({\n          itemId: leaf.id,\n          startAt: updated.startAt ?? updated.setAt,\n          expireAt: updated.expireAt,\n        });\n      }\n      onChange?.(next);\n    },\n    [\n      data,\n      can,\n      guard,\n      canMoveItem,\n      onPermissionDenied,\n      onFieldEdited,\n      onTaskReschedule,\n      onChange,\n    ],\n  );\n\n  const changeStatus = useCallback(\n    (id: string, status: string) => {\n      const item = guard(\"editDetails\", id);\n      if (!item || status === item.status) return;\n      const apply = (items: TaskItem[]): TaskItem[] =>\n        items.map((it) =>\n          it.id === id\n            ? { ...it, status }\n            : it.children?.length\n              ? { ...it, children: apply(it.children) }\n              : it,\n        );\n      onStatusChanged?.({ itemId: id, oldStatus: item.status, newStatus: status });\n      onFieldEdited?.({\n        itemId: id,\n        key: \"status\",\n        oldValue: item.status,\n        newValue: status,\n      });\n      onChange?.(apply(data));\n    },\n    [data, guard, onStatusChanged, onFieldEdited, onChange],\n  );\n\n  const changePriority = useCallback(\n    (id: string, priority: string) => {\n      const item = guard(\"editDetails\", id);\n      if (!item || priority === item.priority) return;\n      // \"priority\" is not a `TaskEditableField`, so no typed field event — the\n      // forest echo carries it (parity with calendar + the card).\n      const apply = (items: TaskItem[]): TaskItem[] =>\n        items.map((it) =>\n          it.id === id\n            ? { ...it, priority }\n            : it.children?.length\n              ? { ...it, children: apply(it.children) }\n              : it,\n        );\n      onChange?.(apply(data));\n    },\n    [data, guard, onChange],\n  );\n\n  /* ── quick-create composer (v0.5.0) ── */\n  const openComposer = useCallback(\n    (target: GanttComposerTarget) => {\n      if (!editable) return;\n      // Gate the create up-front so we never float a composer that will no-op.\n      if (target.parentId != null && !guard(\"create\", target.parentId)) return;\n      setComposerTarget(target);\n    },\n    [editable, guard],\n  );\n  const closeComposer = useCallback(() => setComposerTarget(null), []);\n\n  /* ── cross-surface clipboard (v0.5.0) ── */\n  const copyItem = useCallback(\n    (id: string) => {\n      const item = index.get(id)?.item;\n      if (!item) return;\n      // `copyTasksToClipboard` rejects when `navigator.clipboard` is missing\n      // or the write is denied — swallow-and-report instead of leaking an\n      // unhandled rejection.\n      copyTasksToClipboard([item], \"gantt-timeline\").catch(() => {\n        if (process.env.NODE_ENV !== \"production\") {\n          console.warn(\"[gantt-timeline] copyItem: clipboard write failed\");\n        }\n      });\n    },\n    [index],\n  );\n  const cutItem = useCallback(\n    (id: string) => {\n      const item = guard(\"delete\", id);\n      if (!item) return;\n      // Await the async clipboard write; delete ONLY on fulfillment so a\n      // denied/unavailable clipboard can't destroy the item with nothing\n      // copied. On failure: report, don't throw — the cut is aborted.\n      copyTasksToClipboard([item], \"gantt-timeline\").then(\n        () => deleteItem(id),\n        () => {\n          if (process.env.NODE_ENV !== \"production\") {\n            console.warn(\n              \"[gantt-timeline] cutItem: clipboard write failed — cut aborted, item was NOT removed\",\n            );\n          }\n        },\n      );\n    },\n    [guard, deleteItem],\n  );\n  const pasteTasks = useCallback(\n    (items: TaskItem[], parentId: string | null, atIndex?: number) => {\n      if (!editable || items.length === 0) return;\n      if (parentId != null && !guard(\"create\", parentId)) return;\n      let next = data;\n      const created: TaskItem[] = [];\n      let at = atIndex;\n      for (const raw of items) {\n        // Re-id every grafted subtree so a paste can't collide; dates preserved\n        // (gantt has no \"drop window\" — the bar lands where it was copied from).\n        const root = reassignTaskIds(raw);\n        next = addItem(next, parentId, root, at);\n        created.push(root);\n        if (at != null) at += 1;\n      }\n      if (next === data) return;\n      created.forEach((item) =>\n        onItemAdded?.({ parentId: parentId ?? \"\", item }),\n      );\n      onChange?.(next);\n    },\n    [editable, guard, data, onItemAdded, onChange],\n  );\n\n  /** Splice an edited subtree (same root id) from the embedded card back in. */\n  const applyEditedSubtree = useCallback(\n    (nextItem: TaskItem) => {\n      const prev = index.get(nextItem.id)?.item;\n      if (!prev) {\n        // The item was deleted (another path) while its editor was open. Splicing\n        // an absent id would be a no-op map and echo the UNCHANGED forest, silently\n        // dropping the edit. Drop the stale edit and close instead.\n        setEditingId(null);\n        return;\n      }\n      const apply = (items: TaskItem[]): TaskItem[] =>\n        items.map((it) =>\n          it.id === nextItem.id\n            ? nextItem\n            : it.children?.length\n              ? { ...it, children: apply(it.children) }\n              : it,\n        );\n      const forest = apply(data);\n      // Emit a granular field event per changed editable field, so a consumer\n      // persisting via `onFieldEdited` sees detail-editor edits too — not only\n      // the consolidated forest echo (parity with calendar's v0.2.2 A1 fix).\n      // The embedded card's own granular events are not wired (the editor\n      // passes only `onChange`), so there is no double-fire. `priority` is\n      // intentionally excluded — it is not a `TaskEditableField`, so it\n      // persists via `onChange` only (parity with `changePriority`).\n      const FIELDS: TaskFieldEditedEvent[\"key\"][] = [\n        \"name\",\n        \"description\",\n        \"status\",\n        \"active\",\n        \"setAt\",\n        \"startAt\",\n        \"expireAt\",\n        \"duration\",\n      ];\n      for (const key of FIELDS) {\n        const oldValue = prev[key];\n        const newValue = nextItem[key];\n        if (!Object.is(oldValue, newValue)) {\n          onFieldEdited?.({ itemId: nextItem.id, key, oldValue, newValue });\n        }\n      }\n      if (prev.status !== nextItem.status) {\n        onStatusChanged?.({\n          itemId: nextItem.id,\n          oldStatus: prev.status,\n          newStatus: nextItem.status,\n        });\n      }\n      onChange?.(forest);\n    },\n    [data, index, onFieldEdited, onStatusChanged, onChange],\n  );\n\n  const openEditor = useCallback(\n    (id: string) => {\n      if (guard(\"editDetails\", id)) setEditingId(id);\n    },\n    [guard],\n  );\n  const closeEditor = useCallback(() => setEditingId(null), []);\n  const beginRename = useCallback(\n    (id: string) => {\n      if (guard(\"editDetails\", id)) setRenamingId(id);\n    },\n    [guard],\n  );\n  const endRename = useCallback(() => setRenamingId(null), []);\n\n  return {\n    editable,\n    snap,\n    can,\n    canGroupMove,\n    nodeInfo,\n    rescheduleItem,\n    createItem,\n    deleteItem,\n    renameItemAction,\n    moveItemAction,\n    moveSubtree,\n    changeStatus,\n    changePriority,\n    editingId,\n    openEditor,\n    closeEditor,\n    applyEditedSubtree,\n    renamingId,\n    beginRename,\n    endRename,\n    composerTarget,\n    openComposer,\n    closeComposer,\n    copyItem,\n    cutItem,\n    pasteTasks,\n  };\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/hooks/use-gantt-edit.ts"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/parts/bar-tooltip-full.tsx",
      "content": "\"use client\";\n\nimport { lazy, Suspense } from \"react\";\nimport type { TaskItem } from \"../types\";\n\n// The ONLY module that imports task-card's VALUE, and only lazily — so the\n// card never enters a consumer's bundle unless they opt into the full-card\n// tooltip via `renderTooltip={(item) => <GanttFullCardTooltip item={item} />}`.\nconst TaskCardLazy = lazy(() =>\n  import(\"../../task-card\").then((m) => ({ default: m.TaskCard })),\n);\n\nexport function GanttFullCardTooltip({ item }: { item: TaskItem }) {\n  return (\n    <div className=\"w-72\">\n      <Suspense\n        fallback={\n          <div className=\"p-2 text-xs text-muted-foreground\">Loading…</div>\n        }\n      >\n        <TaskCardLazy defaultValue={item} editable={false} />\n      </Suspense>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/parts/bar-tooltip-full.tsx"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/parts/gantt-context-menu.tsx",
      "content": "\"use client\";\n\n/**\n * Tier-C right-click action menu (v0.2.0). Wraps a target (a body bar row or a\n * gutter row) and offers permission-gated Edit / Rename / Add child / Add sibling\n * / Status / Delete. Every action routes through the same `use-gantt-edit`\n * dispatchers as the pointer + keyboard paths (single mutation chokepoint). When\n * editing is off or nothing is permitted, it renders the child unwrapped — zero\n * overhead in the v1 read-only path.\n */\n\nimport type { ReactNode } from \"react\";\nimport {\n  ContextMenu,\n  ContextMenuContent,\n  ContextMenuItem,\n  ContextMenuSeparator,\n  ContextMenuSub,\n  ContextMenuSubContent,\n  ContextMenuSubTrigger,\n  ContextMenuTrigger,\n} from \"@/components/ui/context-menu\";\nimport { useGanttTimeline } from \"../hooks/use-gantt-context\";\nimport type { TaskItem } from \"../types\";\n\nexport function GanttContextMenu({\n  item,\n  children,\n}: {\n  item: TaskItem;\n  children: ReactNode;\n}) {\n  const ctx = useGanttTimeline();\n\n  const canEdit = ctx.editable && ctx.can(\"editDetails\", item);\n  // \"Add child task\" creates UNDER this item → gated on the item's own rule.\n  const canCreate = ctx.editable && ctx.can(\"create\", item);\n  // \"Add task below\" creates a SIBLING under this item's PARENT → must gate on the\n  // parent's rule (which is what `createItem` actually enforces), else the item\n  // shows then no-ops + fires onPermissionDenied. Root items (no parent) gate on\n  // `editable` only, matching `createItem`'s root-insert path.\n  const parentId = ctx.nodeInfo(item.id)?.parentId ?? null;\n  const parentNode = parentId != null ? ctx.getItem(parentId) : null;\n  const canCreateSibling =\n    ctx.editable &&\n    (parentId == null ? true : !!parentNode && ctx.can(\"create\", parentNode));\n  const canDelete = ctx.editable && ctx.can(\"delete\", item);\n  const statusOptions = ctx.statusOptions ?? [];\n  const priorityOptions = ctx.priorityOptions ?? [];\n\n  if (!canEdit && !canCreate && !canCreateSibling && !canDelete)\n    return <>{children}</>;\n\n  return (\n    <ContextMenu>\n      {/* F-cross-13 path-b: `asChild` is Radix-only (Base UI rejects it). The\n          trigger renders its own wrapper element (a <span> — non-button in both\n          backends); `contents` makes it box-less so layout is untouched, and\n          right-click / long-press bubble up from the child to the trigger's\n          listeners — no prop injection into `children` needed. (v0.5.2) */}\n      <ContextMenuTrigger className=\"contents\">{children}</ContextMenuTrigger>\n      <ContextMenuContent className=\"w-48\">\n        {canEdit ? (\n          <>\n            <ContextMenuItem onSelect={() => ctx.openEditor(item.id)}>\n              Edit…\n            </ContextMenuItem>\n            <ContextMenuItem onSelect={() => ctx.beginRename(item.id)}>\n              Rename\n            </ContextMenuItem>\n          </>\n        ) : null}\n\n        {canCreate ? (\n          <ContextMenuItem onSelect={() => ctx.createItem(item.id)}>\n            Add child task\n          </ContextMenuItem>\n        ) : null}\n\n        {canCreateSibling ? (\n          <ContextMenuItem\n            onSelect={() => {\n              const info = ctx.nodeInfo(item.id);\n              ctx.createItem(\n                info?.parentId ?? null,\n                undefined,\n                (info?.index ?? 0) + 1,\n              );\n            }}\n          >\n            Add task below\n          </ContextMenuItem>\n        ) : null}\n\n        {canEdit && statusOptions.length > 0 ? (\n          <>\n            <ContextMenuSeparator />\n            <ContextMenuSub>\n              <ContextMenuSubTrigger>Status</ContextMenuSubTrigger>\n              <ContextMenuSubContent>\n                {statusOptions.map((o) => (\n                  <ContextMenuItem\n                    key={o.value}\n                    onSelect={() => ctx.changeStatus(item.id, o.value)}\n                  >\n                    {o.icon ? `${o.icon} ` : \"\"}\n                    {o.label}\n                  </ContextMenuItem>\n                ))}\n              </ContextMenuSubContent>\n            </ContextMenuSub>\n          </>\n        ) : null}\n\n        {canEdit && priorityOptions.length > 0 ? (\n          <ContextMenuSub>\n            <ContextMenuSubTrigger>Priority</ContextMenuSubTrigger>\n            <ContextMenuSubContent>\n              {priorityOptions.map((o) => (\n                <ContextMenuItem\n                  key={o.value}\n                  onSelect={() => ctx.changePriority(item.id, o.value)}\n                >\n                  {o.label}\n                </ContextMenuItem>\n              ))}\n            </ContextMenuSubContent>\n          </ContextMenuSub>\n        ) : null}\n\n        <ContextMenuSeparator />\n        <ContextMenuItem onSelect={() => ctx.copyItem(item.id)}>\n          Copy\n        </ContextMenuItem>\n        {canDelete ? (\n          <ContextMenuItem onSelect={() => ctx.cutItem(item.id)}>\n            Cut\n          </ContextMenuItem>\n        ) : null}\n\n        {canDelete ? (\n          <>\n            <ContextMenuSeparator />\n            <ContextMenuItem\n              variant=\"destructive\"\n              onSelect={() => ctx.deleteItem(item.id)}\n            >\n              Delete\n            </ContextMenuItem>\n          </>\n        ) : null}\n      </ContextMenuContent>\n    </ContextMenu>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/parts/gantt-context-menu.tsx"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/parts/gantt-edit-popover.tsx",
      "content": "\"use client\";\n\n/**\n * Detail editor (v0.2.0). A centered modal overlay — a plain backdrop + panel,\n * NOT the shadcn `popover` primitive — so it sidesteps the Radix/Base-UI `asChild`\n * divergence the v1 tooltip avoided the same way. It hosts the lazy\n * `<TaskCard editable>`; the card's `onChange` subtree is spliced back into\n * the forest via `applyEditedSubtree`. The card VALUE loads only when an editor\n * actually opens (React.lazy), so it never weighs on the default bundle.\n */\n\nimport { Suspense, lazy, useEffect } from \"react\";\nimport { useGanttTimeline } from \"../hooks/use-gantt-context\";\n\nconst TaskCardLazy = lazy(() =>\n  import(\"../../task-card\").then((m) => ({ default: m.TaskCard })),\n);\n\nexport function GanttEditPopover() {\n  const ctx = useGanttTimeline();\n  const id = ctx.editingId;\n  const closeEditor = ctx.closeEditor;\n\n  useEffect(() => {\n    if (id == null) return;\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") closeEditor();\n    };\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  }, [id, closeEditor]);\n\n  if (id == null) return null;\n  const item = ctx.getItem(id);\n  if (!item) return null;\n\n  return (\n    <div\n      role=\"dialog\"\n      aria-modal=\"true\"\n      aria-label={`Edit ${item.name}`}\n      className=\"fixed inset-0 z-50 flex items-center justify-center p-4\"\n    >\n      <button\n        type=\"button\"\n        aria-label=\"Close editor\"\n        onClick={closeEditor}\n        className=\"absolute inset-0 cursor-default bg-background/70 backdrop-blur-sm\"\n      />\n      <div className=\"relative z-10 w-full max-w-sm\">\n        <Suspense\n          fallback={\n            <div className=\"rounded-lg border border-border bg-card p-6 text-center text-sm text-muted-foreground\">\n              Loading editor…\n            </div>\n          }\n        >\n          <TaskCardLazy\n            value={item}\n            editable\n            statusOptions={ctx.statusOptions}\n            priorityOptions={ctx.priorityOptions}\n            labelOptions={ctx.labelOptions}\n            permissions={ctx.permissions}\n            onChange={(next) => ctx.applyEditedSubtree(next)}\n          />\n        </Suspense>\n        <div className=\"mt-2 flex justify-end\">\n          <button\n            type=\"button\"\n            onClick={closeEditor}\n            className=\"rounded-md border border-border bg-card px-3 py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-muted\"\n          >\n            Done\n          </button>\n        </div>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/parts/gantt-edit-popover.tsx"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/parts/gantt-quick-composer.tsx",
      "content": "\"use client\";\n\n/**\n * Quick-create composer (Tier B + Tier C). When a double-click on an empty row\n * area sets `composerTarget`, this floats a small title-entry popup at the\n * pointer: type a name + Enter to create, or \"More options\" to open the full\n * editor on the new task. Deliberately a plain fixed-position panel (NOT a Radix\n * Popover) to dodge the Base-UI anchor/asChild divergence — mirrors calendar's\n * quick-composer. A native `<select>` keeps the status pick dep-free.\n *\n * Mounted by the Root (lives inside `GanttTimelineRoot`); reads context.\n */\n\nimport { useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { useGanttTimeline } from \"../hooks/use-gantt-context\";\nimport type {\n  GanttComposerTarget,\n  GanttContextValue,\n  TaskItem,\n} from \"../types\";\n\nconst iso = (ms: number) => new Date(ms).toISOString();\n\nfunction whenText(t: GanttComposerTarget): string {\n  const start = new Date(t.startMs).toLocaleDateString();\n  if (t.endMs == null || t.endMs <= t.startMs) return start;\n  const end = new Date(t.endMs).toLocaleDateString();\n  return start === end ? start : `${start} → ${end}`;\n}\n\nfunction Floating({\n  x,\n  y,\n  onClose,\n  children,\n}: {\n  x: number;\n  y: number;\n  onClose: () => void;\n  children: ReactNode;\n}) {\n  return (\n    <>\n      <div className=\"fixed inset-0 z-40\" onClick={onClose} aria-hidden />\n      <div\n        role=\"dialog\"\n        aria-label=\"Create task\"\n        className=\"fixed z-50 w-64 rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-lg\"\n        style={{ left: x, top: y }}\n      >\n        {children}\n      </div>\n    </>\n  );\n}\n\nfunction ComposerPopup({\n  target,\n  onClose,\n  onCreate,\n  statusOptions,\n  render,\n}: {\n  target: GanttComposerTarget;\n  onClose: () => void;\n  onCreate: GanttContextValue[\"createItem\"];\n  statusOptions: GanttContextValue[\"statusOptions\"];\n  render?: GanttContextValue[\"renderQuickComposer\"];\n}) {\n  const [title, setTitle] = useState(\"\");\n  const [status, setStatus] = useState(statusOptions?.[0]?.value ?? \"\");\n\n  const seedOf = (extra?: Partial<TaskItem>): Partial<TaskItem> => ({\n    name: title.trim() || \"New task\",\n    startAt: iso(target.startMs),\n    setAt: iso(target.startMs),\n    ...(target.endMs != null ? { expireAt: iso(target.endMs) } : {}),\n    ...(status ? { status } : {}),\n    ...extra,\n  });\n  const commit = (extra?: Partial<TaskItem>) => {\n    onCreate(target.parentId, seedOf(extra), target.index);\n    onClose();\n  };\n  const openFull = () => {\n    onCreate(target.parentId, seedOf(), target.index, { openEditor: true });\n    onClose();\n  };\n\n  const vw = typeof window !== \"undefined\" ? window.innerWidth : 1024;\n  const vh = typeof window !== \"undefined\" ? window.innerHeight : 768;\n  const px = Math.max(8, Math.min(target.x ?? 80, vw - 272));\n  const py = Math.max(8, Math.min(target.y ?? 80, vh - 200));\n\n  if (render) {\n    return (\n      <Floating x={px} y={py} onClose={onClose}>\n        {render({\n          startMs: target.startMs,\n          endMs: target.endMs,\n          commit: (seed) => commit(seed),\n          cancel: onClose,\n          openFull,\n        })}\n      </Floating>\n    );\n  }\n\n  return (\n    <Floating x={px} y={py} onClose={onClose}>\n      <form\n        onSubmit={(e) => {\n          e.preventDefault();\n          commit();\n        }}\n        className=\"flex flex-col gap-2\"\n      >\n        <p className=\"text-xs text-muted-foreground\">{whenText(target)}</p>\n        <Input\n          autoFocus\n          value={title}\n          onChange={(e) => setTitle(e.target.value)}\n          onKeyDown={(e) => {\n            if (e.key === \"Escape\") onClose();\n          }}\n          placeholder=\"Task name\"\n          className=\"h-8\"\n        />\n        {statusOptions && statusOptions.length > 0 ? (\n          <select\n            value={status}\n            onChange={(e) => setStatus(e.target.value)}\n            className=\"h-8 rounded-md border border-input bg-transparent px-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/50\"\n            aria-label=\"Status\"\n          >\n            {statusOptions.map((o) => (\n              <option key={o.value} value={o.value}>\n                {o.label}\n              </option>\n            ))}\n          </select>\n        ) : null}\n        <div className=\"flex items-center justify-between\">\n          <button\n            type=\"button\"\n            onClick={openFull}\n            className=\"text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline\"\n          >\n            More options\n          </button>\n          <div className=\"flex gap-1.5\">\n            <Button type=\"button\" size=\"sm\" variant=\"ghost\" onClick={onClose}>\n              Cancel\n            </Button>\n            <Button type=\"submit\" size=\"sm\">\n              Create\n            </Button>\n          </div>\n        </div>\n      </form>\n    </Floating>\n  );\n}\n\nexport function GanttQuickComposer() {\n  const { composerTarget, closeComposer, createItem, renderQuickComposer, statusOptions } =\n    useGanttTimeline();\n  if (!composerTarget) return null;\n  return (\n    <ComposerPopup\n      key={`${composerTarget.startMs}:${composerTarget.x ?? 0}:${composerTarget.y ?? 0}`}\n      target={composerTarget}\n      onClose={closeComposer}\n      onCreate={createItem}\n      statusOptions={statusOptions}\n      render={renderQuickComposer}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/parts/gantt-quick-composer.tsx"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/parts/gantt-bars.tsx",
      "content": "\"use client\";\n\nimport type { HTMLAttributes } from \"react\";\nimport { Avatar, AvatarFallback, AvatarImage } from \"@/components/ui/avatar\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { cn } from \"@/lib/utils\";\nimport type { TaskItem, TaskStatusOption } from \"../types\";\nimport { effEndMs, effStartMs } from \"../lib/geometry\";\n\n/* ───────── helpers ───────── */\n\nfunction initials(name: string): string {\n  return name\n    .split(/\\s+/)\n    .map((p) => p[0])\n    .filter(Boolean)\n    .slice(0, 2)\n    .join(\"\")\n    .toUpperCase();\n}\n\nfunction fmtDate(ms: number): string {\n  return new Intl.DateTimeFormat(undefined, {\n    month: \"short\",\n    day: \"numeric\",\n    year: \"numeric\",\n  }).format(new Date(ms));\n}\n\n/* ───────── GanttBar (Tier C) ───────── */\n\nexport type GanttBarProps = {\n  leftPx: number;\n  widthPx: number;\n  fill: string;\n  rowHeight: number;\n  overdue?: boolean;\n  inactive?: boolean;\n  locked?: boolean;\n  priorityColor?: string;\n  selected?: boolean;\n  /** v0.2.0 — grab cursor for drag-to-reschedule. */\n  movable?: boolean;\n  /** v0.2.0 — render left/right edge resize handles (`data-edge`). */\n  resizable?: boolean;\n} & HTMLAttributes<HTMLDivElement>;\n\nexport function GanttBar({\n  leftPx,\n  widthPx,\n  fill,\n  rowHeight,\n  overdue,\n  inactive,\n  locked,\n  priorityColor,\n  selected,\n  movable,\n  resizable,\n  className,\n  style,\n  ...rest\n}: GanttBarProps) {\n  const barH = Math.max(10, Math.min(rowHeight - 12, 22));\n  return (\n    <div\n      data-selected={selected || undefined}\n      className={cn(\n        \"absolute top-1/2 -translate-y-1/2 rounded-[5px] shadow-sm ring-offset-background transition-shadow\",\n        movable ? \"cursor-grab active:cursor-grabbing\" : \"cursor-pointer\",\n        \"outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1\",\n        \"data-[selected]:ring-2 data-[selected]:ring-foreground/70 data-[selected]:ring-offset-1\",\n        inactive && \"opacity-50\",\n        className,\n      )}\n      style={{\n        left: leftPx,\n        width: Math.max(widthPx, 6),\n        height: barH,\n        background: fill,\n        ...style,\n      }}\n      {...rest}\n    >\n      {priorityColor ? (\n        <span\n          aria-hidden\n          // dir-ok: bar sits on a physical LTR time axis (inline left/width, pointer clientX drag), so its edges stay physical\n          className=\"absolute left-0 top-0 h-full w-1 rounded-l-[5px]\"\n          style={{ background: priorityColor }}\n        />\n      ) : null}\n      {overdue ? (\n        <span\n          aria-hidden\n          // dir-ok: bar sits on a physical LTR time axis (inline left/width, pointer clientX drag), so its edges stay physical\n          className=\"absolute inset-y-0 right-0 w-1.5 rounded-r-[5px] bg-destructive\"\n        />\n      ) : null}\n      {locked ? (\n        <span\n          aria-hidden\n          // dir-ok: bar sits on a physical LTR time axis (inline left/width, pointer clientX drag), so its edges stay physical\n          className=\"absolute right-1 top-1/2 -translate-y-1/2 text-[9px] leading-none text-background/80\"\n        >\n          🔒\n        </span>\n      ) : null}\n      {resizable ? (\n        <>\n          <span\n            data-edge=\"start\"\n            aria-hidden\n          // dir-ok: bar sits on a physical LTR time axis (inline left/width, pointer clientX drag), so its edges stay physical\n            className=\"absolute inset-y-0 left-0 w-2 cursor-col-resize rounded-l-[5px] hover:bg-foreground/25\"\n          />\n          <span\n            data-edge=\"end\"\n            aria-hidden\n          // dir-ok: bar sits on a physical LTR time axis (inline left/width, pointer clientX drag), so its edges stay physical\n            className=\"absolute inset-y-0 right-0 w-2 cursor-col-resize rounded-r-[5px] hover:bg-foreground/25\"\n          />\n        </>\n      ) : null}\n    </div>\n  );\n}\n\n/* ───────── SummaryBar (Tier C) ───────── */\n\nexport type SummaryBarProps = {\n  leftPx: number;\n  widthPx: number;\n  selected?: boolean;\n  /** v0.3.0 — grab cursor + enlarged hit area for group-move (drag → shift subtree). */\n  groupMovable?: boolean;\n} & HTMLAttributes<HTMLDivElement>;\n\nexport function SummaryBar({\n  leftPx,\n  widthPx,\n  selected,\n  groupMovable,\n  className,\n  style,\n  ...rest\n}: SummaryBarProps) {\n  return (\n    <div\n      data-selected={selected || undefined}\n      className={cn(\n        \"absolute top-1/2 -translate-y-1/2 rounded-sm bg-foreground/85\",\n        groupMovable ? \"cursor-grab active:cursor-grabbing\" : \"cursor-pointer\",\n        \"outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n        \"data-[selected]:ring-2 data-[selected]:ring-foreground\",\n        className,\n      )}\n      style={{ left: leftPx, width: Math.max(widthPx, 8), height: 7, ...style }}\n      {...rest}\n    >\n      {/* enlarged pointer hit area (visual stays a thin 7px bar) */}\n      {groupMovable ? (\n        <span aria-hidden className=\"absolute -inset-y-2 inset-x-0\" />\n      ) : null}\n      {/* bracket end-caps */}\n      <span\n        aria-hidden\n          // dir-ok: bar sits on a physical LTR time axis (inline left/width, pointer clientX drag), so its edges stay physical\n        className=\"absolute -bottom-1 left-0 h-2 w-1.5 -skew-x-[20deg] bg-foreground/85\"\n      />\n      <span\n        aria-hidden\n          // dir-ok: bar sits on a physical LTR time axis (inline left/width, pointer clientX drag), so its edges stay physical\n        className=\"absolute -bottom-1 right-0 h-2 w-1.5 skew-x-[20deg] bg-foreground/85\"\n      />\n    </div>\n  );\n}\n\n/* ───────── MilestoneDiamond (Tier C) ───────── */\n\nexport type MilestoneDiamondProps = {\n  leftPx: number;\n  fill: string;\n  selected?: boolean;\n  /** v0.2.0 — grab cursor for drag-to-move the instant. */\n  movable?: boolean;\n} & HTMLAttributes<HTMLDivElement>;\n\nexport function MilestoneDiamond({\n  leftPx,\n  fill,\n  selected,\n  movable,\n  className,\n  style,\n  ...rest\n}: MilestoneDiamondProps) {\n  const size = 13;\n  return (\n    <div\n      data-selected={selected || undefined}\n      className={cn(\n        \"absolute top-1/2 rounded-[3px] shadow-sm\",\n        movable ? \"cursor-grab active:cursor-grabbing\" : \"cursor-pointer\",\n        \"outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n        \"data-[selected]:ring-2 data-[selected]:ring-foreground/70\",\n        className,\n      )}\n      style={{\n        left: leftPx - size / 2,\n        width: size,\n        height: size,\n        transform: \"translateY(-50%) rotate(45deg)\",\n        background: fill,\n        ...style,\n      }}\n      {...rest}\n    />\n  );\n}\n\n/* ───────── TodayLine (Tier C) ───────── */\n\nexport function TodayLine({ leftPx }: { leftPx: number }) {\n  return (\n    <div\n      aria-hidden\n      className=\"pointer-events-none absolute inset-y-0 z-10 w-0.5 bg-primary/80\"\n      style={{ left: leftPx }}\n    >\n      <span className=\"absolute -top-px left-1/2 -translate-x-1/2 rounded-b-sm bg-primary px-1 py-0.5 text-[9px] font-medium leading-none text-primary-foreground\">\n        Today\n      </span>\n    </div>\n  );\n}\n\n/* ───────── BarTooltip (Tier C, lightweight default) ───────── */\n\nexport function BarTooltip({\n  item,\n  statusOptions,\n}: {\n  item: TaskItem;\n  statusOptions?: TaskStatusOption[];\n}) {\n  const startMs = effStartMs(item);\n  const endMs = effEndMs(item);\n  const statusOpt = statusOptions?.find((o) => o.value === item.status);\n  return (\n    <div className=\"min-w-44 max-w-72 space-y-1.5\">\n      <div className=\"text-xs font-semibold text-popover-foreground\">\n        {item.name}\n      </div>\n      <div className=\"font-mono text-[11px] text-muted-foreground\">\n        {endMs == null\n          ? `◆ ${fmtDate(startMs)}`\n          : `${fmtDate(startMs)} → ${fmtDate(endMs)}`}\n      </div>\n      <div className=\"flex items-center gap-2 pt-0.5\">\n        {item.targetPerson ? (\n          <span className=\"flex items-center gap-1.5\">\n            <Avatar className=\"size-4\">\n              {item.targetPerson.avatar ? (\n                <AvatarImage\n                  src={item.targetPerson.avatar}\n                  alt={item.targetPerson.name}\n                />\n              ) : null}\n              <AvatarFallback className=\"text-[8px]\">\n                {initials(item.targetPerson.name)}\n              </AvatarFallback>\n            </Avatar>\n            <span className=\"text-[11px] text-muted-foreground\">\n              {item.targetPerson.name}\n            </span>\n          </span>\n        ) : null}\n        {statusOpt ? (\n          <Badge variant={statusOpt.variant ?? \"secondary\"} className=\"text-[10px]\">\n            {statusOpt.icon ? `${statusOpt.icon} ` : \"\"}\n            {statusOpt.label}\n          </Badge>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/parts/gantt-bars.tsx"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/parts/gantt-timeline-axis.tsx",
      "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useGanttTimeline } from \"../hooks/use-gantt-context\";\nimport type { GanttViewport } from \"../types\";\nimport {\n  addUnit,\n  isWeekend,\n  majorLabel,\n  minorLabel,\n  pickScales,\n  ticks,\n  x,\n} from \"../lib/time-scale\";\n\nconst OVERSCAN_PX = 260;\n\n/** Tier C — dumb two-tier header from a viewport. */\nexport function AxisHeader({\n  viewport,\n  bodyWidth,\n  gutterWidth,\n  showWeekendShading,\n  className,\n}: {\n  viewport: GanttViewport;\n  bodyWidth: number;\n  gutterWidth: number;\n  showWeekendShading?: boolean;\n  className?: string;\n}) {\n  const { minor, major } = pickScales(viewport.pxPerMs);\n  const fromMs = viewport.originMs - OVERSCAN_PX / viewport.pxPerMs;\n  const toMs = viewport.originMs + (bodyWidth + OVERSCAN_PX) / viewport.pxPerMs;\n  const ready = bodyWidth > 0;\n  const minorTicks = ready ? ticks(minor, fromMs, toMs) : [];\n  const majorTicks = ready ? ticks(major, fromMs, toMs) : [];\n  const weekendsOn =\n    showWeekendShading && (minor === \"hour\" || minor === \"day\");\n\n  return (\n    <div className={cn(\"flex select-none border-b bg-card\", className)}>\n      <div className=\"shrink-0 border-e border-border\" style={{ width: gutterWidth }} />\n      <div className=\"relative grow overflow-hidden\" style={{ height: 46 }}>\n        {weekendsOn\n          ? minorTicks\n              .filter((t) => isWeekend(t))\n              .map((t) => {\n                const left = x(viewport, t);\n                const w = x(viewport, addUnit(minor, t)) - left;\n                return (\n                  <div\n                    key={`w${t}`}\n                    aria-hidden\n                    className=\"absolute inset-y-0 bg-muted/50\"\n                    style={{ left, width: w }}\n                  />\n                );\n              })\n          : null}\n        {majorTicks.map((t) => {\n          const left = x(viewport, t);\n          const w = x(viewport, addUnit(major, t)) - left;\n          return (\n            <div\n              key={`M${t}`}\n              // dir-ok: cell is placed by computed style left on the physical time axis; border must stay on its right edge\n              className=\"absolute top-0 flex h-6 items-center overflow-hidden whitespace-nowrap border-r border-border/60 px-2 text-xs font-medium text-foreground\"\n              style={{ left, width: w }}\n            >\n              {majorLabel(major, t)}\n            </div>\n          );\n        })}\n        {minorTicks.map((t) => {\n          const left = x(viewport, t);\n          const w = x(viewport, addUnit(minor, t)) - left;\n          return (\n            <div\n              key={`m${t}`}\n              // dir-ok: cell is placed by computed style left on the physical time axis; border must stay on its right edge\n              className=\"absolute bottom-0 flex h-5 items-center justify-center overflow-hidden border-r border-border/40 text-[10px] tabular-nums text-muted-foreground\"\n              style={{ left, width: w }}\n            >\n              {minorLabel(minor, t)}\n            </div>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n\n/** Tier B — context-connected axis. */\nexport function GanttTimelineAxis({ className }: { className?: string }) {\n  const { viewport, bodyWidth, gutterWidth, showWeekendShading } =\n    useGanttTimeline();\n  return (\n    <AxisHeader\n      viewport={viewport}\n      bodyWidth={bodyWidth}\n      gutterWidth={gutterWidth}\n      showWeekendShading={showWeekendShading}\n      className={className}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/parts/gantt-timeline-axis.tsx"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/parts/gantt-timeline-body.tsx",
      "content": "\"use client\";\n\n/* eslint-disable react-hooks/refs -- bodyScrollRef is bundled on the context value;\n   the React Compiler's refs rule false-positives on reads taken off a context object\n   (see blackboard). Ref reads here are confined to effects + ref= props. */\n\nimport {\n  useEffect,\n  useRef,\n  useState,\n  type KeyboardEvent,\n  type MouseEvent,\n  type PointerEvent,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport { useGanttTimeline } from \"../hooks/use-gantt-context\";\nimport type { GanttSnap, GanttTimeUnit, GanttViewport, TaskItem } from \"../types\";\nimport {\n  MS,\n  addUnit,\n  isWeekend,\n  pickScales,\n  startOfUnit,\n  ticks,\n  timeAt,\n  x,\n} from \"../lib/time-scale\";\nimport {\n  BarTooltip,\n  GanttBar,\n  MilestoneDiamond,\n  SummaryBar,\n  TodayLine,\n} from \"./gantt-bars\";\nimport { GanttContextMenu } from \"./gantt-context-menu\";\n\ntype HoverState = { item: TaskItem; leftPx: number; topPx: number };\n\ntype EditDrag =\n  | {\n      kind: \"move\";\n      id: string;\n      origStart: number;\n      origEnd: number | null;\n      grabMs: number;\n      curStart: number;\n      curEnd: number | null;\n      topPx: number;\n    }\n  | {\n      kind: \"resize\";\n      id: string;\n      edge: \"start\" | \"end\";\n      origStart: number;\n      origEnd: number;\n      curStart: number;\n      curEnd: number;\n      topPx: number;\n    }\n  | {\n      kind: \"create\";\n      parentId: string | null;\n      index: number;\n      fromMs: number;\n      toMs: number;\n      topPx: number;\n    }\n  | {\n      // v0.3.0 — group-move: rigidly shift a summary's whole subtree by deltaMs.\n      kind: \"groupmove\";\n      id: string;\n      grabMs: number;\n      deltaMs: number;\n      spanStart: number;\n      spanEnd: number;\n      topPx: number;\n    };\n\nconst MIN_MS = 60_000;\nconst DRAG_THRESHOLD = 4; // px the pointer must travel before a press becomes a gesture\nconst EDGE_PX = 8; // resize hot-zone at each bar edge (needs a center move zone to coexist)\n\n/** What sits under a press — classified once on pointerdown, acted on in `resolvePending`. */\ntype Candidate =\n  | { kind: \"summary\"; id: string }\n  | { kind: \"barEdge\"; id: string; edge: \"start\" | \"end\" }\n  | { kind: \"barBody\"; id: string }\n  | { kind: \"emptyRow\"; rowId: string; parentId: string | null; index: number }\n  | { kind: \"void\" };\n\n/** A deferred press: nothing has committed yet; intent is resolved on the first move. */\ntype Pending = {\n  pointerId: number;\n  x0: number;\n  y0: number;\n  ms0: number;\n  candidate: Candidate;\n};\n\nfunction snapUnitMs(snap: GanttSnap, minor: GanttTimeUnit): number {\n  if (snap === \"off\") return 0;\n  if (typeof snap === \"number\") return snap;\n  const unit = snap === \"minor\" ? minor : snap;\n  switch (unit) {\n    case \"hour\":\n      return MS.hour;\n    case \"day\":\n      return MS.day;\n    case \"week\":\n      return MS.week;\n    case \"month\":\n      return 2_629_800_000;\n    case \"quarter\":\n      return 7_889_400_000;\n    default:\n      return MS.day;\n  }\n}\n\n/**\n * The calendar unit a snap setting resolves to, or null when snapping is off /\n * a fixed-ms grid. A named unit snaps to real calendar boundaries (matching the\n * axis ticks); `\"minor\"` follows the current minor unit (which can be month or\n * quarter when zoomed out — where average-ms rounding visibly drifts off-grid).\n */\nfunction snapCalUnit(snap: GanttSnap, minor: GanttTimeUnit): GanttTimeUnit | null {\n  if (snap === \"off\" || typeof snap === \"number\") return null;\n  return snap === \"minor\" ? minor : snap;\n}\n\n/**\n * Snap `t` to the nearest boundary. A calendar `unit` lands on a real\n * start-of-unit (so a snapped edge lines up with a gridline the axis drew);\n * otherwise a positive `ms` grid rounds to the nearest multiple (numeric snap),\n * and `ms <= 0` with no unit means snapping is off.\n */\nfunction snapPos(t: number, ms: number, unit: GanttTimeUnit | null): number {\n  if (unit) {\n    const lo = startOfUnit(unit, t);\n    const hi = addUnit(unit, lo);\n    return t - lo <= hi - t ? lo : hi;\n  }\n  return ms > 0 ? Math.round(t / ms) * ms : t;\n}\n\nconst iso = (ms: number) => new Date(ms).toISOString();\n\nexport function GanttTimelineBody({ className }: { className?: string }) {\n  const ctx = useGanttTimeline();\n  const scrollRef = ctx.bodyScrollRef;\n  const { viewport, bodyWidth, editable } = ctx;\n\n  const [hover, setHover] = useState<HoverState | null>(null);\n  const [editDrag, setEditDrag] = useState<EditDrag | null>(null);\n  const editDragRef = useRef<EditDrag | null>(null);\n  const pendingRef = useRef<Pending | null>(null);\n  const snapUnitRef = useRef(0);\n  const snapCalRef = useRef<GanttTimeUnit | null>(null);\n\n  /* ── measure width ── */\n  const setBodyWidth = ctx.setBodyWidth;\n  useEffect(() => {\n    const el = scrollRef.current;\n    if (!el) return;\n    const update = () => setBodyWidth(el.clientWidth);\n    update();\n    // Coalesce observer callbacks into one rAF. We observe the same element we\n    // resize, so a vertical-scrollbar appearance shrinks clientWidth → relayout →\n    // re-fire; the rAF gate settles that in a single frame instead of tripping\n    // the \"ResizeObserver loop completed\" warning.\n    let raf = 0;\n    const ro = new ResizeObserver(() => {\n      if (raf) return;\n      raf = requestAnimationFrame(() => {\n        raf = 0;\n        update();\n      });\n    });\n    ro.observe(el);\n    return () => {\n      if (raf) cancelAnimationFrame(raf);\n      ro.disconnect();\n    };\n  }, [scrollRef, setBodyWidth]);\n\n  /* ── wheel (non-passive) ── */\n  const { onZoomAt, onPan, disableGestures } = ctx;\n  useEffect(() => {\n    const el = scrollRef.current;\n    if (!el || disableGestures) return;\n    const onWheel = (e: WheelEvent) => {\n      if (e.ctrlKey || e.metaKey) {\n        e.preventDefault();\n        setHover(null); // the bar moves under the frozen tooltip x — drop it\n        const rect = el.getBoundingClientRect();\n        onZoomAt(Math.exp(-e.deltaY * 0.0015), e.clientX - rect.left);\n      } else if (e.shiftKey || Math.abs(e.deltaX) > Math.abs(e.deltaY)) {\n        e.preventDefault();\n        setHover(null);\n        onPan(-(e.deltaX || e.deltaY));\n      }\n    };\n    el.addEventListener(\"wheel\", onWheel, { passive: false });\n    return () => el.removeEventListener(\"wheel\", onWheel);\n  }, [scrollRef, disableGestures, onZoomAt, onPan]);\n\n  /* ── pan/pinch gestures (v1) ── */\n  const pointers = useRef(new Map<number, { x: number; y: number }>());\n  const lockRef = useRef<null | \"h\" | \"v\">(null);\n  const pinchRef = useRef<number | null>(null);\n  const velRef = useRef(0);\n  const lastRef = useRef<{ x: number; t: number } | null>(null);\n\n  const { minor } = pickScales(viewport.pxPerMs);\n\n  /** Time under the pointer (body-relative x). */\n  function timeAtPointer(clientX: number, el: HTMLElement): number {\n    const rect = el.getBoundingClientRect();\n    return timeAt(viewport, clientX - rect.left);\n  }\n\n  /** Vertical offset (= ri.start) of an item's row — robust vs DOM nesting. */\n  function rowTopOf(id: string): number {\n    const ri = ctx.renderItems.find((r) => ctx.rows[r.index]?.item.id === id);\n    return ri?.start ?? 0;\n  }\n\n  /* ── press classification (deferred; the gesture is chosen on the first move) ── */\n\n  /**\n   * Which edge of a bar (if any) the press is near — by PIXEL proximity to the\n   * bar's geometric edges, not a DOM `[data-edge]` hit. A center move zone must\n   * remain, so a narrow bar exposes no resize edges (it moves as a whole) instead\n   * of being all-handle with no body to grab. Milestones / non-finite geometry\n   * have no edges.\n   */\n  function edgeAt(\n    e: PointerEvent<HTMLDivElement>,\n    item: TaskItem,\n  ): \"start\" | \"end\" | null {\n    const geo = ctx.geometryFor(item);\n    if (geo.endMs == null) return null;\n    if (!Number.isFinite(geo.startMs) || !Number.isFinite(geo.endMs)) return null;\n    const rect = e.currentTarget.getBoundingClientRect();\n    const px = e.clientX - rect.left;\n    const left = x(viewport, geo.startMs);\n    const right = x(viewport, geo.endMs);\n    if (right - left < EDGE_PX * 3) return null; // too narrow → whole-bar move\n    if (px - left <= EDGE_PX) return \"start\";\n    if (right - px <= EDGE_PX) return \"end\";\n    return null;\n  }\n\n  /**\n   * Classify what's under a press WITHOUT starting anything. The gesture is chosen\n   * later in `resolvePending`, once the drag direction is known — so a click (no\n   * movement) selects, a vertical drag scrolls, and neither is hijacked into an\n   * edit. Read-only, or anything not movable/resizable, classifies as `void` → pan.\n   */\n  function classifyTarget(e: PointerEvent<HTMLDivElement>): Candidate {\n    if (!editable) return { kind: \"void\" };\n    const target = e.target as HTMLElement;\n\n    // summary bracket → group-move when the whole subtree is movable; else pan.\n    const summaryEl = target.closest<HTMLElement>(\"[data-summaryid]\");\n    if (summaryEl) {\n      const sid = summaryEl.dataset.summaryid!;\n      const sitem = ctx.getItem(sid);\n      if (sitem && ctx.canGroupMove(sitem) && ctx.summarySpanFor(sitem)) {\n        return { kind: \"summary\", id: sid };\n      }\n      return { kind: \"void\" };\n    }\n\n    // bar → resize (near a wide-enough edge) or move; else pan.\n    const barEl = target.closest<HTMLElement>(\"[data-itemid]\");\n    if (barEl) {\n      const id = barEl.dataset.itemid!;\n      const item = ctx.rows.find((r) => r.item.id === id)?.item;\n      if (item) {\n        const edge = edgeAt(e, item);\n        if (edge && ctx.can(\"resize\", item)) return { kind: \"barEdge\", id, edge };\n        if (ctx.can(\"move\", item)) return { kind: \"barBody\", id };\n      }\n      return { kind: \"void\" };\n    }\n\n    // empty row area → draw a sibling, but ONLY in draw mode; otherwise pan.\n    // Summary rows are derived (read-only), so they always pan.\n    if (ctx.drawMode) {\n      const rowEl = target.closest<HTMLElement>(\"[data-rowid]\");\n      if (rowEl) {\n        const rowId = rowEl.dataset.rowid!;\n        const row = ctx.rows.find((r) => r.item.id === rowId);\n        if (row && !row.isSummary) {\n          const info = ctx.nodeInfo(rowId);\n          return {\n            kind: \"emptyRow\",\n            rowId,\n            parentId: info?.parentId ?? null,\n            index: (info?.index ?? 0) + 1,\n          };\n        }\n      }\n    }\n    return { kind: \"void\" };\n  }\n\n  function moveEdit(e: PointerEvent<HTMLDivElement>) {\n    const d = editDragRef.current;\n    if (!d) return;\n    const tMs = timeAtPointer(e.clientX, e.currentTarget);\n    const u = snapUnitRef.current;\n    const cu = snapCalRef.current;\n    let nextDrag: EditDrag;\n    if (d.kind === \"move\") {\n      const delta = tMs - d.grabMs;\n      const newStart = snapPos(d.origStart + delta, u, cu);\n      const shift = newStart - d.origStart;\n      nextDrag = {\n        ...d,\n        curStart: newStart,\n        curEnd: d.origEnd != null ? d.origEnd + shift : null,\n      };\n    } else if (d.kind === \"resize\") {\n      if (d.edge === \"start\") {\n        const ns = Math.min(snapPos(tMs, u, cu), d.origEnd - MIN_MS);\n        nextDrag = { ...d, curStart: ns, curEnd: d.origEnd };\n      } else {\n        const ne = Math.max(snapPos(tMs, u, cu), d.origStart + MIN_MS);\n        nextDrag = { ...d, curStart: d.origStart, curEnd: ne };\n      }\n    } else if (d.kind === \"groupmove\") {\n      // Snap the leading edge of the span; delta is the realized shift.\n      const newStart = snapPos(d.spanStart + (tMs - d.grabMs), u, cu);\n      nextDrag = { ...d, deltaMs: newStart - d.spanStart };\n    } else {\n      nextDrag = { ...d, toMs: snapPos(tMs, u, cu) };\n    }\n    editDragRef.current = nextDrag;\n    setEditDrag(nextDrag);\n  }\n\n  function commitEdit() {\n    const d = editDragRef.current;\n    editDragRef.current = null;\n    setEditDrag(null);\n    if (!d) return;\n    if (d.kind === \"groupmove\") {\n      if (d.deltaMs !== 0) ctx.moveSubtree(d.id, d.deltaMs);\n      return;\n    }\n    if (d.kind === \"create\") {\n      const a = Math.min(d.fromMs, d.toMs);\n      const b = Math.max(d.fromMs, d.toMs);\n      if (b - a < MIN_MS) return; // a click, not a draw\n      ctx.createItem(\n        d.parentId,\n        { startAt: iso(a), expireAt: iso(b), setAt: iso(a), name: \"New task\" },\n        d.index,\n      );\n      return;\n    }\n    const item = ctx.rows.find((r) => r.item.id === d.id)?.item;\n    if (!item) return;\n    const expireDriven = item.expireAt != null;\n    if (d.kind === \"move\") {\n      if (d.curStart === d.origStart) return;\n      const patch =\n        expireDriven && d.curEnd != null\n          ? { startAt: iso(d.curStart), expireAt: iso(d.curEnd) }\n          : { startAt: iso(d.curStart) };\n      ctx.rescheduleItem(d.id, patch, \"move\");\n    } else {\n      if (d.curStart === d.origStart && d.curEnd === d.origEnd) return;\n      if (d.edge === \"start\") {\n        const patch = expireDriven\n          ? { startAt: iso(d.curStart) }\n          : { startAt: iso(d.curStart), duration: d.origEnd - d.curStart };\n        ctx.rescheduleItem(d.id, patch, \"resize\");\n      } else {\n        const patch = expireDriven\n          ? { expireAt: iso(d.curEnd) }\n          : { duration: d.curEnd - d.origStart };\n        ctx.rescheduleItem(d.id, patch, \"resize\");\n      }\n    }\n  }\n\n  function startDrag(d: EditDrag) {\n    editDragRef.current = d;\n    setEditDrag(d);\n  }\n\n  /**\n   * First significant move after a press picks exactly one gesture. Vertical-dominant\n   * → scroll the list (edit gestures are all horizontal-intent). Horizontal-dominant\n   * → the candidate decides: resize / move / group-move / draw, or pan for `void`.\n   * Below the threshold the press stays pending, so a click just selects.\n   */\n  function resolvePending(e: PointerEvent<HTMLDivElement>) {\n    const p = pendingRef.current;\n    if (!p || p.pointerId !== e.pointerId) return;\n    const dx = e.clientX - p.x0;\n    const dy = e.clientY - p.y0;\n    if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;\n\n    pendingRef.current = null;\n\n    // Vertical-dominant → scroll (works over bars and empty space alike).\n    if (Math.abs(dy) > Math.abs(dx)) {\n      lockRef.current = \"v\";\n      lastRef.current = { x: e.clientX, t: e.timeStamp };\n      return;\n    }\n\n    const c = p.candidate;\n    if (c.kind === \"barEdge\") {\n      const item = ctx.rows.find((r) => r.item.id === c.id)?.item;\n      const geo = item ? ctx.geometryFor(item) : null;\n      if (geo && geo.endMs != null) {\n        startDrag({\n          kind: \"resize\",\n          id: c.id,\n          edge: c.edge,\n          origStart: geo.startMs,\n          origEnd: geo.endMs,\n          curStart: geo.startMs,\n          curEnd: geo.endMs,\n          topPx: rowTopOf(c.id),\n        });\n        return;\n      }\n    } else if (c.kind === \"barBody\") {\n      const item = ctx.rows.find((r) => r.item.id === c.id)?.item;\n      if (item) {\n        const geo = ctx.geometryFor(item);\n        startDrag({\n          kind: \"move\",\n          id: c.id,\n          origStart: geo.startMs,\n          origEnd: geo.endMs,\n          grabMs: p.ms0,\n          curStart: geo.startMs,\n          curEnd: geo.endMs,\n          topPx: rowTopOf(c.id),\n        });\n        return;\n      }\n    } else if (c.kind === \"summary\") {\n      const sitem = ctx.getItem(c.id);\n      const span = sitem ? ctx.summarySpanFor(sitem) : null;\n      if (span) {\n        startDrag({\n          kind: \"groupmove\",\n          id: c.id,\n          grabMs: p.ms0,\n          deltaMs: 0,\n          spanStart: span.startMs,\n          spanEnd: span.endMs,\n          topPx: rowTopOf(c.id),\n        });\n        return;\n      }\n    } else if (c.kind === \"emptyRow\") {\n      const snapped = snapPos(p.ms0, snapUnitRef.current, snapCalRef.current);\n      startDrag({\n        kind: \"create\",\n        parentId: c.parentId,\n        index: c.index,\n        fromMs: snapped,\n        toMs: snapped,\n        topPx: rowTopOf(c.rowId),\n      });\n      return;\n    }\n\n    // void (or any fall-through) → horizontal pan.\n    ctx.beginPan();\n    lockRef.current = \"h\";\n    lastRef.current = { x: e.clientX, t: e.timeStamp };\n    velRef.current = 0;\n  }\n\n  function onPointerDown(e: PointerEvent<HTMLDivElement>) {\n    // The context-menu content is portaled to document.body but is still a React\n    // child of this scroll surface, so its pointer events bubble here through the\n    // React tree. Ignore any event whose real target isn't a DOM descendant of\n    // this surface, else a menu-item click would start a gesture here and swallow\n    // the item's own pointerup (the \"menu opens but items do nothing\" bug).\n    if (!e.currentTarget.contains(e.target as Node)) return;\n    if (disableGestures) return;\n    if (e.button === 2) return; // right-click → context menu, not a gesture\n\n    e.currentTarget.setPointerCapture(e.pointerId);\n    pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });\n    setHover(null);\n    ctx.beginPan(); // touching the canvas halts any momentum fling\n\n    if (pointers.current.size === 2) {\n      // second finger → pinch-zoom; abandon any pending or in-flight single gesture\n      pendingRef.current = null;\n      if (editDragRef.current) {\n        editDragRef.current = null;\n        setEditDrag(null);\n      }\n      const [a, b] = [...pointers.current.values()];\n      pinchRef.current = Math.hypot(a.x - b.x, a.y - b.y);\n      lockRef.current = null;\n      return;\n    }\n\n    // Single pointer → DEFER. Capture snap settings + classify what's under the\n    // press; the gesture itself is chosen on the first move (`resolvePending`).\n    snapUnitRef.current = e.altKey ? 0 : snapUnitMs(ctx.snap, minor);\n    snapCalRef.current = e.altKey ? null : snapCalUnit(ctx.snap, minor);\n    pendingRef.current = {\n      pointerId: e.pointerId,\n      x0: e.clientX,\n      y0: e.clientY,\n      ms0: timeAtPointer(e.clientX, e.currentTarget),\n      candidate: classifyTarget(e),\n    };\n    lockRef.current = null;\n    lastRef.current = null;\n    velRef.current = 0;\n  }\n\n  function onPointerMove(e: PointerEvent<HTMLDivElement>) {\n    if (editDragRef.current) {\n      moveEdit(e);\n      return;\n    }\n    if (disableGestures) return;\n\n    // pinch-zoom (two active pointers)\n    if (pointers.current.size >= 2 && pinchRef.current != null) {\n      pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });\n      const [a, b] = [...pointers.current.values()];\n      const dist = Math.hypot(a.x - b.x, a.y - b.y);\n      if (dist > 0 && pinchRef.current > 0) {\n        const rect = e.currentTarget.getBoundingClientRect();\n        onZoomAt(dist / pinchRef.current, (a.x + b.x) / 2 - rect.left);\n      }\n      pinchRef.current = dist;\n      return;\n    }\n\n    // a press is still pending → update its position and try to resolve intent\n    if (pendingRef.current && pendingRef.current.pointerId === e.pointerId) {\n      pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });\n      resolvePending(e);\n      return;\n    }\n\n    // resolved pan / vertical-scroll\n    const prev = pointers.current.get(e.pointerId);\n    if (!prev) return;\n    const dx = e.clientX - prev.x;\n    const dy = e.clientY - prev.y;\n    pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });\n    if (lockRef.current === \"h\") {\n      onPan(dx);\n      const last = lastRef.current;\n      const t = e.timeStamp;\n      if (last && t > last.t) velRef.current = (e.clientX - last.x) / (t - last.t);\n      lastRef.current = { x: e.clientX, t };\n    } else if (lockRef.current === \"v\" && e.pointerType === \"mouse\") {\n      const el = scrollRef.current;\n      if (el) el.scrollTop -= dy;\n    }\n  }\n\n  function endPointer(e: PointerEvent<HTMLDivElement>) {\n    const wasEdit = editDragRef.current != null;\n    if (wasEdit) commitEdit();\n    pendingRef.current = null; // never crossed threshold → a click; onClick handles select\n\n    if (pointers.current.has(e.pointerId)) pointers.current.delete(e.pointerId);\n    if (pointers.current.size < 2) pinchRef.current = null;\n\n    if (!wasEdit && pointers.current.size === 0 && lockRef.current === \"h\") {\n      const last = lastRef.current;\n      const fresh = last != null && e.timeStamp - last.t <= 100;\n      ctx.endPanWithVelocity(fresh ? velRef.current : 0);\n    }\n    if (pointers.current.size === 0) {\n      lockRef.current = null;\n      lastRef.current = null;\n    }\n  }\n\n  /* ── keyboard editing (body-focused + a selected item) ── */\n  function onKeyDown(e: KeyboardEvent<HTMLDivElement>) {\n    // Ignore keys bubbling from the portaled context menu (see onPointerDown) so\n    // menu navigation/select doesn't double-trigger body reschedule/delete/open.\n    if (!e.currentTarget.contains(e.target as Node)) return;\n    if (!editable || !ctx.selectedId) return;\n    const item = ctx.rows.find((r) => r.item.id === ctx.selectedId)?.item;\n    if (!item) return;\n    const u = snapUnitMs(ctx.snap, minor) || MS.day;\n    const geo = ctx.geometryFor(item);\n    const expireDriven = item.expireAt != null;\n    switch (e.key) {\n      case \"Delete\":\n      case \"Backspace\":\n        e.preventDefault();\n        ctx.deleteItem(item.id);\n        break;\n      case \"Enter\":\n        e.preventDefault();\n        ctx.openEditor(item.id);\n        break;\n      case \"ArrowLeft\":\n      case \"ArrowRight\": {\n        e.preventDefault();\n        if (\n          !Number.isFinite(geo.startMs) ||\n          (geo.endMs != null && !Number.isFinite(geo.endMs))\n        )\n          break; // unparseable date — skip keyboard reschedule (Delete/Enter still work)\n        const dir = e.key === \"ArrowRight\" ? 1 : -1;\n        if (e.shiftKey && geo.endMs != null) {\n          const ne = Math.max(geo.startMs + MIN_MS, geo.endMs + dir * u);\n          ctx.rescheduleItem(\n            item.id,\n            expireDriven\n              ? { expireAt: iso(ne) }\n              : { duration: ne - geo.startMs },\n            \"resize\",\n          );\n        } else {\n          const ns = geo.startMs + dir * u;\n          ctx.rescheduleItem(\n            item.id,\n            expireDriven && geo.endMs != null\n              ? { startAt: iso(ns), expireAt: iso(geo.endMs + dir * u) }\n              : { startAt: iso(ns) },\n            \"move\",\n          );\n        }\n        break;\n      }\n      default:\n        break;\n    }\n  }\n\n  /**\n   * v0.5.0 — double-click an empty row area → quick-create a sibling task at that\n   * time. A double-click ON a bar/summary opens the editor (handled on the shape),\n   * so ignore those targets here. Independent of draw mode (draw = drag a span).\n   */\n  function onDoubleClick(e: MouseEvent<HTMLDivElement>) {\n    if (!editable) return;\n    const target = e.target as HTMLElement;\n    if (target.closest(\"[data-itemid]\") || target.closest(\"[data-summaryid]\"))\n      return;\n    const rowEl = target.closest<HTMLElement>(\"[data-rowid]\");\n    if (!rowEl) return;\n    const rowId = rowEl.dataset.rowid!;\n    const row = ctx.rows.find((r) => r.item.id === rowId);\n    if (!row || row.isSummary) return;\n    const info = ctx.nodeInfo(rowId);\n    const startMs = snapPos(\n      timeAtPointer(e.clientX, e.currentTarget),\n      snapUnitMs(ctx.snap, minor),\n      snapCalUnit(ctx.snap, minor),\n    );\n    const span = snapUnitMs(ctx.snap, minor) || MS.day;\n    const composerTarget = {\n      startMs,\n      endMs: startMs + span,\n      parentId: info?.parentId ?? null,\n      index: (info?.index ?? 0) + 1,\n      x: e.clientX,\n      y: e.clientY,\n    };\n    if (ctx.quickCompose) {\n      ctx.openComposer(composerTarget);\n    } else {\n      ctx.createItem(\n        composerTarget.parentId,\n        {\n          name: \"New task\",\n          startAt: iso(startMs),\n          expireAt: iso(startMs + span),\n          setAt: iso(startMs),\n        },\n        composerTarget.index,\n        { openEditor: true },\n      );\n    }\n  }\n\n  /* ── weekend bands ── */\n  const weekendsOn =\n    ctx.showWeekendShading && (minor === \"hour\" || minor === \"day\");\n  const dayBands =\n    weekendsOn && bodyWidth > 0\n      ? ticks(\n          \"day\",\n          viewport.originMs - 86_400_000,\n          viewport.originMs + bodyWidth / viewport.pxPerMs,\n        ).filter(isWeekend)\n      : [];\n\n  const todayLeft = x(viewport, ctx.nowMs);\n  const showToday =\n    ctx.showTodayLine && todayLeft >= -2 && todayLeft <= bodyWidth + 2;\n\n  function activate(item: TaskItem) {\n    ctx.setFocusedId(item.id);\n    ctx.select(item.id);\n    ctx.onTaskClick?.(item);\n    scrollRef.current?.focus();\n  }\n\n  return (\n    <div\n      ref={scrollRef}\n      tabIndex={editable ? 0 : undefined}\n      onScroll={(e) => ctx.onBodyScroll(e.currentTarget.scrollTop)}\n      onPointerDown={onPointerDown}\n      onPointerMove={onPointerMove}\n      onPointerUp={endPointer}\n      onPointerCancel={endPointer}\n      onDoubleClick={onDoubleClick}\n      onKeyDown={onKeyDown}\n      style={{ touchAction: disableGestures ? undefined : \"pan-y\" }}\n      className={cn(\n        \"relative h-full grow overflow-x-hidden overflow-y-auto bg-background outline-none\",\n        !disableGestures &&\n          !editDrag &&\n          !(editable && ctx.drawMode) &&\n          \"cursor-grab active:cursor-grabbing\",\n        (editDrag?.kind === \"create\" || (editable && ctx.drawMode)) &&\n          \"cursor-crosshair\",\n        className,\n      )}\n    >\n      <div className=\"relative\" style={{ height: ctx.totalSize, minWidth: \"100%\" }}>\n        {dayBands.map((t) => {\n          const left = x(viewport, t);\n          const w = x(viewport, addUnit(\"day\", t)) - left;\n          return (\n            <div\n              key={`wk${t}`}\n              aria-hidden\n              className=\"absolute inset-y-0 bg-muted/40\"\n              style={{ left, width: w }}\n            />\n          );\n        })}\n\n        {showToday ? <TodayLine leftPx={todayLeft} /> : null}\n\n        {ctx.renderItems.map((ri) => {\n          const row = ctx.rows[ri.index];\n          if (!row) return null;\n          const item = row.item;\n          const selected = ctx.selectedId === item.id;\n          const color = ctx.resolveColor(item);\n          const geo = ctx.geometryFor(item);\n          const priColor = item.priority\n            ? ctx.priorityOptions?.find((o) => o.value === item.priority)?.color\n            : undefined;\n          const movable = editable && ctx.can(\"move\", item);\n          const resizable = editable && ctx.can(\"resize\", item);\n\n          const enter = (leftPx: number) =>\n            setHover({ item, leftPx, topPx: ri.start });\n          const leave = () => setHover(null);\n\n          // A bad/unparseable date yields NaN geometry. Render no shape (the row\n          // label still shows) so we never position a bar at NaN→origin or throw\n          // on a later edit-commit. Summary rows use summarySpan, which is NaN-safe.\n          const geoOk =\n            Number.isFinite(geo.startMs) &&\n            (geo.endMs == null || Number.isFinite(geo.endMs));\n\n          let shape: React.ReactNode = null;\n          let labelLeft = 0;\n\n          if (row.isSummary) {\n            const span = ctx.summarySpanFor(item);\n            if (span) {\n              const left = x(viewport, span.startMs);\n              const w = x(viewport, span.endMs) - left;\n              labelLeft = left + Math.max(w, 8) + 6;\n              shape = (\n                <SummaryBar\n                  data-summaryid={item.id}\n                  leftPx={left}\n                  widthPx={w}\n                  selected={selected}\n                  groupMovable={editable && ctx.canGroupMove(item)}\n                  aria-hidden\n                  onClick={() => activate(item)}\n                  onMouseEnter={() => enter(left)}\n                  onMouseLeave={leave}\n                />\n              );\n            }\n          } else if (!geoOk) {\n            // unparseable date — label-only row, no draggable bar (see geoOk note)\n          } else if (geo.isMilestone) {\n            const left = x(viewport, geo.startMs);\n            labelLeft = left + 10;\n            shape = (\n              <MilestoneDiamond\n                data-itemid={item.id}\n                leftPx={left}\n                fill={color.fill}\n                selected={selected}\n                movable={movable}\n                aria-hidden\n                onClick={() => activate(item)}\n                onDoubleClick={() => editable && ctx.openEditor(item.id)}\n                onMouseEnter={() => enter(left)}\n                onMouseLeave={leave}\n              />\n            );\n          } else if (geo.endMs != null) {\n            const left = x(viewport, geo.startMs);\n            const w = x(viewport, geo.endMs) - left;\n            labelLeft = left + Math.max(w, 6) + 6;\n            shape = (\n              <GanttBar\n                data-itemid={item.id}\n                leftPx={left}\n                widthPx={w}\n                fill={color.fill}\n                rowHeight={ctx.rowHeight}\n                overdue={color.isOverdue}\n                inactive={!item.active}\n                locked={item.locked}\n                priorityColor={priColor}\n                selected={selected}\n                movable={movable}\n                resizable={resizable}\n                aria-hidden\n                onClick={() => activate(item)}\n                onDoubleClick={() => editable && ctx.openEditor(item.id)}\n                onMouseEnter={() => enter(left)}\n                onMouseLeave={leave}\n              />\n            );\n          }\n\n          const rowInner = (\n            <div\n              data-rowid={item.id}\n              className={cn(\n                \"absolute inset-x-0 border-b border-border/40\",\n                selected && \"bg-accent/40\",\n              )}\n              style={{ top: ri.start, height: ctx.rowHeight }}\n            >\n              {shape}\n              {labelLeft < bodyWidth + 40 ? (\n                <span\n                  className={cn(\n                    \"pointer-events-none absolute top-1/2 max-w-55 -translate-y-1/2 truncate text-xs\",\n                    row.isSummary\n                      ? \"font-medium text-foreground\"\n                      : \"text-foreground/85\",\n                  )}\n                  style={{ left: labelLeft }}\n                >\n                  {item.name}\n                </span>\n              ) : null}\n            </div>\n          );\n\n          return editable && !row.isSummary ? (\n            <GanttContextMenu key={item.id} item={item}>\n              {rowInner}\n            </GanttContextMenu>\n          ) : (\n            <div key={item.id}>{rowInner}</div>\n          );\n        })}\n\n        {/* edit drag preview */}\n        {editDrag ? (\n          <EditPreview\n            drag={editDrag}\n            viewport={viewport}\n            rowHeight={ctx.rowHeight}\n          />\n        ) : null}\n\n        {hover && !editDrag ? (\n          <div\n            className=\"pointer-events-none absolute z-30 rounded-md border border-border bg-popover p-2.5 text-popover-foreground shadow-md\"\n            style={{\n              left: Math.max(\n                4,\n                Math.min(hover.leftPx, Math.max(4, bodyWidth - 200)),\n              ),\n              top:\n                hover.topPx > 96 ? hover.topPx - 8 : hover.topPx + ctx.rowHeight + 6,\n              transform: hover.topPx > 96 ? \"translateY(-100%)\" : undefined,\n            }}\n          >\n            {ctx.renderTooltip?.(hover.item) ?? (\n              <BarTooltip item={hover.item} statusOptions={ctx.statusOptions} />\n            )}\n          </div>\n        ) : null}\n      </div>\n    </div>\n  );\n\n}\n\nfunction EditPreview({\n  drag,\n  viewport,\n  rowHeight,\n}: {\n  drag: EditDrag;\n  viewport: GanttViewport;\n  rowHeight: number;\n}) {\n  let left: number;\n  let width: number;\n  let label: string;\n  if (drag.kind === \"create\") {\n    const a = Math.min(drag.fromMs, drag.toMs);\n    const b = Math.max(drag.fromMs, drag.toMs);\n    left = x(viewport, a);\n    width = Math.max(x(viewport, b) - left, 2);\n    label = `${new Date(a).toLocaleDateString()} → ${new Date(b).toLocaleDateString()}`;\n  } else if (drag.kind === \"groupmove\") {\n    const s = drag.spanStart + drag.deltaMs;\n    const e = drag.spanEnd + drag.deltaMs;\n    left = x(viewport, s);\n    width = Math.max(x(viewport, e) - left, 8);\n    label = `${new Date(s).toLocaleDateString()} → ${new Date(e).toLocaleDateString()}`;\n  } else {\n    const start = drag.curStart;\n    const end = drag.curEnd ?? drag.curStart;\n    left = x(viewport, start);\n    width = Math.max(x(viewport, end) - left, 6);\n    label =\n      drag.curEnd == null\n        ? new Date(start).toLocaleDateString()\n        : `${new Date(start).toLocaleDateString()} → ${new Date(end).toLocaleDateString()}`;\n  }\n  return (\n    <div\n      aria-hidden\n      className=\"pointer-events-none absolute z-40\"\n      style={{ top: drag.topPx, height: rowHeight }}\n    >\n      <div\n        className=\"absolute top-1/2 h-5 -translate-y-1/2 rounded-[5px] border-2 border-primary bg-primary/20\"\n        style={{ left, width }}\n      />\n      <span\n        className=\"absolute top-1/2 -translate-y-1/2 whitespace-nowrap rounded bg-primary px-1.5 py-0.5 font-mono text-[10px] leading-none text-primary-foreground\"\n        style={{ left: left + width + 6 }}\n      >\n        {label}\n      </span>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/parts/gantt-timeline-body.tsx"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/parts/gantt-timeline-gutter.tsx",
      "content": "\"use client\";\n\n/* eslint-disable react-hooks/refs -- gutterTrackRef is bundled on the context value; the\n   React Compiler's refs rule false-positives on reads taken off a context object (see\n   blackboard). The ref is used only as a ref= prop + read inside effects. */\n\nimport { useEffect, useRef, type KeyboardEvent } from \"react\";\nimport {\n  DndContext,\n  KeyboardSensor,\n  PointerSensor,\n  pointerWithin,\n  useDraggable,\n  useDroppable,\n  useSensor,\n  useSensors,\n  type DragEndEvent,\n} from \"@dnd-kit/core\";\nimport { ChevronRight, GripVertical, Plus, Trash2 } from \"lucide-react\";\nimport { Avatar, AvatarFallback, AvatarImage } from \"@/components/ui/avatar\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Input } from \"@/components/ui/input\";\nimport { cn } from \"@/lib/utils\";\nimport { useGanttTimeline } from \"../hooks/use-gantt-context\";\nimport type { GanttRow, TaskLabelOption, TaskStatusOption } from \"../types\";\nimport { effEndMs, effStartMs } from \"../lib/geometry\";\nimport { GanttContextMenu } from \"./gantt-context-menu\";\n\nfunction initials(name: string): string {\n  return name\n    .split(/\\s+/)\n    .map((p) => p[0])\n    .filter(Boolean)\n    .slice(0, 2)\n    .join(\"\")\n    .toUpperCase();\n}\n\nfunction rowAriaLabel(row: GanttRow, statusOpt?: TaskStatusOption): string {\n  const { item } = row;\n  const start = new Date(effStartMs(item)).toLocaleDateString();\n  const end = effEndMs(item);\n  const when =\n    end == null\n      ? `milestone ${start}`\n      : `${start} to ${new Date(end).toLocaleDateString()}`;\n  const status = statusOpt ? `, ${statusOpt.label}` : \"\";\n  return `${item.name}, ${when}${status}`;\n}\n\n/* ───────── GutterRow (Tier C) ───────── */\n\nexport function GutterRow({\n  row,\n  statusOptions,\n  labelOptions,\n  selected,\n  tabIndex,\n  onToggle,\n  onActivate,\n  editable,\n  renaming,\n  canCreate,\n  canDelete,\n  gripRef,\n  gripProps,\n  onAddChild,\n  onDelete,\n  onRenameCommit,\n  onRenameCancel,\n}: {\n  row: GanttRow;\n  statusOptions?: TaskStatusOption[];\n  labelOptions?: TaskLabelOption[];\n  selected?: boolean;\n  tabIndex: number;\n  onToggle: () => void;\n  onActivate: () => void;\n  editable?: boolean;\n  renaming?: boolean;\n  canCreate?: boolean;\n  canDelete?: boolean;\n  gripRef?: (el: HTMLElement | null) => void;\n  gripProps?: Record<string, unknown>;\n  onAddChild?: () => void;\n  onDelete?: () => void;\n  onRenameCommit?: (name: string) => void;\n  onRenameCancel?: () => void;\n}) {\n  const { item, depth, hasChildren, collapsed, posInSet, setSize } = row;\n  const statusOpt = statusOptions?.find((o) => o.value === item.status);\n  const dots = (item.labels ?? [])\n    .map((key) => labelOptions?.find((o) => o.value === key))\n    .filter(Boolean)\n    .slice(0, 4) as TaskLabelOption[];\n\n  return (\n    <div\n      role=\"treeitem\"\n      aria-level={depth + 1}\n      aria-setsize={setSize}\n      aria-posinset={posInSet}\n      aria-expanded={hasChildren ? !collapsed : undefined}\n      aria-selected={selected || undefined}\n      aria-label={rowAriaLabel(row, statusOpt)}\n      data-rowid={item.id}\n      tabIndex={tabIndex}\n      onClick={onActivate}\n      className={cn(\n        \"group/row flex h-full cursor-default select-none items-center gap-1.5 border-b border-border/40 pe-2 outline-none\",\n        \"focus-visible:bg-accent focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring\",\n        selected && \"bg-accent\",\n        !item.active && \"opacity-60\",\n      )}\n      style={{ paddingLeft: 8 + depth * 16 }}\n    >\n      {editable ? (\n        <button\n          ref={gripRef as ((el: HTMLButtonElement | null) => void) | undefined}\n          type=\"button\"\n          tabIndex={-1}\n          aria-label=\"Drag to reorder\"\n          onClick={(e) => e.stopPropagation()}\n          className=\"-ms-1 hidden shrink-0 cursor-grab touch-none text-muted-foreground hover:text-foreground active:cursor-grabbing group-hover/row:block\"\n          {...gripProps}\n        >\n          <GripVertical className=\"size-3.5\" />\n        </button>\n      ) : null}\n\n      {hasChildren ? (\n        <button\n          type=\"button\"\n          tabIndex={-1}\n          aria-label={collapsed ? \"Expand\" : \"Collapse\"}\n          onClick={(e) => {\n            e.stopPropagation();\n            onToggle();\n          }}\n          className=\"grid size-4 shrink-0 place-items-center rounded text-muted-foreground hover:bg-muted hover:text-foreground\"\n        >\n          <ChevronRight\n            className={cn(\n              \"size-3.5 transition-transform\",\n              !collapsed && \"rotate-90\",\n            )}\n          />\n        </button>\n      ) : (\n        <span className=\"inline-block w-4 shrink-0\" />\n      )}\n\n      {item.targetPerson ? (\n        <Avatar className=\"size-5 shrink-0\">\n          {item.targetPerson.avatar ? (\n            <AvatarImage\n              src={item.targetPerson.avatar}\n              alt={item.targetPerson.name}\n            />\n          ) : null}\n          <AvatarFallback className=\"text-[9px]\">\n            {initials(item.targetPerson.name)}\n          </AvatarFallback>\n        </Avatar>\n      ) : null}\n\n      {renaming ? (\n        <Input\n          autoFocus\n          defaultValue={item.name}\n          onClick={(e) => e.stopPropagation()}\n          onKeyDown={(e) => {\n            e.stopPropagation();\n            if (e.key === \"Enter\") onRenameCommit?.(e.currentTarget.value.trim());\n            else if (e.key === \"Escape\") onRenameCancel?.();\n          }}\n          onBlur={(e) => onRenameCommit?.(e.currentTarget.value.trim())}\n          className=\"h-6 flex-1 px-1.5 py-0 text-sm\"\n        />\n      ) : (\n        <span className=\"truncate text-sm text-foreground\">{item.name}</span>\n      )}\n\n      {!renaming && dots.length > 0 ? (\n        <span className=\"ms-auto flex shrink-0 items-center gap-1\">\n          {dots.map((d) => (\n            <span\n              key={d.value}\n              title={d.label}\n              className=\"size-2 rounded-full\"\n              style={{ background: d.color ?? \"var(--muted-foreground)\" }}\n            />\n          ))}\n        </span>\n      ) : null}\n\n      {!renaming && statusOpt ? (\n        <Badge\n          variant={statusOpt.variant ?? \"secondary\"}\n          className={cn(\"shrink-0 text-[10px]\", dots.length === 0 && \"ms-auto\")}\n        >\n          {statusOpt.label}\n        </Badge>\n      ) : null}\n\n      {editable && !renaming ? (\n        <span className=\"hidden shrink-0 items-center gap-0.5 group-hover/row:flex\">\n          {canCreate ? (\n            <button\n              type=\"button\"\n              tabIndex={-1}\n              aria-label=\"Add child task\"\n              onClick={(e) => {\n                e.stopPropagation();\n                onAddChild?.();\n              }}\n              className=\"grid size-5 place-items-center rounded text-muted-foreground hover:bg-muted hover:text-foreground\"\n            >\n              <Plus className=\"size-3.5\" />\n            </button>\n          ) : null}\n          {canDelete ? (\n            <button\n              type=\"button\"\n              tabIndex={-1}\n              aria-label=\"Delete task\"\n              onClick={(e) => {\n                e.stopPropagation();\n                onDelete?.();\n              }}\n              className=\"grid size-5 place-items-center rounded text-muted-foreground hover:bg-destructive/15 hover:text-destructive\"\n            >\n              <Trash2 className=\"size-3.5\" />\n            </button>\n          ) : null}\n        </span>\n      ) : null}\n    </div>\n  );\n}\n\n/* ───────── drop zones (Tier-B internal) ───────── */\n\nfunction DropZones({ id }: { id: string }) {\n  const before = useDroppable({ id: `before:${id}` });\n  const into = useDroppable({ id: `into:${id}` });\n  const after = useDroppable({ id: `after:${id}` });\n  return (\n    <>\n      <div\n        ref={before.setNodeRef}\n        className={cn(\n          \"pointer-events-none absolute inset-x-0 top-0 h-1/4\",\n          before.isOver && \"border-t-2 border-primary\",\n        )}\n      />\n      <div\n        ref={into.setNodeRef}\n        className={cn(\n          \"pointer-events-none absolute inset-x-0 top-1/4 h-2/4\",\n          into.isOver && \"rounded bg-primary/15 ring-1 ring-inset ring-primary\",\n        )}\n      />\n      <div\n        ref={after.setNodeRef}\n        className={cn(\n          \"pointer-events-none absolute inset-x-0 bottom-0 h-1/4\",\n          after.isOver && \"border-b-2 border-primary\",\n        )}\n      />\n    </>\n  );\n}\n\n/* ───────── GanttTimelineGutter (Tier B) ───────── */\n\nexport function GanttTimelineGutter({ className }: { className?: string }) {\n  const ctx = useGanttTimeline();\n  const treeRef = useRef<HTMLDivElement | null>(null);\n  // Alias the bundled ref object to a local so the compiler tracks it as a\n  // RefObject (mutating `.current.scrollTop` is then a legal ref mutation, not a\n  // forbidden modification of a context value — same pattern as the body).\n  const bodyScrollRef = ctx.bodyScrollRef;\n\n  const rows = ctx.rows;\n  // Refs so the focus effect can read the latest rows/rowHeight without widening\n  // its dependency to \"any data change\" (which would steal focus on every edit).\n  const rowsRef = useRef(rows);\n  rowsRef.current = rows;\n  const rowHeightRef = useRef(ctx.rowHeight);\n  rowHeightRef.current = ctx.rowHeight;\n  const activeId = ctx.focusedId ?? rows[0]?.item.id ?? null;\n\n  const sensors = useSensors(\n    useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),\n    useSensor(KeyboardSensor),\n  );\n\n  // Move DOM focus to the focused row. A virtualized row outside the scroll\n  // window isn't in the DOM, so we first scroll the body to bring it into view\n  // (the gutter mirrors body scroll via translateY) — otherwise focus() would\n  // no-op and keyboard nav would silently dead-end past the visible rows. The\n  // body re-renders the row asynchronously after the scroll, so retry across a\n  // few frames until the node exists.\n  useEffect(() => {\n    const fid = ctx.focusedId;\n    const track = treeRef.current;\n    if (!fid || !track) return;\n\n    const idx = rowsRef.current.findIndex((r) => r.item.id === fid);\n    const el = bodyScrollRef.current;\n    const rh = rowHeightRef.current;\n    if (idx >= 0 && el) {\n      const top = idx * rh;\n      const bottom = top + rh;\n      if (top < el.scrollTop) el.scrollTop = top;\n      else if (bottom > el.scrollTop + el.clientHeight)\n        el.scrollTop = bottom - el.clientHeight;\n    }\n\n    const safe =\n      typeof CSS !== \"undefined\" && CSS.escape\n        ? CSS.escape(fid)\n        : fid.replace(/\"/g, '\\\\\"');\n    let raf = 0;\n    let tries = 0;\n    const focusRow = () => {\n      const node = track.querySelector<HTMLElement>(`[data-rowid=\"${safe}\"]`);\n      if (node) node.focus();\n      else if (tries++ < 3) raf = requestAnimationFrame(focusRow);\n    };\n    focusRow();\n    return () => {\n      if (raf) cancelAnimationFrame(raf);\n    };\n  }, [ctx.focusedId, bodyScrollRef]);\n\n  function onKeyDown(e: KeyboardEvent<HTMLDivElement>) {\n    // The context menu portals its content but is still a React child of this\n    // tree, so its keydowns bubble here. Ignore events that didn't originate\n    // inside the tree, else menu navigation double-triggers row nav/select/delete.\n    if (!e.currentTarget.contains(e.target as Node)) return;\n    if (ctx.renamingId) return; // rename input owns the keys\n    const i = rows.findIndex((r) => r.item.id === activeId);\n    const focusAt = (j: number) => {\n      const r = rows[Math.max(0, Math.min(rows.length - 1, j))];\n      if (r) ctx.setFocusedId(r.item.id);\n    };\n    const cur = rows[i];\n    switch (e.key) {\n      case \"ArrowDown\":\n        e.preventDefault();\n        focusAt(i + 1);\n        break;\n      case \"ArrowUp\":\n        e.preventDefault();\n        focusAt(i - 1);\n        break;\n      case \"Home\":\n        e.preventDefault();\n        focusAt(0);\n        break;\n      case \"End\":\n        e.preventDefault();\n        focusAt(rows.length - 1);\n        break;\n      case \"ArrowRight\":\n        if (cur?.hasChildren && cur.collapsed) {\n          e.preventDefault();\n          ctx.toggleCollapse(cur.item.id);\n        } else if (i < rows.length - 1) {\n          e.preventDefault();\n          focusAt(i + 1);\n        }\n        break;\n      case \"ArrowLeft\":\n        if (cur?.hasChildren && !cur.collapsed) {\n          e.preventDefault();\n          ctx.toggleCollapse(cur.item.id);\n        } else if (cur?.parentId) {\n          e.preventDefault();\n          ctx.setFocusedId(cur.parentId);\n        }\n        break;\n      case \"Enter\":\n        if (cur) {\n          e.preventDefault();\n          ctx.select(cur.item.id);\n          ctx.onTaskClick?.(cur.item);\n        }\n        break;\n      case \"F2\":\n        if (cur && ctx.editable) {\n          e.preventDefault();\n          ctx.beginRename(cur.item.id);\n        }\n        break;\n      case \"Delete\":\n      case \"Backspace\":\n        if (cur && ctx.editable) {\n          e.preventDefault();\n          ctx.deleteItem(cur.item.id);\n        }\n        break;\n      case \" \":\n        if (cur?.hasChildren) {\n          e.preventDefault();\n          ctx.toggleCollapse(cur.item.id);\n        }\n        break;\n      default:\n        break;\n    }\n  }\n\n  function onDragEnd(e: DragEndEvent) {\n    const activeId = String(e.active.id);\n    if (!e.over) return;\n    const [zone, targetId] = String(e.over.id).split(\":\");\n    if (!targetId || targetId === activeId) return;\n    const info = ctx.nodeInfo(targetId);\n    if (zone === \"into\") {\n      const target = ctx.getItem(targetId);\n      ctx.moveItemAction(activeId, targetId, target?.children?.length ?? 0);\n    } else if (zone === \"before\") {\n      ctx.moveItemAction(activeId, info?.parentId ?? null, info?.index ?? 0);\n    } else {\n      ctx.moveItemAction(activeId, info?.parentId ?? null, (info?.index ?? 0) + 1);\n    }\n  }\n\n  const tree = (\n    <div\n      ref={treeRef}\n      role=\"tree\"\n      aria-label=\"Task rows\"\n      onKeyDown={onKeyDown}\n      className={cn(\n        \"h-full shrink-0 overflow-hidden border-e border-border bg-card\",\n        className,\n      )}\n      style={{ width: ctx.gutterWidth }}\n    >\n      <div\n        ref={ctx.gutterTrackRef}\n        className=\"relative\"\n        style={{ height: ctx.totalSize }}\n      >\n        {ctx.renderItems.map((ri) => {\n          const row = rows[ri.index];\n          if (!row) return null;\n          return (\n            <GutterRowItem\n              key={row.item.id}\n              row={row}\n              top={ri.start}\n              height={ctx.rowHeight}\n              activeId={activeId}\n            />\n          );\n        })}\n      </div>\n    </div>\n  );\n\n  // A single DndContext is always present (draggables self-disable when read-only)\n  // so the per-row `useDraggable` hooks always have a provider.\n  return (\n    <DndContext\n      sensors={sensors}\n      collisionDetection={pointerWithin}\n      onDragEnd={onDragEnd}\n    >\n      {tree}\n    </DndContext>\n  );\n}\n\n/** One gutter row: drag source (grip activator) + drop zones + the dumb GutterRow. */\nfunction GutterRowItem({\n  row,\n  top,\n  height,\n  activeId,\n}: {\n  row: GanttRow;\n  top: number;\n  height: number;\n  activeId: string | null;\n}) {\n  const ctx = useGanttTimeline();\n  const id = row.item.id;\n  const item = row.item;\n  const canMove = ctx.editable && ctx.can(\"move\", item);\n  const canCreate = ctx.editable && ctx.can(\"create\", item);\n  const canDelete = ctx.editable && ctx.can(\"delete\", item);\n  const draggable = useDraggable({ id, disabled: !canMove });\n\n  return (\n    <div\n      ref={draggable.setNodeRef}\n      className={cn(\"absolute inset-x-0\", draggable.isDragging && \"opacity-40\")}\n      style={{ top, height }}\n    >\n      <GanttContextMenu item={item}>\n        <GutterRow\n          row={row}\n          statusOptions={ctx.statusOptions}\n          labelOptions={ctx.labelOptions}\n          selected={ctx.selectedId === id}\n          tabIndex={activeId === id ? 0 : -1}\n          editable={ctx.editable}\n          renaming={ctx.renamingId === id}\n          canCreate={canCreate}\n          canDelete={canDelete}\n          gripRef={canMove ? draggable.setActivatorNodeRef : undefined}\n          gripProps={\n            canMove ? { ...draggable.listeners, ...draggable.attributes } : undefined\n          }\n          onToggle={() => ctx.toggleCollapse(id)}\n          onActivate={() => {\n            ctx.setFocusedId(id);\n            ctx.select(id);\n            ctx.onTaskClick?.(item);\n          }}\n          onAddChild={() => ctx.createItem(id)}\n          onDelete={() => ctx.deleteItem(id)}\n          onRenameCommit={(name) => {\n            if (name) ctx.renameItemAction(id, name);\n            ctx.endRename();\n          }}\n          onRenameCancel={() => ctx.endRename()}\n        />\n      </GanttContextMenu>\n      {ctx.editable ? <DropZones id={id} /> : null}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/parts/gantt-timeline-gutter.tsx"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/parts/gantt-timeline-root.tsx",
      "content": "\"use client\";\n\nimport {\n  forwardRef,\n  useCallback,\n  useEffect,\n  useImperativeHandle,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport type {\n  GanttColorResolver,\n  GanttContextValue,\n  GanttTimelineHandle,\n  GanttTimelineRootProps,\n  TaskItem,\n} from \"../types\";\nimport {\n  dataExtent as computeExtent,\n  effStartMs,\n  geometryFor as computeGeometry,\n  parseGanttDate,\n  summarySpan,\n} from \"../lib/geometry\";\nimport { ancestorsOf, flatten, indexById, parentIds } from \"../lib/flatten\";\nimport { barFill, resolveRamp, toneFor } from \"../lib/color\";\nimport { useColorTick } from \"../hooks/use-color-tick\";\nimport { useGanttViewport } from \"../hooks/use-gantt-viewport\";\nimport { useGanttVirtual } from \"../hooks/use-gantt-virtual\";\nimport { useGanttEdit } from \"../hooks/use-gantt-edit\";\nimport { GanttContext } from \"../hooks/use-gantt-context\";\nimport { GanttEditPopover } from \"./gantt-edit-popover\";\nimport { GanttQuickComposer } from \"./gantt-quick-composer\";\nimport {\n  readTasksFromClipboardEvent,\n  writeTasksToClipboardEvent,\n} from \"../../task-card/lib/clipboard\";\n\nexport const GanttTimelineRoot = forwardRef<\n  GanttTimelineHandle,\n  GanttTimelineRootProps\n>(function GanttTimelineRoot(props, ref) {\n  const {\n    data,\n    statusOptions,\n    priorityOptions,\n    labelOptions,\n    colorRamp,\n    colorRefreshIntervalMs = 60_000,\n    zoom,\n    defaultZoom = \"week\",\n    onZoomChange,\n    minZoom = \"hour\",\n    maxZoom = \"quarter\",\n    onViewportChange,\n    disableGestures = false,\n    range,\n    now,\n    rowHeight = 36,\n    gutterWidth = 280,\n    showWeekendShading = false,\n    defaultCollapsedIds,\n    collapsedIds,\n    onCollapsedChange,\n    selectedId,\n    onSelect,\n    onTaskClick,\n    renderTooltip,\n    // editing (v0.2.0)\n    editable = false,\n    onChange,\n    snap = \"minor\",\n    quickCompose = true,\n    renderQuickComposer,\n    onTaskReschedule,\n    onItemAdded,\n    onItemRemoved,\n    onItemMoved,\n    onFieldEdited,\n    onStatusChanged,\n    permissions,\n    canMoveItem,\n    canResizeItem,\n    canDeleteItem,\n    canCreateChild,\n    canEditItem,\n    onPermissionDenied,\n    className,\n    children,\n  } = props;\n  const ariaLabel = props[\"aria-label\"];\n\n  /* ── now (SSR-safe) ── */\n  const tick = useColorTick(colorRefreshIntervalMs);\n  const [clientNow, setClientNow] = useState<number | null>(null);\n  useEffect(() => {\n    if (now == null) setClientNow(Date.now());\n  }, [now, tick]);\n  const resolvedNow = now != null ? (typeof now === \"function\" ? now() : now) : null;\n\n  const extent = useMemo(() => computeExtent(data), [data]);\n  const nowMs =\n    resolvedNow != null ? resolvedNow.getTime() : clientNow ?? extent.startMs;\n  const showTodayLine = resolvedNow != null || clientNow != null;\n\n  /* ── collapse (controlled / uncontrolled) ── */\n  const collapseControlled = collapsedIds != null;\n  const [internalCollapsed, setInternalCollapsed] = useState<Set<string>>(\n    () => new Set(defaultCollapsedIds ?? []),\n  );\n  const collapsedSet = useMemo(\n    () => (collapseControlled ? new Set(collapsedIds) : internalCollapsed),\n    [collapseControlled, collapsedIds, internalCollapsed],\n  );\n  const setCollapsed = useCallback(\n    (next: Set<string>) => {\n      if (!collapseControlled) setInternalCollapsed(next);\n      onCollapsedChange?.([...next]);\n    },\n    [collapseControlled, onCollapsedChange],\n  );\n  const isCollapsed = useCallback((id: string) => collapsedSet.has(id), [collapsedSet]);\n  const toggleCollapse = useCallback(\n    (id: string) => {\n      const next = new Set(collapsedSet);\n      if (next.has(id)) next.delete(id);\n      else next.add(id);\n      setCollapsed(next);\n    },\n    [collapsedSet, setCollapsed],\n  );\n\n  /* ── selection (controlled / uncontrolled) ── */\n  const selControlled = selectedId !== undefined;\n  const [internalSel, setInternalSel] = useState<string | null>(null);\n  const selectedVal = selControlled ? selectedId ?? null : internalSel;\n  const select = useCallback(\n    (id: string | null) => {\n      if (!selControlled) setInternalSel(id);\n      onSelect?.(id);\n    },\n    [selControlled, onSelect],\n  );\n\n  const [focusedId, setFocusedId] = useState<string | null>(null);\n\n  /* ── draw mode (v0.4.0) — empty-row drag draws vs pans; toolbar-toggled ── */\n  const [drawMode, setDrawMode] = useState(false);\n\n  /* ── rows + virtualization ── */\n  const rows = useMemo(() => flatten(data, (id) => collapsedSet.has(id)), [data, collapsedSet]);\n  const rowsRef = useRef(rows);\n  rowsRef.current = rows;\n  const itemIndex = useMemo(() => indexById(data), [data]);\n\n  const bodyScrollRef = useRef<HTMLDivElement | null>(null);\n  const gutterTrackRef = useRef<HTMLDivElement | null>(null);\n  const rootRef = useRef<HTMLDivElement | null>(null);\n  const { renderItems, totalSize, measure } = useGanttVirtual({\n    count: rows.length,\n    scrollRef: bodyScrollRef,\n    rowHeight,\n  });\n\n  const [bodyWidth, setBodyWidth] = useState(0);\n\n  /* ── viewport ── */\n  const vp = useGanttViewport({\n    dataExtent: extent,\n    bodyWidth,\n    defaultZoom,\n    controlledZoom: zoom,\n    onZoomChange,\n    minZoom,\n    maxZoom,\n    onViewportChange,\n    range,\n    nowMs,\n  });\n\n  /* ── color + geometry closures ── */\n  const ramp = useMemo(() => resolveRamp(colorRamp), [colorRamp]);\n  const geometryFor = useCallback(\n    (item: TaskItem) => computeGeometry(item, nowMs, toneFor(item, statusOptions)),\n    [nowMs, statusOptions],\n  );\n  const resolveColor = useCallback<GanttColorResolver>(\n    (item) => {\n      const { fill, tone } = barFill(item, nowMs, ramp, statusOptions);\n      return { fill, tone, isOverdue: geometryFor(item).isOverdue };\n    },\n    [nowMs, ramp, statusOptions, geometryFor],\n  );\n  const summarySpanFor = useCallback(\n    (item: TaskItem) => summarySpan(item),\n    [],\n  );\n\n  /* ── editing (v0.2.0) — controlled-echo dispatchers + edit-UI targets ── */\n  const edit = useGanttEdit({\n    data,\n    editable,\n    snap,\n    statusOptions,\n    onChange,\n    onTaskReschedule,\n    onItemAdded,\n    onItemRemoved,\n    onItemMoved,\n    onFieldEdited,\n    onStatusChanged,\n    permissions,\n    canMoveItem,\n    canResizeItem,\n    canDeleteItem,\n    canCreateChild,\n    canEditItem,\n    onPermissionDenied,\n  });\n\n  // Stable locals for the clipboard-effect deps (`edit` is a fresh object each\n  // render; its state fields + useCallback dispatchers are the real dependencies).\n  const {\n    editingId: editEditingId,\n    renamingId: editRenamingId,\n    composerTarget: editComposerTarget,\n    deleteItem: editDeleteItem,\n    nodeInfo: editNodeInfo,\n    pasteTasks: editPasteTasks,\n  } = edit;\n\n  /* ── cross-surface clipboard (v0.5.0) — copy/cut/paste TaskItems through the OS\n        clipboard (shared ilinxa/task envelope; foreign text ignored). Document-level\n        so it fires regardless of the focused element; gated on the gantt containing\n        focus, skipped over text inputs + while an editor/rename/composer is up. ── */\n  useEffect(() => {\n    if (!editable) return;\n    const owns = () => {\n      const active = document.activeElement;\n      return !!rootRef.current && !!active && rootRef.current.contains(active);\n    };\n    const overText = () => {\n      const el = document.activeElement as HTMLElement | null;\n      return (\n        el?.tagName === \"INPUT\" ||\n        el?.tagName === \"TEXTAREA\" ||\n        el?.isContentEditable === true\n      );\n    };\n    const busy = () =>\n      editEditingId != null ||\n      editRenamingId != null ||\n      editComposerTarget != null;\n    const targetId = (): string | null => selectedVal ?? focusedId;\n    const onCopy = (e: ClipboardEvent) => {\n      if (!owns() || overText() || busy()) return;\n      const id = targetId();\n      const item = id ? itemIndex.get(id) : undefined;\n      if (!item) return;\n      writeTasksToClipboardEvent(e, [item], \"gantt-timeline\");\n      e.preventDefault();\n    };\n    const onCut = (e: ClipboardEvent) => {\n      if (!owns() || overText() || busy()) return;\n      const id = targetId();\n      const item = id ? itemIndex.get(id) : undefined;\n      if (!item) return;\n      writeTasksToClipboardEvent(e, [item], \"gantt-timeline\");\n      editDeleteItem(item.id);\n      e.preventDefault();\n    };\n    const onPaste = (e: ClipboardEvent) => {\n      if (!owns() || overText() || busy()) return;\n      const items = readTasksFromClipboardEvent(e);\n      if (!items) return;\n      // Paste as a sibling of the target (root if none); dates preserved.\n      const id = targetId();\n      const info = id ? editNodeInfo(id) : undefined;\n      editPasteTasks(\n        items,\n        info?.parentId ?? null,\n        info ? info.index + 1 : undefined,\n      );\n      e.preventDefault();\n    };\n    document.addEventListener(\"copy\", onCopy);\n    document.addEventListener(\"cut\", onCut);\n    document.addEventListener(\"paste\", onPaste);\n    return () => {\n      document.removeEventListener(\"copy\", onCopy);\n      document.removeEventListener(\"cut\", onCut);\n      document.removeEventListener(\"paste\", onPaste);\n    };\n  }, [\n    editable,\n    editEditingId,\n    editRenamingId,\n    editComposerTarget,\n    editDeleteItem,\n    editNodeInfo,\n    editPasteTasks,\n    selectedVal,\n    focusedId,\n    itemIndex,\n  ]);\n\n  /* ── vertical scroll sync (body drives, gutter mirrors) ── */\n  const onBodyScroll = useCallback((scrollTop: number) => {\n    if (gutterTrackRef.current) {\n      gutterTrackRef.current.style.transform = `translateY(${-scrollTop}px)`;\n    }\n  }, []);\n\n  /* ── scroll-to-item (expand ancestors, then center) ── */\n  const scrollToItemId = useCallback(\n    (id: string) => {\n      const anc = ancestorsOf(data, id);\n      if (anc.length) {\n        const next = new Set(collapsedSet);\n        anc.forEach((a) => next.delete(a));\n        setCollapsed(next);\n      }\n      const item = itemIndex.get(id);\n      if (item) vp.scrollToMs(effStartMs(item));\n      requestAnimationFrame(() => {\n        const idx = rowsRef.current.findIndex((r) => r.item.id === id);\n        const el = bodyScrollRef.current;\n        if (idx >= 0 && el) {\n          el.scrollTop = Math.max(\n            0,\n            idx * rowHeight - el.clientHeight / 2 + rowHeight / 2,\n          );\n        }\n      });\n    },\n    [data, collapsedSet, setCollapsed, itemIndex, vp, rowHeight],\n  );\n\n  /* ── imperative handle ── */\n  useImperativeHandle(\n    ref,\n    () => ({\n      // Same parser as the bars: a date-only string is floating-local.\n      scrollToDate: (d) => vp.scrollToMs(parseGanttDate(d)),\n      scrollToItem: (id) => scrollToItemId(id),\n      scrollToToday: () => vp.scrollToToday(),\n      expandAll: () => setCollapsed(new Set()),\n      collapseAll: () => setCollapsed(new Set(parentIds(data))),\n      setZoom: (z) => vp.setZoomLevel(z),\n      zoomBy: (f) => vp.zoomBy(f),\n      zoomToFit: () => vp.zoomToFit(),\n      addTask: (parentId, item) => edit.createItem(parentId, item),\n      deleteTask: (id) => edit.deleteItem(id),\n      editTask: (id) => edit.openEditor(id),\n      beginRename: (id) => edit.beginRename(id),\n      shiftTaskGroup: (id, deltaMs) => edit.moveSubtree(id, deltaMs),\n    }),\n    [vp, scrollToItemId, setCollapsed, data, edit],\n  );\n\n  const ctx: GanttContextValue = {\n    rows,\n    renderItems,\n    totalSize,\n    rowHeight,\n    gutterWidth,\n    bodyScrollRef,\n    gutterTrackRef,\n    onBodyScroll,\n    /*\n     * v0.5.1 — `measureRows` is public (it reaches consumers through the\n     * exported `useGanttTimeline()` context) and was an empty body, so a\n     * consumer re-measuring after a row-height change got silence. The\n     * virtualizer's own `measure()` was already returned by `useGanttVirtual`\n     * and simply never destructured.\n     */\n    measureRows: measure,\n    viewport: vp.viewport,\n    bodyWidth,\n    setBodyWidth,\n    dataExtent: extent,\n    disableGestures,\n    onPan: vp.onPan,\n    onZoomAt: vp.onZoomAt,\n    beginPan: vp.beginPan,\n    endPanWithVelocity: vp.endPanWithVelocity,\n    namedZoom: vp.namedZoom,\n    setZoomLevel: vp.setZoomLevel,\n    zoomBy: vp.zoomBy,\n    zoomToFit: vp.zoomToFit,\n    scrollToToday: vp.scrollToToday,\n    scrollToItemId,\n    pageBy: vp.pageBy,\n    nowMs,\n    showTodayLine,\n    resolveColor,\n    geometryFor,\n    summarySpanFor,\n    statusOptions,\n    priorityOptions,\n    labelOptions,\n    showWeekendShading,\n    isCollapsed,\n    toggleCollapse,\n    selectedId: selectedVal,\n    select,\n    onTaskClick,\n    renderTooltip,\n    focusedId,\n    setFocusedId,\n\n    // editing (v0.2.0)\n    editable,\n    snap,\n    drawMode,\n    setDrawMode,\n    permissions,\n    getItem: (id: string) => itemIndex.get(id),\n    can: edit.can,\n    canGroupMove: edit.canGroupMove,\n    nodeInfo: edit.nodeInfo,\n    rescheduleItem: edit.rescheduleItem,\n    createItem: edit.createItem,\n    deleteItem: edit.deleteItem,\n    renameItemAction: edit.renameItemAction,\n    moveItemAction: edit.moveItemAction,\n    moveSubtree: edit.moveSubtree,\n    changeStatus: edit.changeStatus,\n    changePriority: edit.changePriority,\n    editingId: edit.editingId,\n    openEditor: edit.openEditor,\n    closeEditor: edit.closeEditor,\n    applyEditedSubtree: edit.applyEditedSubtree,\n    renamingId: edit.renamingId,\n    beginRename: edit.beginRename,\n    endRename: edit.endRename,\n    // quick-create composer (v0.5.0)\n    quickCompose,\n    renderQuickComposer,\n    composerTarget: edit.composerTarget,\n    openComposer: edit.openComposer,\n    closeComposer: edit.closeComposer,\n    // cross-surface clipboard (v0.5.0)\n    copyItem: edit.copyItem,\n    cutItem: edit.cutItem,\n    pasteTasks: edit.pasteTasks,\n  };\n\n  return (\n    <GanttContext.Provider value={ctx}>\n      <div\n        ref={rootRef}\n        role=\"group\"\n        aria-label={ariaLabel ?? \"Gantt timeline\"}\n        className={cn(\"text-foreground\", className)}\n      >\n        {children}\n      </div>\n      {editable ? <GanttEditPopover /> : null}\n      {editable ? <GanttQuickComposer /> : null}\n    </GanttContext.Provider>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/parts/gantt-timeline-root.tsx"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/parts/gantt-timeline-skeleton.tsx",
      "content": "\"use client\";\n\nimport { Skeleton } from \"@/components/ui/skeleton\";\nimport { cn } from \"@/lib/utils\";\n\n/** Tier C — loading placeholder (axis + rows). Zero state; composes anywhere. */\nexport function GanttTimelineSkeleton({\n  rows = 7,\n  gutterWidth = 280,\n  rowHeight = 36,\n  className,\n}: {\n  rows?: number;\n  gutterWidth?: number;\n  rowHeight?: number;\n  className?: string;\n}) {\n  return (\n    <div\n      className={cn(\n        \"overflow-hidden rounded-lg border border-border bg-card\",\n        className,\n      )}\n      aria-busy\n      aria-label=\"Loading timeline\"\n    >\n      <div className=\"flex border-b border-border\">\n        <div\n          className=\"flex shrink-0 items-center border-e border-border p-2\"\n          style={{ width: gutterWidth }}\n        >\n          <Skeleton className=\"h-4 w-24\" />\n        </div>\n        <div className=\"flex grow items-center gap-6 p-2\">\n          {Array.from({ length: 6 }).map((_, i) => (\n            <Skeleton key={i} className=\"h-4 w-16\" />\n          ))}\n        </div>\n      </div>\n      {Array.from({ length: rows }).map((_, i) => (\n        <div\n          key={i}\n          className=\"flex border-b border-border/40\"\n          style={{ height: rowHeight }}\n        >\n          <div\n            className=\"flex shrink-0 items-center gap-2 border-e border-border px-2\"\n            style={{ width: gutterWidth, paddingLeft: 8 + (i % 3) * 16 }}\n          >\n            <Skeleton className=\"size-4 rounded-full\" />\n            <Skeleton className=\"h-3.5 w-28\" />\n          </div>\n          <div className=\"flex grow items-center px-3\">\n            <Skeleton\n              className=\"h-4 rounded\"\n              style={{\n                width: `${28 + ((i * 37) % 48)}%`,\n                marginLeft: `${(i * 53) % 30}%`,\n              }}\n            />\n          </div>\n        </div>\n      ))}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/parts/gantt-timeline-skeleton.tsx"
    },
    {
      "path": "src/registry/components/data/gantt-timeline/parts/gantt-timeline-toolbar.tsx",
      "content": "\"use client\";\n\nimport { CalendarClock, Maximize2, Minus, Pencil, Plus } from \"lucide-react\";\nimport { Button } from \"@/components/ui/button\";\nimport { Separator } from \"@/components/ui/separator\";\nimport { cn } from \"@/lib/utils\";\nimport { useGanttTimeline } from \"../hooks/use-gantt-context\";\nimport type { GanttZoom } from \"../types\";\n\nconst ZOOMS: { value: GanttZoom; label: string }[] = [\n  { value: \"hour\", label: \"H\" },\n  { value: \"day\", label: \"D\" },\n  { value: \"week\", label: \"W\" },\n  { value: \"month\", label: \"M\" },\n  { value: \"quarter\", label: \"Q\" },\n];\n\nexport function GanttTimelineToolbar({ className }: { className?: string }) {\n  const {\n    namedZoom,\n    setZoomLevel,\n    zoomBy,\n    zoomToFit,\n    scrollToToday,\n    editable,\n    drawMode,\n    setDrawMode,\n  } = useGanttTimeline();\n  return (\n    <div\n      className={cn(\n        \"flex items-center gap-1.5 border-b border-border bg-card px-2 py-1.5\",\n        className,\n      )}\n    >\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"ghost\"\n        className=\"h-7 gap-1.5 px-2 text-xs\"\n        onClick={scrollToToday}\n      >\n        <CalendarClock className=\"size-3.5\" /> Today\n      </Button>\n      <Separator orientation=\"vertical\" className=\"mx-0.5 h-5\" />\n      <Button\n        type=\"button\"\n        size=\"icon\"\n        variant=\"outline\"\n        className=\"size-7\"\n        aria-label=\"Zoom out\"\n        onClick={() => zoomBy(0.7)}\n      >\n        <Minus className=\"size-3.5\" />\n      </Button>\n      <Button\n        type=\"button\"\n        size=\"icon\"\n        variant=\"outline\"\n        className=\"size-7\"\n        aria-label=\"Zoom in\"\n        onClick={() => zoomBy(1 / 0.7)}\n      >\n        <Plus className=\"size-3.5\" />\n      </Button>\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"ghost\"\n        className=\"h-7 gap-1.5 px-2 text-xs\"\n        onClick={zoomToFit}\n      >\n        <Maximize2 className=\"size-3.5\" /> Fit\n      </Button>\n      <Separator orientation=\"vertical\" className=\"mx-0.5 h-5\" />\n      <div\n        role=\"group\"\n        aria-label=\"Zoom level\"\n        className=\"ms-auto inline-flex overflow-hidden rounded-md border border-border\"\n      >\n        {ZOOMS.map((z) => (\n          <button\n            key={z.value}\n            type=\"button\"\n            aria-pressed={namedZoom === z.value}\n            onClick={() => setZoomLevel(z.value)}\n            className={cn(\n              \"h-7 w-7 text-xs font-medium transition-colors\",\n              namedZoom === z.value\n                ? \"bg-primary text-primary-foreground\"\n                : \"bg-card text-muted-foreground hover:bg-muted hover:text-foreground\",\n            )}\n          >\n            {z.label}\n          </button>\n        ))}\n      </div>\n      {editable ? (\n        <>\n          <Separator orientation=\"vertical\" className=\"mx-0.5 h-5\" />\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant={drawMode ? \"default\" : \"ghost\"}\n            aria-pressed={drawMode}\n            title=\"Draw mode — drag an empty row to create a task (off = drag to pan)\"\n            className=\"h-7 gap-1.5 px-2 text-xs\"\n            onClick={() => setDrawMode(!drawMode)}\n          >\n            <Pencil className=\"size-3.5\" /> Draw\n          </Button>\n        </>\n      ) : null}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/gantt-timeline/parts/gantt-timeline-toolbar.tsx"
    }
  ],
  "meta": {
    "version": "0.7.2",
    "status": "alpha"
  },
  "categories": [
    "data",
    "task-management"
  ],
  "type": "registry:block"
}