Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(tasks): add task and project gantt timelines (#7809)

dev-rbe5e595dfc4a1
diff --git a/apps/web/src/components/gantt/create-gantt-creation.ts b/apps/web/src/components/gantt/create-gantt-creation.ts
new file mode 100644
index 0000000000..45b6d9ac44
--- /dev/null
+++ b/apps/web/src/components/gantt/create-gantt-creation.ts
@@ -0,0 +1,135 @@
+import {
+ type Accessor,
+ createEffect,
+ createSignal,
+ on,
+ onCleanup,
+} from 'solid-js';
+import { HEADER_HEIGHT } from './gantt-context';
+import { type GanttDate, ganttDateFromDay, toGanttDay } from './gantt-date';
+import { type GanttGuide, ganttCreationRange } from './gantt-interaction';
+
+export type GanttCreation = { start: Date; end: Date };
+
+/** Owns selection and pointer listeners; only a completed gesture opens the host composer. */
+export function createGanttCreation(options: {
+ viewport: Accessor<HTMLDivElement | undefined>;
+ editing: Accessor<boolean>;
+ setEditing: (editing: boolean) => void;
+ clearGuide: () => void;
+ labelWidth: Accessor<number>;
+ pointToDay: (
+ clientX: number,
+ exclude?: HTMLElement,
+ snap?: boolean
+ ) => GanttGuide | undefined;
+ onCreate: Accessor<((dates: GanttCreation) => void) | undefined>;
+ minDate: Accessor<GanttDate>;
+}) {
+ const [draft, setDraft] = createSignal<{
+ first: number;
+ last: number;
+ top: number;
+ }>();
+ let cancelGesture: (() => void) | undefined;
+
+ function begin(event: PointerEvent) {
+ const viewport = options.viewport();
+ if (
+ !options.onCreate() ||
+ !viewport ||
+ event.button !== 0 ||
+ options.editing()
+ )
+ return;
+
+ const target = event.target;
+ if (
+ !(target instanceof Element) ||
+ target.closest(
+ 'button, a, input, [data-gantt-bar], [data-gantt-label], [data-gantt-header], [data-gantt-group-header], [data-gantt-pagination]'
+ )
+ )
+ return;
+
+ const rect = viewport.getBoundingClientRect();
+ if (event.clientY < rect.top + HEADER_HEIGHT) return;
+ const first = options.pointToDay(event.clientX, undefined, false)?.day;
+ const minimum = toGanttDay(options.minDate());
+ if (first === undefined || (minimum !== undefined && first < minimum))
+ return;
+
+ event.preventDefault();
+ const pointerId = event.pointerId;
+ const initialX = event.clientX;
+ const top = event.clientY - rect.top + viewport.scrollTop - 14;
+ let last = first;
+ let moved = false;
+ let finished = false;
+ options.setEditing(true);
+ options.clearGuide();
+
+ const update = (next: PointerEvent) => {
+ if (finished || next.pointerId !== pointerId) return;
+ moved ||= Math.abs(next.clientX - initialX) >= 8;
+ const x = Math.max(
+ rect.left + options.labelWidth(),
+ Math.min(next.clientX, rect.right - 1)
+ );
+ last = Math.max(
+ minimum ?? -Infinity,
+ options.pointToDay(x, undefined, false)?.day ?? last
+ );
+ if (moved) setDraft({ first, last, top });
+ };
+ const cancel = () => {
+ // Cancellation also invalidates callbacks already queued for this gesture.
+ if (finished) return;
+ finished = true;
+ window.removeEventListener('pointermove', update);
+ window.removeEventListener('pointerup', finish);
+ window.removeEventListener('pointercancel', cancel);
+ window.removeEventListener('keydown', cancelOnEscape, true);
+ window.removeEventListener('blur', cancel);
+ options.setEditing(false);
+ setDraft(undefined);
+ cancelGesture = undefined;
+ };
+ const cancelOnEscape = (next: KeyboardEvent) => {
+ if (finished || next.key !== 'Escape') return;
+ next.preventDefault();
+ next.stopPropagation();
+ cancel();
+ };
+ const finish = (next: PointerEvent) => {
+ if (finished || next.pointerId !== pointerId) return;
+ update(next);
+ const range = ganttCreationRange(first, last);
+ cancel();
+ if (moved)
+ options.onCreate()?.({
+ start: ganttDateFromDay(range.start),
+ end: ganttDateFromDay(range.end - 1),
+ });
+ };
+
+ cancelGesture = cancel;
+ window.addEventListener('pointermove', update);
+ window.addEventListener('pointerup', finish);
+ window.addEventListener('pointercancel', cancel);
+ window.addEventListener('keydown', cancelOnEscape, true);
+ window.addEventListener('blur', cancel);
+ }
+
+ createEffect(
+ on(options.viewport, (viewport) => {
+ viewport?.addEventListener('pointerdown', begin);
+ onCleanup(() => {
+ viewport?.removeEventListener('pointerdown', begin);
+ cancelGesture?.();
+ });
+ })
+ );
+
+ return { draft };
+}
diff --git a/apps/web/src/components/gantt/create-gantt-pan.ts b/apps/web/src/components/gantt/create-gantt-pan.ts
new file mode 100644
index 0000000000..cd4ffc1744
--- /dev/null
+++ b/apps/web/src/components/gantt/create-gantt-pan.ts
@@ -0,0 +1,76 @@
+import { type Accessor, createSignal, onCleanup } from 'solid-js';
+
+/** Owns one middle-button gesture; calendar geometry stays with Gantt.Root. */
+export function createGanttPan(options: {
+ viewport: Accessor<HTMLDivElement | undefined>;
+ editing: Accessor<boolean>;
+ setEditing: (editing: boolean) => void;
+ clearGuide: () => void;
+ panBy: (deltaX: number, deltaY: number) => void;
+}) {
+ const [panning, setPanning] = createSignal(false);
+ let cancelGesture: (() => void) | undefined;
+
+ function start(event: MouseEvent) {
+ const viewport = options.viewport();
+ if (event.button !== 1 || options.editing() || panning() || !viewport)
+ return;
+
+ event.preventDefault();
+ event.stopPropagation();
+ let x = event.clientX;
+ let y = event.clientY;
+ let finished = false;
+ options.clearGuide();
+ options.setEditing(true);
+ setPanning(true);
+
+ const finish = () => {
+ // Removed listeners can still have queued callbacks; termination is final.
+ if (finished) return;
+ finished = true;
+ window.removeEventListener('mousemove', move, true);
+ window.removeEventListener('mouseup', release, true);
+ window.removeEventListener('keydown', cancelOnEscape, true);
+ window.removeEventListener('blur', finish);
+ setPanning(false);
+ options.setEditing(false);
+ cancelGesture = undefined;
+ };
+ const move = (next: MouseEvent) => {
+ if (finished) return;
+ if (options.viewport() !== viewport || !(next.buttons & 4)) {
+ finish();
+ return;
+ }
+ next.preventDefault();
+ next.stopPropagation();
+ options.panBy(x - next.clientX, y - next.clientY);
+ x = next.clientX;
+ y = next.clientY;
+ };
+ const release = (next: MouseEvent) => {
+ if (finished || next.button !== 1) return;
+ next.preventDefault();
+ next.stopPropagation();
+ finish();
+ };
+ const cancelOnEscape = (next: KeyboardEvent) => {
+ if (finished || next.key !== 'Escape') return;
+ next.preventDefault();
+ next.stopPropagation();
+ finish();
+ };
+
+ cancelGesture = finish;
+ window.addEventListener('mousemove', move, true);
+ window.addEventListener('mouseup', release, true);
+ window.addEventListener('keydown', cancelOnEscape, true);
+ window.addEventListener('blur', finish);
+ }
+
+ const cancel = () => cancelGesture?.();
+ onCleanup(cancel);
+
+ return { panning, start, cancel };
+}
diff --git a/apps/web/src/components/gantt/create-gantt-today.ts b/apps/web/src/components/gantt/create-gantt-today.ts
new file mode 100644
index 0000000000..20826f8b8a
--- /dev/null
+++ b/apps/web/src/components/gantt/create-gantt-today.ts
@@ -0,0 +1,30 @@
+import { createSignal, onCleanup, onMount } from 'solid-js';
+import { toGanttDay } from './gantt-date';
+
+/** One local-day clock per chart, including tabs that resume after midnight. */
+export function createGanttToday() {
+ const [today, setToday] = createSignal(toGanttDay(new Date())!);
+ onMount(() => {
+ let timer: ReturnType<typeof setTimeout>;
+ const refresh = () => {
+ clearTimeout(timer);
+ const now = new Date();
+ setToday(toGanttDay(now)!);
+ const midnight = new Date(now);
+ midnight.setHours(24, 0, 0, 0);
+ timer = setTimeout(refresh, midnight.getTime() - now.getTime());
+ };
+ const onVisibility = () => {
+ if (document.visibilityState === 'visible') refresh();
+ };
+ refresh();
+ window.addEventListener('focus', refresh);
+ document.addEventListener('visibilitychange', onVisibility);
+ onCleanup(() => {
+ clearTimeout(timer);
+ window.removeEventListener('focus', refresh);
+ document.removeEventListener('visibilitychange', onVisibility);
+ });
+ });
+ return today;
+}
diff --git a/apps/web/src/components/gantt/gantt-bar.test.ts b/apps/web/src/components/gantt/gantt-bar.test.ts
new file mode 100644
index 0000000000..34854c3b2c
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-bar.test.ts
@@ -0,0 +1,125 @@
+import { cleanup, fireEvent, render } from '@solidjs/testing-library';
+import { createComponent, createSignal } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import { Gantt } from './gantt';
+import { toGanttDay } from './gantt-date';
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+it('increases deadline urgency on calendar days but excludes undated, inactive, and clipped ends', () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date(2026, 2, 3, 12));
+ const [end, setEnd] = createSignal<string | null>('2026-03-11');
+ const [enabled, setEnabled] = createSignal(true);
+ const view = render(() =>
+ createComponent(Gantt.Root, {
+ range: {
+ start: toGanttDay('2026-03-01')!,
+ end: toGanttDay('2026-03-21')!,
+ },
+ defaultScale: 'day',
+ get children() {
+ return createComponent(Gantt.Bar, {
+ start: '2026-03-01',
+ get end() {
+ return end();
+ },
+ get deadlineWarning() {
+ return enabled();
+ },
+ });
+ },
+ })
+ );
+ const warning = () =>
+ view.container.querySelector<HTMLElement>('[data-gantt-end-warning]');
+ expect(warning()).toBeNull();
+ setEnd('2026-03-10');
+ const distant = Number(warning()!.dataset.ganttEndWarning);
+ setEnd('2026-03-04');
+ expect(Number(warning()!.dataset.ganttEndWarning)).toBeGreaterThan(distant);
+ setEnd('2026-03-03');
+ expect(Number(warning()!.dataset.ganttEndWarning)).toBe(0.35);
+ setEnd('2026-03-02');
+ expect(Number(warning()!.dataset.ganttEndWarning)).toBe(0.35);
+ setEnabled(false);
+ expect(warning()).toBeNull();
+ setEnabled(true);
+ setEnd(null);
+ expect(warning()).toBeNull();
+ vi.setSystemTime(new Date(2026, 2, 28, 12));
+ fireEvent.focus(window);
+ setEnd('2026-03-30');
+ expect(warning()).toBeNull();
+});
+
+it('refreshes all deadline gradients and Today at local midnight and on tab resume, then clears the shared timer', async () => {
+ vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] });
+ vi.setSystemTime(new Date(2026, 2, 7, 23, 59, 59));
+ const view = render(() =>
+ createComponent(Gantt.Root, {
+ range: {
+ start: toGanttDay('2026-03-01')!,
+ end: toGanttDay('2026-03-21')!,
+ },
+ defaultScale: 'day',
+ get children() {
+ return [
+ createComponent(Gantt.Bar, {
+ start: '2026-03-01',
+ end: '2026-03-15',
+ }),
+ createComponent(Gantt.Bar, {
+ start: '2026-03-01',
+ end: '2026-03-08',
+ }),
+ createComponent(Gantt.TodayMarker, {}),
+ ];
+ },
+ })
+ );
+ const strength = (end: string) =>
+ Number(
+ view.container.querySelector<HTMLElement>(
+ `[data-gantt-end="${toGanttDay(end)}"] [data-gantt-end-warning]`
+ )?.dataset.ganttEndWarning ?? 0
+ );
+ const todayLeft = () =>
+ Number.parseFloat(
+ view.container.querySelector<HTMLElement>('[data-gantt-today]')!.style
+ .left
+ );
+ const initialLeft = todayLeft();
+ expect(strength('2026-03-15')).toBe(0);
+ expect(strength('2026-03-08')).toBeLessThan(0.35);
+ expect(vi.getTimerCount()).toBe(1);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(strength('2026-03-15')).toBeGreaterThan(0);
+ expect(strength('2026-03-08')).toBe(0.35);
+ expect(todayLeft()).toBe(initialLeft + 40);
+ // Local calendar midnights can be 23 or 25 hours apart across DST.
+ await vi.advanceTimersByTimeAsync(
+ new Date(2026, 2, 9).getTime() - new Date(2026, 2, 8).getTime()
+ );
+ expect(todayLeft()).toBe(initialLeft + 80);
+ expect(vi.getTimerCount()).toBe(1);
+ const previous = strength('2026-03-15');
+ const visibility = vi.spyOn(document, 'visibilityState', 'get');
+ visibility.mockReturnValue('hidden');
+ vi.setSystemTime(new Date(2026, 2, 12, 12));
+ fireEvent(document, new Event('visibilitychange'));
+ expect(strength('2026-03-15')).toBe(previous);
+ visibility.mockReturnValue('visible');
+ fireEvent(document, new Event('visibilitychange'));
+ expect(strength('2026-03-15')).toBeGreaterThan(previous);
+ expect(vi.getTimerCount()).toBe(1);
+ view.unmount();
+ fireEvent.focus(window);
+ fireEvent(document, new Event('visibilitychange'));
+ expect(vi.getTimerCount()).toBe(0);
+});
diff --git a/apps/web/src/components/gantt/gantt-bar.tsx b/apps/web/src/components/gantt/gantt-bar.tsx
new file mode 100644
index 0000000000..399d1da7de
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-bar.tsx
@@ -0,0 +1,135 @@
+import { cn, Layer } from '@ui';
+import { createMemo, type JSX, Show, splitProps } from 'solid-js';
+import { GanttCalendarClip } from './gantt-clip';
+import { useGantt } from './gantt-context';
+import {
+ formatGanttDay,
+ type GanttDate,
+ ganttBarGeometry,
+ toGanttDay,
+} from './gantt-date';
+
+export function GanttBar(
+ props: Omit<JSX.ButtonHTMLAttributes<HTMLButtonElement>, 'style'> & {
+ start: GanttDate;
+ end?: GanttDate;
+ deadlineWarning?: boolean;
+ }
+) {
+ const gantt = useGantt();
+ const [local, rest] = splitProps(props, [
+ 'start',
+ 'end',
+ 'deadlineWarning',
+ 'class',
+ 'children',
+ 'title',
+ ]);
+ const geometry = createMemo(() => {
+ const start = toGanttDay(local.start);
+ const end = local.end;
+ const range = gantt.range();
+ // An undated interval has an open tail, not an unreachable handle at an infinite horizon.
+ const openEnd = Math.max((start ?? range.start) + 7, gantt.today() + 7);
+ return ganttBarGeometry(
+ { start: local.start, end },
+ end == null || end === ''
+ ? { ...range, end: Math.min(range.end, openEnd) }
+ : range,
+ gantt.pixelsPerDay()
+ );
+ });
+ const placed = () => {
+ const value = geometry();
+ return 'left' in value ? value : undefined;
+ };
+
+ return (
+ <Show when={placed()}>
+ {(bar) => {
+ const description = () =>
+ `${local.title ?? 'Timeline item'}: ${formatGanttDay(bar().start)} → ${bar().end === undefined ? 'No end date' : formatGanttDay(bar().end!)}`;
+ const position = () => ({
+ left: `${gantt.labelWidth() + bar().left}px`,
+ width: `${bar().width}px`,
+ });
+ const drawerInset = () =>
+ gantt.labelWidth() === 0 && gantt.sidebar.open()
+ ? gantt.sidebar.width()
+ : 0;
+ const deadlineUrgency = () => {
+ const end = bar().end;
+ if (
+ local.deadlineWarning === false ||
+ end === undefined ||
+ end + 1 > gantt.range().end
+ )
+ return 0;
+ const remaining = end - gantt.today();
+ return Math.min(1, Math.max(0, (8 - remaining) / 8));
+ };
+ return (
+ <div
+ data-gantt-bar=""
+ data-gantt-start={bar().start}
+ data-gantt-end={bar().end}
+ class="group pointer-events-none absolute top-1/2 z-10 h-7 -translate-y-1/2 text-xs"
+ style={position()}
+ >
+ <GanttCalendarClip width={bar().width}>
+ <Layer depth={2}>
+ <div
+ data-gantt-bar-body=""
+ class={cn(
+ 'group/bar pointer-events-auto relative size-full rounded-md text-ink',
+ local.class
+ )}
+ >
+ <span
+ aria-hidden="true"
+ data-gantt-bar-fill=""
+ data-gantt-end-warning={
+ deadlineUrgency() > 0
+ ? deadlineUrgency() * 0.35
+ : undefined
+ }
+ class="pointer-events-none absolute inset-0 rounded-[inherit] shadow-sm [--gantt-bar-bg:var(--color-surface)] bg-[color:var(--gantt-bar-bg)] [background-image:var(--gantt-bar-gradient,none)] group-hover/bar:[background-image:linear-gradient(var(--color-hover),var(--color-hover)),var(--gantt-bar-gradient,none)] light-mode:[--gantt-bar-bg:color-mix(in_oklch,var(--color-surface)_92%,var(--color-ink))]"
+ style={{
+ '--gantt-bar-gradient':
+ deadlineUrgency() > 0
+ ? `linear-gradient(to left, color-mix(in oklch, var(--color-failure-ink) ${deadlineUrgency() * 35}%, var(--gantt-bar-bg)), var(--gantt-bar-bg) 65%)`
+ : undefined,
+ 'mask-image':
+ bar().kind === 'open-ended'
+ ? 'linear-gradient(to right, black 65%, transparent 100%)'
+ : undefined,
+ }}
+ />
+ <button
+ {...rest}
+ type="button"
+ title={description()}
+ aria-label={rest['aria-label'] ?? description()}
+ class="relative size-full text-left whitespace-nowrap outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-current"
+ >
+ <span
+ data-gantt-bar-label=""
+ class="sticky flex h-full w-max max-w-full items-center overflow-hidden px-2"
+ style={{
+ left: `${gantt.labelWidth() + drawerInset()}px`,
+ }}
+ >
+ <span class="flex min-w-0 items-center gap-1.5">
+ {local.children}
+ </span>
+ </span>
+ </button>
+ </div>
+ </Layer>
+ </GanttCalendarClip>
+ </div>
+ );
+ }}
+ </Show>
+ );
+}
diff --git a/apps/web/src/components/gantt/gantt-chart.tsx b/apps/web/src/components/gantt/gantt-chart.tsx
new file mode 100644
index 0000000000..de173b54d9
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-chart.tsx
@@ -0,0 +1,188 @@
+import { cn, Scroll } from '@ui';
+import {
+ createMemo,
+ For,
+ onCleanup,
+ onMount,
+ type ParentProps,
+} from 'solid-js';
+import { createGanttPan } from './create-gantt-pan';
+import { GanttCalendarScene } from './gantt-clip';
+import { HEADER_HEIGHT, useGantt } from './gantt-context';
+import { ganttTicks } from './gantt-date';
+import { GanttCursorGuide } from './gantt-markers';
+
+export function GanttChart(
+ props: ParentProps<{ class?: string; label?: string }>
+) {
+ const gantt = useGantt();
+ let element: HTMLDivElement | undefined;
+ let pointerX: number | undefined;
+ let centered = false;
+ const pan = createGanttPan({
+ viewport: gantt.viewport,
+ editing: gantt.editing,
+ setEditing: gantt.setEditing,
+ clearGuide: () => {
+ pointerX = undefined;
+ gantt.setGuide(undefined);
+ },
+ panBy: gantt.panBy,
+ });
+ const preventMiddleClick = (event: MouseEvent) => {
+ if (event.button !== 1) return;
+ event.preventDefault();
+ event.stopPropagation();
+ };
+ const measure = () => {
+ gantt.updateViewport();
+ if (centered || !element?.clientWidth) return;
+ centered = true;
+ queueMicrotask(() => {
+ if (gantt.viewport() === element) gantt.scrollToToday('instant');
+ });
+ };
+ const zoom = (event: WheelEvent) => {
+ if (!event.ctrlKey && !event.metaKey) {
+ // Wheel events continue at a clamped edge even when no scroll event fires.
+ gantt.updateViewport();
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ if (
+ event.target instanceof Element &&
+ event.target.closest('[data-gantt-label]')
+ )
+ return;
+ if (gantt.editing()) return;
+ gantt.markScrollZoom();
+ let unit = 1;
+ switch (event.deltaMode) {
+ case WheelEvent.DOM_DELTA_LINE:
+ unit = 16;
+ break;
+ case WheelEvent.DOM_DELTA_PAGE:
+ unit = element!.clientHeight;
+ break;
+ }
+ gantt.zoomAt(event.clientX, event.deltaY * unit);
+ updateGuide();
+ };
+ const updateGuide = () =>
+ queueMicrotask(() => {
+ if (
+ pointerX === undefined ||
+ gantt.editing() ||
+ gantt.viewport() !== element
+ )
+ return;
+ gantt.setGuide(gantt.pointToDay(pointerX));
+ });
+ onMount(() => {
+ const resize = new ResizeObserver(measure);
+ const attachment = new MutationObserver(connect);
+ function connect() {
+ if (!element?.isConnected) return;
+ attachment.disconnect();
+ gantt.setViewport(element);
+ resize.observe(element);
+ element.addEventListener('wheel', zoom, { passive: false });
+ element.addEventListener('mousedown', pan.start, true);
+ element.addEventListener('auxclick', preventMiddleClick, true);
+ measure();
+ }
+ attachment.observe(document, { childList: true, subtree: true });
+ connect();
+ onCleanup(() => {
+ resize.disconnect();
+ attachment.disconnect();
+ element?.removeEventListener('wheel', zoom);
+ element?.removeEventListener('mousedown', pan.start, true);
+ element?.removeEventListener('auxclick', preventMiddleClick, true);
+ pan.cancel();
+ if (gantt.viewport() === element) gantt.setViewport(undefined);
+ });
+ });
+ return (
+ <Scroll
+ class={cn('min-h-0 min-w-0 flex-1', props.class)}
+ orientation="both"
+ scrollbars="both"
+ autoHide={false}
+ verticalScrollbarInset={HEADER_HEIGHT}
+ scrollRef={(viewport) => {
+ element = viewport;
+ }}
+ viewportProps={{
+ 'aria-label': props.label ?? 'Gantt timeline',
+ class: pan.panning()
+ ? 'cursor-grabbing select-none [&_*]:cursor-grabbing'
+ : undefined,
+ tabIndex: 0,
+ style: { 'overscroll-behavior': 'none', 'overflow-anchor': 'none' },
+ onScroll: () => {
+ gantt.updateViewport();
+ updateGuide();
+ },
+ onPointerMove: (event) => {
+ if (
+ event.target.closest(
+ '[data-gantt-label], [data-gantt-group-header]'
+ )
+ ) {
+ pointerX = undefined;
+ gantt.setGuide(undefined);
+ return;
+ }
+ pointerX = event.clientX;
+ if (gantt.editing()) return;
+ gantt.setGuide(gantt.pointToDay(event.clientX));
+ },
+ onPointerLeave: () => {
+ pointerX = undefined;
+ if (!gantt.editing()) gantt.setGuide(undefined);
+ },
+ }}
+ contentProps={{
+ style: {
+ position: 'relative',
+ isolation: 'isolate',
+ width: `${gantt.width()}px`,
+ 'min-height': '100%',
+ 'padding-bottom': '32px',
+ },
+ }}
+ >
+ <GridLines />
+ <GanttCursorGuide />
+ {props.children}
+ </Scroll>
+ );
+}
+
+function GridLines() {
+ const gantt = useGantt();
+ const ticks = createMemo(() =>
+ gantt.gridVisible()
+ ? ganttTicks(gantt.range(), gantt.gridScale(), gantt.visibleRange())
+ : []
+ );
+ return (
+ <GanttCalendarScene>
+ <For each={ticks()}>
+ {(tick) => (
+ <div
+ class={cn(
+ 'absolute inset-y-0 border-l border-edge-muted/60',
+ gantt.gridStyle() === 'dashed' && 'border-dashed'
+ )}
+ style={{
+ left: `${gantt.labelWidth() + (tick.start - gantt.range().start) * gantt.pixelsPerDay()}px`,
+ }}
+ />
+ )}
+ </For>
+ </GanttCalendarScene>
+ );
+}
diff --git a/apps/web/src/components/gantt/gantt-clip.tsx b/apps/web/src/components/gantt/gantt-clip.tsx
new file mode 100644
index 0000000000..749c6c2d64
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-clip.tsx
@@ -0,0 +1,54 @@
+import { cn } from '@ui';
+import type { ParentProps } from 'solid-js';
+import { HEADER_HEIGHT, useGantt } from './gantt-context';
+
+/** The transformed parent owns positioning; native sticky clipping excludes the label column. */
+export function GanttCalendarClip(
+ props: ParentProps<{ width: number; inset?: number; closingInset?: number }>
+) {
+ const gantt = useGantt();
+ return (
+ <div
+ data-gantt-calendar-clip=""
+ class={cn(
+ 'sticky h-full w-0',
+ props.closingInset !== undefined &&
+ 'animate-[gantt-scene-close_200ms_linear] motion-reduce:animate-none'
+ )}
+ style={{
+ left: `${props.inset ?? gantt.labelWidth()}px`,
+ 'clip-path': `inset(0 -${props.width}px 0 0)`,
+ '--gantt-closing-inset': `${props.closingInset ?? 0}px`,
+ }}
+ >
+ <div class="fixed inset-0">{props.children}</div>
+ </div>
+ );
+}
+
+/** Native clipping keeps decoration out of both fixed labels and floating item panels. */
+export function GanttCalendarScene(props: ParentProps<{ class?: string }>) {
+ const gantt = useGantt();
+ return (
+ <div
+ aria-hidden="true"
+ class={cn('pointer-events-none absolute inset-x-0 bottom-0', props.class)}
+ style={{ top: `${HEADER_HEIGHT}px`, transform: 'translateZ(0)' }}
+ >
+ <GanttCalendarClip
+ width={gantt.width()}
+ inset={
+ gantt.labelWidth() ||
+ (gantt.sidebar.open() ? gantt.sidebar.width() : 0)
+ }
+ closingInset={
+ gantt.labelWidth() === 0 && !gantt.sidebar.open()
+ ? gantt.sidebar.width()
+ : undefined
+ }
+ >
+ {props.children}
+ </GanttCalendarClip>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/gantt/gantt-context.ts b/apps/web/src/components/gantt/gantt-context.ts
new file mode 100644
index 0000000000..895a23bf9d
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-context.ts
@@ -0,0 +1,54 @@
+import { type Accessor, createContext, useContext } from 'solid-js';
+import type { GanttRange, GanttScale } from './gantt-date';
+import type { GanttGuide } from './gantt-interaction';
+
+export const HEADER_HEIGHT = 48;
+export type GanttContext = {
+ today: Accessor<number>;
+ range: Accessor<GanttRange>;
+ scale: Accessor<GanttScale>;
+ setScale: (scale: GanttScale) => void;
+ pixelsPerDay: Accessor<number>;
+ zoomAt: (clientX: number, wheelDelta: number) => void;
+ scrollZooming: Accessor<boolean>;
+ markScrollZoom: () => void;
+ gridVisible: Accessor<boolean>;
+ setGridVisible: (visible: boolean) => void;
+ gridScale: Accessor<GanttScale>;
+ setGridScale: (scale: GanttScale) => void;
+ gridStyle: Accessor<'solid' | 'dashed'>;
+ setGridStyle: (style: 'solid' | 'dashed') => void;
+ labelWidth: Accessor<number>;
+ rowHeight: Accessor<number>;
+ sidebar: {
+ open: Accessor<boolean>;
+ width: Accessor<number>;
+ setOpen: (open: boolean) => void;
+ setTrigger: (element: HTMLButtonElement | undefined) => void;
+ };
+ width: Accessor<number>;
+ visibleRange: Accessor<GanttRange>;
+ viewport: Accessor<HTMLDivElement | undefined>;
+ setViewport: (element: HTMLDivElement | undefined) => void;
+ updateViewport: () => void;
+ panBy: (deltaX: number, deltaY: number) => void;
+ scrollToToday: (behavior?: ScrollBehavior) => void;
+ guide: Accessor<GanttGuide | undefined>;
+ setGuide: (guide: GanttGuide | undefined) => void;
+ editing: Accessor<boolean>;
+ setEditing: (editing: boolean) => void;
+ pointToDay: (
+ clientX: number,
+ exclude?: HTMLElement,
+ snap?: boolean
+ ) => GanttGuide | undefined;
+};
+
+export const GanttContextProvider = createContext<GanttContext>();
+
+/** Presentation capabilities for components composed inside Gantt.Root. */
+export function useGantt(): GanttContext {
+ const context = useContext(GanttContextProvider);
+ if (!context) throw new Error('Gantt components require Gantt.Root');
+ return context;
+}
diff --git a/apps/web/src/components/gantt/gantt-create-area.tsx b/apps/web/src/components/gantt/gantt-create-area.tsx
new file mode 100644
index 0000000000..931072c1e2
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-create-area.tsx
@@ -0,0 +1,63 @@
+import { Show } from 'solid-js';
+import {
+ createGanttCreation,
+ type GanttCreation,
+} from './create-gantt-creation';
+import { GanttCalendarClip } from './gantt-clip';
+import { useGantt } from './gantt-context';
+import { formatGanttDay, type GanttDate } from './gantt-date';
+import { ganttCreationRange } from './gantt-interaction';
+
+/** Available space opens a host-owned composer without writing an entity. */
+export function GanttCreateArea(props: {
+ onCreate?: (dates: GanttCreation) => void;
+ minDate?: GanttDate;
+}) {
+ const gantt = useGantt();
+ const { draft } = createGanttCreation({
+ viewport: gantt.viewport,
+ editing: gantt.editing,
+ setEditing: gantt.setEditing,
+ clearGuide: () => gantt.setGuide(undefined),
+ labelWidth: gantt.labelWidth,
+ pointToDay: gantt.pointToDay,
+ onCreate: () => props.onCreate,
+ minDate: () => props.minDate,
+ });
+
+ return (
+ <Show when={draft()}>
+ {(selection) => {
+ const range = () =>
+ ganttCreationRange(selection().first, selection().last);
+ return (
+ <div
+ aria-hidden="true"
+ class="pointer-events-none absolute z-10 h-7"
+ style={{
+ top: `${selection().top}px`,
+ left: `${gantt.labelWidth() + (range().start - gantt.range().start) * gantt.pixelsPerDay()}px`,
+ width: `${(range().end - range().start) * gantt.pixelsPerDay()}px`,
+ transform: 'translateZ(0)',
+ }}
+ >
+ <GanttCalendarClip
+ width={(range().end - range().start) * gantt.pixelsPerDay()}
+ >
+ <div class="size-full rounded-md border border-ink-muted bg-[color-mix(in_oklch,var(--color-ink)_18%,var(--color-panel))]" />
+ </GanttCalendarClip>
+ <span
+ class="absolute right-0 top-full mt-1 overflow-hidden rounded border border-edge-muted bg-tooltip px-2 py-1 text-xs text-ink whitespace-nowrap"
+ style={{
+ 'max-width': `${Math.max(0, (gantt.visibleRange().end - gantt.visibleRange().start) * gantt.pixelsPerDay() - 16)}px`,
+ translate: `clamp(calc(${(gantt.visibleRange().start - range().end) * gantt.pixelsPerDay() + 8}px + 100%), 0px, ${(gantt.visibleRange().end - range().end) * gantt.pixelsPerDay() - 8}px) 0`,
+ }}
+ >
+ Due {formatGanttDay(range().end - 1)}
+ </span>
+ </div>
+ );
+ }}
+ </Show>
+ );
+}
diff --git a/apps/web/src/components/gantt/gantt-date.test.ts b/apps/web/src/components/gantt/gantt-date.test.ts
new file mode 100644
index 0000000000..0781657bf2
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-date.test.ts
@@ -0,0 +1,190 @@
+import { describe, expect, it } from 'vitest';
+import {
+ deriveGanttRange,
+ ganttBarGeometry,
+ ganttDateFromDay,
+ ganttTicks,
+ normalizeGanttRange,
+ toGanttDay,
+} from './gantt-date';
+
+const day = (value: string) => toGanttDay(value)!;
+const range = { start: day('2026-03-01'), end: day('2026-04-01') };
+
+describe('Gantt calendar geometry', () => {
+ it('preserves date-only values and rejects calendar overflow instead of normalizing it', () => {
+ expect(day('2024-02-29') + 1).toBe(day('2024-03-01'));
+ for (const value of [
+ '2026-02-29',
+ '2026-02-30T12:00:00Z',
+ '2026-13-01',
+ '2026-00-01',
+ '0',
+ 'invalid',
+ ]) {
+ expect(toGanttDay(value)).toBeUndefined();
+ }
+ expect(toGanttDay(new Date(Number.NaN))).toBeUndefined();
+ expect(day('0001-01-01')).toBeLessThan(day('0100-01-01'));
+ });
+
+ it('writes the same local calendar day across DST changes and early years', () => {
+ for (const value of ['2026-03-08', '2026-11-01', '0001-01-01']) {
+ const ordinal = day(value);
+ expect(toGanttDay(ganttDateFromDay(ordinal))).toBe(ordinal);
+ expect(ganttDateFromDay(ordinal).getHours()).toBe(0);
+ }
+ });
+
+ it('uses calendar-day distances across local daylight-saving transitions', () => {
+ const before = new Date(2026, 2, 7, 12);
+ const after = new Date(2026, 2, 9, 12);
+ expect(toGanttDay(after)! - toGanttDay(before)!).toBe(2);
+ expect(toGanttDay(before.toISOString())).toBe(toGanttDay(before));
+ expect(
+ toGanttDay(new Date(2026, 10, 2))! - toGanttDay(new Date(2026, 9, 31))!
+ ).toBe(2);
+ });
+
+ it('includes the deadline day and keeps same-day intervals visible', () => {
+ expect(
+ ganttBarGeometry({ start: '2026-03-08', end: '2026-03-08' }, range, 40)
+ ).toMatchObject({
+ kind: 'scheduled',
+ left: 280,
+ width: 40,
+ });
+ expect(
+ ganttBarGeometry({ start: '2026-03-07', end: '2026-03-09' }, range, 20)
+ ).toMatchObject({
+ kind: 'scheduled',
+ width: 60,
+ });
+ });
+
+ it('distinguishes open-ended intervals from invalid and reversed deadlines', () => {
+ expect(ganttBarGeometry({ start: '2026-03-08' }, range, 20)).toMatchObject({
+ kind: 'open-ended',
+ width: 480,
+ end: undefined,
+ });
+ expect(
+ ganttBarGeometry({ start: '2026-03-08', end: 'invalid' }, range, 20)
+ ).toEqual({ kind: 'invalid-end' });
+ expect(
+ ganttBarGeometry({ start: '2026-03-08', end: '2026-03-07' }, range, 20)
+ ).toEqual({ kind: 'reversed' });
+ expect(ganttBarGeometry({ start: null }, range, 20)).toEqual({
+ kind: 'missing-start',
+ });
+ expect(ganttBarGeometry({ start: 'invalid' }, range, 20)).toEqual({
+ kind: 'invalid-start',
+ });
+ });
+
+ it('clips both range boundaries without drawing intervals outside the chart', () => {
+ expect(
+ ganttBarGeometry({ start: '2026-02-01', end: '2026-04-15' }, range, 6)
+ ).toMatchObject({
+ kind: 'scheduled',
+ left: 0,
+ width: 186,
+ });
+ expect(
+ ganttBarGeometry({ start: '2026-01-01', end: '2026-02-28' }, range, 6)
+ ).toEqual({ kind: 'outside' });
+ expect(ganttBarGeometry({ start: '2026-04-01' }, range, 6)).toEqual({
+ kind: 'outside',
+ });
+ });
+
+ it('includes today but excludes a reversed deadline from derived bounds', () => {
+ expect(
+ deriveGanttRange(
+ [
+ { start: '2026-03-01', end: '2000-01-01' },
+ { start: '2026-03-10', end: '2026-04-15' },
+ { start: 'invalid', end: 'invalid' },
+ ],
+ '2026-03-08'
+ )
+ ).toEqual({ start: day('2026-02-22'), end: day('2026-04-30') });
+ const empty = deriveGanttRange([], '2026-03-08');
+ expect(empty.end - empty.start).toBe(22);
+ expect(normalizeGanttRange({ start: 12.5, end: 8 })).toEqual({
+ start: 12,
+ end: 13,
+ });
+ const invalid = normalizeGanttRange({ start: Number.NaN, end: Infinity });
+ expect(Number.isFinite(invalid.start)).toBe(true);
+ expect(invalid.end).toBeGreaterThan(invalid.start);
+ });
+
+ it('uses real calendar months across leap years and clips partial months', () => {
+ const months = ganttTicks(
+ { start: day('2024-02-10'), end: day('2024-04-05') },
+ 'month'
+ );
+ expect(months.map((tick) => tick.end - tick.start)).toEqual([20, 31, 4]);
+ const weeks = ganttTicks(range, 'week', {
+ start: day('2026-03-11'),
+ end: day('2026-03-15'),
+ });
+ expect(weeks).toHaveLength(1);
+ expect(weeks[0].start).toBe(day('2026-03-09'));
+ expect(weeks[0].end).toBe(day('2026-03-17'));
+ expect(weeks[0].label).toBe('9');
+ });
+
+ it.each([
+ ['2023-02-01', '2023-03-01', [7, 7, 7, 7], ['1', '8', '15', '22']],
+ ['2024-02-01', '2024-03-01', [7, 8, 7, 7], ['1', '8', '16', '23']],
+ ['2026-04-01', '2026-05-01', [8, 7, 8, 7], ['1', '9', '16', '24']],
+ ['2026-03-01', '2026-04-01', [8, 8, 7, 8], ['1', '9', '17', '24']],
+ ] as const)(
+ 'balances week-scale sections in %s without changing calendar dates',
+ (start, end, lengths, labels) => {
+ const ticks = ganttTicks({ start: day(start), end: day(end) }, 'week');
+ expect(ticks.map((tick) => tick.end - tick.start)).toEqual(lengths);
+ expect(ticks.map((tick) => tick.label)).toEqual(labels);
+ expect(ticks.at(-1)?.end).toBe(day(end));
+ }
+ );
+
+ it('keeps month-aligned sections stable across clipped ranges and year boundaries', () => {
+ const bounds = { start: day('2026-12-30'), end: day('2027-01-10') };
+ expect(
+ ganttTicks(bounds, 'week', {
+ start: day('2026-12-31'),
+ end: day('2027-01-05'),
+ })
+ ).toEqual([
+ { start: day('2026-12-30'), end: day('2027-01-01'), label: '30' },
+ { start: day('2027-01-01'), end: day('2027-01-09'), label: '1' },
+ ]);
+ expect(
+ ganttTicks(bounds, 'week', { start: day('2027-01-09'), end: bounds.end })
+ ).toEqual([{ start: day('2027-01-09'), end: bounds.end, label: '9' }]);
+ });
+
+ it('limits month labels to the visible window across December and January', () => {
+ const bounds = { start: day('2000-01-01'), end: day('2050-01-01') };
+ const visible = { start: day('2026-12-20'), end: day('2027-02-10') };
+ const months = ganttTicks(bounds, 'month', visible);
+ expect(months.map((tick) => tick.label)).toEqual([
+ 'December',
+ 'January',
+ 'February',
+ ]);
+ });
+ it('bounds tick generation to the visible window and guards enormous inputs', () => {
+ const long = { start: day('2000-01-01'), end: day('2050-01-01') };
+ const visible = { start: day('2026-03-01'), end: day('2026-03-11') };
+ expect(ganttTicks(long, 'day', visible)).toHaveLength(10);
+ expect(ganttTicks(long, 'day')).toHaveLength(1_000);
+ expect(ganttTicks(long, 'week')).toHaveLength(1_000);
+ expect(
+ ganttTicks(range, 'week', { start: range.end, end: range.end + 7 })
+ ).toEqual([]);
+ });
+});
diff --git a/apps/web/src/components/gantt/gantt-date.ts b/apps/web/src/components/gantt/gantt-date.ts
new file mode 100644
index 0000000000..94d95f051c
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-date.ts
@@ -0,0 +1,247 @@
+import { match } from 'ts-pattern';
+
+export type GanttDate = string | Date | null | undefined;
+export type GanttScale = 'day' | 'week' | 'month';
+export type GanttInterval = { start: GanttDate; end?: GanttDate };
+/** Calendar-day ordinals, with an exclusive end. */
+export type GanttRange = { start: number; end: number };
+export type GanttTick = { start: number; end: number; label: string };
+
+const DAY_MS = 86_400_000;
+
+function ordinal(year: number, month: number, day: number) {
+ const date = new Date(0);
+ date.setUTCFullYear(year, month, day);
+ date.setUTCHours(0, 0, 0, 0);
+ return date.getTime() / DAY_MS;
+}
+
+/** Date-only values keep their stated day; timestamps use the viewer's local day. */
+export function toGanttDay(value: GanttDate): number | undefined {
+ if (value == null || value === '') return;
+
+ if (typeof value === 'string') {
+ const parts = /^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(value);
+ if (!parts) return;
+ const year = Number(parts[1]);
+ const month = Number(parts[2]) - 1;
+ const day = Number(parts[3]);
+ const result = ordinal(year, month, day);
+ const date = new Date(result * DAY_MS);
+ if (
+ date.getUTCFullYear() !== year ||
+ date.getUTCMonth() !== month ||
+ date.getUTCDate() !== day
+ )
+ return;
+ if (value.length === 10) return result;
+ }
+
+ const date = value instanceof Date ? value : new Date(value);
+ if (!Number.isFinite(date.getTime())) return;
+ return ordinal(date.getFullYear(), date.getMonth(), date.getDate());
+}
+
+/** Property writes use local midnight, matching the existing date-picker calendar day. */
+export function ganttDateFromDay(day: number): Date {
+ const utc = new Date(day * DAY_MS);
+ const date = new Date(0);
+ date.setFullYear(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate());
+ date.setHours(0, 0, 0, 0);
+ return date;
+}
+export function formatGanttDay(day: number, includeYear = true): string {
+ return new Intl.DateTimeFormat('en-US', {
+ month: 'short',
+ day: 'numeric',
+ ...(includeYear ? { year: 'numeric' as const } : {}),
+ timeZone: 'UTC',
+ }).format(new Date(day * DAY_MS));
+}
+
+export function formatGanttMonth(
+ day: number,
+ format: 'long' | 'short' = 'long'
+): string {
+ return new Intl.DateTimeFormat('en-US', {
+ month: format,
+ timeZone: 'UTC',
+ }).format(new Date(day * DAY_MS));
+}
+
+export function ganttPixelsPerDay(scale: GanttScale): number {
+ return match(scale)
+ .with('day', () => 40)
+ .with('week', () => 20)
+ .with('month', () => 6)
+ .exhaustive();
+}
+
+export function deriveGanttRange(
+ intervals: readonly GanttInterval[],
+ today: GanttDate = new Date()
+): GanttRange {
+ const current = toGanttDay(today) ?? toGanttDay(new Date())!;
+ let start = current;
+ let end = current;
+ for (const interval of intervals) {
+ const first = toGanttDay(interval.start);
+ const last = toGanttDay(interval.end);
+ if (first !== undefined) {
+ start = Math.min(start, first);
+ end = Math.max(end, first);
+ }
+ if (last !== undefined && (first === undefined || last >= first)) {
+ start = Math.min(start, last);
+ end = Math.max(end, last);
+ }
+ }
+ return { start: start - 7, end: end + 15 };
+}
+
+export function normalizeGanttRange(range: GanttRange): GanttRange {
+ if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) {
+ return deriveGanttRange([]);
+ }
+ const start = Math.floor(range.start);
+ return { start, end: Math.max(start + 1, Math.ceil(range.end)) };
+}
+
+export type GanttBarGeometry =
+ | {
+ kind:
+ | 'missing-start'
+ | 'invalid-start'
+ | 'invalid-end'
+ | 'reversed'
+ | 'outside';
+ }
+ | {
+ kind: 'scheduled' | 'open-ended';
+ left: number;
+ width: number;
+ start: number;
+ end?: number;
+ };
+
+/** Inclusive deadlines occupy their final day, including same-day intervals. */
+export function ganttBarGeometry(
+ interval: GanttInterval,
+ range: GanttRange,
+ pixelsPerDay: number
+): GanttBarGeometry {
+ const start = toGanttDay(interval.start);
+ if (start === undefined) {
+ return {
+ kind:
+ interval.start == null || interval.start === ''
+ ? 'missing-start'
+ : 'invalid-start',
+ };
+ }
+ const missingEnd = interval.end == null || interval.end === '';
+ const end = toGanttDay(interval.end);
+ if (!missingEnd && end === undefined) return { kind: 'invalid-end' };
+ if (end !== undefined && end < start) return { kind: 'reversed' };
+
+ const clippedStart = Math.max(start, range.start);
+ const clippedEnd = Math.min(
+ end === undefined ? range.end : end + 1,
+ range.end
+ );
+ if (clippedEnd <= clippedStart) return { kind: 'outside' };
+ return {
+ kind: end === undefined ? 'open-ended' : 'scheduled',
+ left: (clippedStart - range.start) * pixelsPerDay,
+ width: (clippedEnd - clippedStart) * pixelsPerDay,
+ start,
+ end,
+ };
+}
+
+function monthStart(day: number): number {
+ const date = new Date(day * DAY_MS);
+ return ordinal(date.getUTCFullYear(), date.getUTCMonth(), 1);
+}
+
+function nextMonth(day: number): number {
+ const date = new Date(day * DAY_MS);
+ return ordinal(date.getUTCFullYear(), date.getUTCMonth() + 1, 1);
+}
+
+/** Generate only visible ticks; long schedules do not create one node per calendar day. */
+export function ganttTicks(
+ range: GanttRange,
+ scale: GanttScale,
+ visible: GanttRange = range
+): GanttTick[] {
+ const first = Math.max(range.start, Math.floor(visible.start));
+ const last = Math.min(range.end, Math.ceil(visible.end));
+ if (last <= first) return [];
+
+ // Roughly weekly marks divide each real month evenly instead of drifting with weekdays.
+ if (scale === 'week') {
+ return ganttTicks(range, 'month', visible)
+ .flatMap((month) => {
+ const start = monthStart(month.start);
+ const length = nextMonth(start) - start;
+ return [0, 1, 2, 3].flatMap((section) => {
+ const sectionStart = start + Math.round((length * section) / 4);
+ const sectionEnd = start + Math.round((length * (section + 1)) / 4);
+ if (sectionEnd <= first || sectionStart >= last) return [];
+ const tickStart = Math.max(sectionStart, range.start);
+ return [
+ {
+ start: tickStart,
+ end: Math.min(sectionEnd, range.end),
+ label: String(new Date(tickStart * DAY_MS).getUTCDate()),
+ },
+ ];
+ });
+ })
+ .slice(0, 1_000);
+ }
+
+ let cursor = scale === 'month' ? monthStart(first) : first;
+ const ticks: GanttTick[] = [];
+ // A malformed or enormous visible range must not block the main thread.
+ while (cursor < last && ticks.length < 1_000) {
+ const next = scale === 'month' ? nextMonth(cursor) : cursor + 1;
+ const label =
+ scale === 'month'
+ ? formatGanttMonth(cursor)
+ : String(new Date(cursor * DAY_MS).getUTCDate());
+ ticks.push({
+ start: Math.max(cursor, range.start),
+ end: Math.min(next, range.end),
+ label,
+ });
+ cursor = next;
+ }
+ return ticks;
+}
+
+/** Stable calendar-year bounds keep sticky markers anchored while visible months change. */
+export function ganttYearTicks(
+ range: GanttRange,
+ visible: GanttRange = range
+): GanttTick[] {
+ const first = Math.max(range.start, Math.floor(visible.start));
+ const last = Math.min(range.end, Math.ceil(visible.end));
+ if (last <= first) return [];
+
+ const years: GanttTick[] = [];
+ let year = new Date(first * DAY_MS).getUTCFullYear();
+ let cursor = ordinal(year, 0, 1);
+ while (cursor < last && years.length < 1_000) {
+ const next = ordinal(year + 1, 0, 1);
+ years.push({
+ start: Math.max(cursor, range.start),
+ end: Math.min(next, range.end),
+ label: String(year),
+ });
+ year += 1;
+ cursor = next;
+ }
+ return years;
+}
diff --git a/apps/web/src/components/gantt/gantt-drop-preview.tsx b/apps/web/src/components/gantt/gantt-drop-preview.tsx
new file mode 100644
index 0000000000..1e6aa41900
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-drop-preview.tsx
@@ -0,0 +1,28 @@
+import { GanttBar } from './gantt-bar';
+import type { GanttDate } from './gantt-date';
+import { GanttLabel } from './gantt-sidebar';
+
+/** A non-interactive, date-preserving outline at the destination's sorted row. */
+export function GanttDropPreview(props: {
+ start: GanttDate;
+ end?: GanttDate;
+ title: string;
+}) {
+ return (
+ <>
+ <GanttLabel>
+ <div class="flex h-7 w-full min-w-0 items-center rounded-md border border-dashed border-ink-muted px-2 text-xs text-ink-muted">
+ <span class="truncate">{props.title}</span>
+ </div>
+ </GanttLabel>
+ <GanttBar
+ start={props.start}
+ end={props.end}
+ title={props.title}
+ class="border-dashed opacity-50 shadow-none"
+ >
+ <span class="min-w-0 truncate">{props.title}</span>
+ </GanttBar>
+ </>
+ );
+}
diff --git a/apps/web/src/components/gantt/gantt-group-drag.test.ts b/apps/web/src/components/gantt/gantt-group-drag.test.ts
new file mode 100644
index 0000000000..ababf69f96
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-group-drag.test.ts
@@ -0,0 +1,253 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { createComponent, createSignal } from 'solid-js';
+import { insert } from 'solid-js/web';
+import { afterEach, expect, it, vi } from 'vitest';
+import { Gantt } from './gantt';
+import { useGantt } from './gantt-context';
+import type { GanttGroupMove } from './gantt-group-drag';
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+function fixture(withPreview = false) {
+ vi.stubGlobal('requestAnimationFrame', () => 1);
+ vi.stubGlobal('cancelAnimationFrame', () => {});
+ const [allowed, setAllowed] = createSignal(true);
+ const [scope, setScope] = createSignal('status');
+ const move = vi.fn(async (_move: GanttGroupMove) => {});
+ const open = vi.fn();
+ const [rows, setRows] = createSignal([{ id: 'a:one', name: 'Original row' }]);
+ const renderNormal = vi.fn((row: { id: string; name: string }) => {
+ const element = document.createElement('div');
+ element.dataset.stableRow = row.id;
+ element.textContent = row.name;
+ return element;
+ });
+ const viewport = document.createElement('div');
+ viewport.getBoundingClientRect = () => new DOMRect(0, 0, 800, 600);
+ render(() =>
+ createComponent(Gantt.Root, {
+ range: { start: 0, end: 100 },
+ get children() {
+ return createComponent(Gantt.GroupDrag, {
+ get scope() {
+ return scope();
+ },
+ canDrag: () => allowed(),
+ canDrop: () => allowed(),
+ onMove: move,
+ getPlacement: () => ({ index: 0 }),
+ get children() {
+ return createComponent(() => {
+ const gantt = useGantt();
+ gantt.setViewport(viewport);
+ const label = document.createElement('div');
+ label.dataset.ganttLabel = '';
+ const button = document.createElement('button');
+ button.textContent = 'Source';
+ button.onclick = open;
+ button.getBoundingClientRect = () => new DOMRect(8, 86, 264, 28);
+ label.append(button);
+ const body = document.createElement('div');
+ body.dataset.ganttBarBody = '';
+ body.getBoundingClientRect = () => new DOMRect(150, 86, 1000, 28);
+ const bar = document.createElement('button');
+ const text = document.createElement('span');
+ text.dataset.ganttBarLabel = '';
+ text.style.position = 'sticky';
+ text.textContent = 'Bar';
+ bar.append(text);
+ bar.onclick = open;
+ const action = document.createElement('button');
+ action.textContent = 'Action';
+ body.append(bar, action);
+ insert(
+ viewport,
+ createComponent(Gantt.DragItem, {
+ id: 'one',
+ key: 'a:one',
+ groupId: 'a',
+ label: 'Source',
+ get children() {
+ return createComponent(Gantt.Row, {
+ children: [label, body],
+ });
+ },
+ })
+ );
+ insert(
+ viewport,
+ createComponent(Gantt.Row, {
+ get children() {
+ return createComponent(Gantt.GroupDrop, {
+ id: 'b',
+ groupId: 'b',
+ });
+ },
+ })
+ );
+ if (withPreview)
+ insert(
+ viewport,
+ createComponent(Gantt.Rows<{ id: string; name: string }>, {
+ get items() {
+ return rows();
+ },
+ getKey: (row) => row.id,
+ children: renderNormal,
+ renderDropPreview: () => 'Destination ghost',
+ })
+ );
+ return viewport;
+ }, {});
+ },
+ });
+ },
+ })
+ );
+ viewport.querySelector<HTMLElement>(
+ '[data-gantt-group-drop]'
+ )!.getBoundingClientRect = () => new DOMRect(0, 200, 800, 40);
+ const press = (source = 'Source') =>
+ fireEvent.mouseDown(screen.getByRole('button', { name: source }), {
+ clientX: 300,
+ clientY: 100,
+ button: 0,
+ });
+ const hover = (y = 220) =>
+ fireEvent.mouseMove(document, { clientX: 300, clientY: y });
+ const release = () =>
+ fireEvent.mouseUp(document, { clientX: 300, clientY: 220 });
+ return {
+ move,
+ open,
+ press,
+ hover,
+ release,
+ setAllowed,
+ setScope,
+ viewport,
+ renderNormal,
+ setRows,
+ };
+}
+
+it.each(['Source', 'Bar'])(
+ 'moves from %s only after the drag threshold and suppresses opening',
+ async (source) => {
+ const chart = fixture();
+ chart.press(source);
+ chart.hover(105);
+ chart.release();
+ expect(chart.move).not.toHaveBeenCalled();
+ chart.press(source);
+ chart.hover();
+ chart.release();
+ fireEvent.click(screen.getByRole('button', { name: source }));
+ await waitFor(() => expect(chart.move).toHaveBeenCalledOnce());
+ expect(chart.move).toHaveBeenCalledWith({
+ id: 'one',
+ fromGroup: 'a',
+ toGroup: 'b',
+ });
+ expect(chart.open).not.toHaveBeenCalled();
+ }
+);
+it.each(['escape', 'permission', 'scope', 'outside'])(
+ 'rejects a drop after %s changes during the drag',
+ (change) => {
+ const chart = fixture();
+ chart.press();
+ chart.hover();
+ if (change === 'escape') fireEvent.keyDown(document, { key: 'Escape' });
+ if (change === 'permission') chart.setAllowed(false);
+ if (change === 'scope') chart.setScope('priority');
+ if (change === 'outside') chart.hover(700);
+ chart.release();
+ expect(chart.move).not.toHaveBeenCalled();
+ }
+);
+
+it('does not start group dragging from secondary action buttons', () => {
+ const chart = fixture();
+ chart.press('Action');
+ chart.hover();
+ chart.release();
+ expect(chart.move).not.toHaveBeenCalled();
+});
+
+it('blocks a second drag while saving and reports failure before allowing a retry', async () => {
+ const chart = fixture();
+ let reject!: (error: Error) => void;
+ chart.move.mockImplementationOnce(
+ () =>
+ new Promise<void>((_resolve, fail) => {
+ reject = fail;
+ })
+ );
+ chart.press();
+ chart.hover();
+ chart.release();
+ chart.press('Bar');
+ chart.hover();
+ chart.release();
+ expect(chart.move).toHaveBeenCalledOnce();
+ reject(new Error('offline'));
+ await waitFor(() =>
+ expect(screen.getByRole('alert').textContent).toBe(
+ 'Could not move item. Try again.'
+ )
+ );
+ chart.press();
+ chart.hover();
+ chart.release();
+ await waitFor(() => expect(chart.move).toHaveBeenCalledTimes(2));
+});
+
+it('snapshots the visible bar and keeps its clone inert while reserving a destination row', async () => {
+ const chart = fixture(true);
+ const original = screen.getByRole('button', { name: 'Bar' });
+ chart.press('Bar');
+ chart.hover();
+ const snapshot = document.querySelector<HTMLElement>(
+ '[data-gantt-drag-preview]'
+ )!;
+ expect(snapshot.style.width).toBe('540px');
+ expect(snapshot.inert).toBe(true);
+ expect(snapshot.getAttribute('aria-hidden')).toBe('true');
+ expect(
+ snapshot.querySelector<HTMLElement>('[data-gantt-bar-label]')!.style
+ .position
+ ).toBe('static');
+ const ghost = chart.viewport.querySelector<HTMLElement>(
+ '[data-gantt-drop-preview]'
+ )!;
+ expect(ghost.textContent).toBe('Destination ghost');
+ chart.hover();
+ expect(chart.viewport.querySelector('[data-gantt-drop-preview]')).toBe(ghost);
+ expect(chart.renderNormal).toHaveBeenCalledOnce();
+ const retained = chart.viewport.querySelector('[data-stable-row]');
+ chart.setRows([{ id: 'a:one', name: 'Replacement' }]);
+ expect(chart.viewport.querySelector('[data-stable-row]')).toBe(retained);
+ chart.setRows([]);
+ expect(chart.viewport.querySelector('[data-stable-row]')).toBe(retained);
+ chart.setRows([{ id: 'a:one', name: 'Replacement' }]);
+ expect(screen.getByRole('button', { name: 'Bar' })).toBe(original);
+ fireEvent.keyDown(document, { key: 'Escape' });
+ expect(chart.viewport.querySelector('[data-gantt-drop-preview]')).toBeNull();
+ expect(document.querySelector('[data-gantt-drag-preview]')).toBeNull();
+ expect(chart.viewport.querySelector('[data-stable-row]')?.textContent).toBe(
+ 'Replacement'
+ );
+ chart.release();
+ expect(chart.move).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/components/gantt/gantt-group-drag.tsx b/apps/web/src/components/gantt/gantt-group-drag.tsx
new file mode 100644
index 0000000000..098c8b2ba3
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-group-drag.tsx
@@ -0,0 +1,332 @@
+import {
+ type CollisionDetector,
+ createDraggable,
+ createDroppable,
+ DragDropProvider,
+ DragOverlay,
+} from '@thisbeyond/solid-dnd';
+import { cn, Layer } from '@ui';
+import {
+ createContext,
+ createSignal,
+ onCleanup,
+ type ParentProps,
+ Show,
+ useContext,
+} from 'solid-js';
+import { cloneDragPreview } from '../drag-drop/drag-preview';
+import { DragSessionSensors } from '../drag-drop/drag-session-sensors';
+import { HEADER_HEIGHT, useGantt } from './gantt-context';
+import type { GanttGroupPlacement } from './gantt-group-placement';
+
+export type GanttGroupMove = {
+ id: string;
+ fromGroup: string;
+ toGroup: string;
+};
+
+type DragItem = {
+ id: string;
+ key: string | number;
+ groupId: string;
+ label: string;
+};
+const GroupDragContext = createContext<{
+ active: () => DragItem | undefined;
+ target: () => string | undefined;
+ canDrag: (id: string) => boolean;
+ start: (event: MouseEvent, element: HTMLElement) => void;
+ move: () => GanttGroupMove | undefined;
+ placement: () => GanttGroupPlacement | undefined;
+ suppressClick: () => boolean;
+}>();
+
+export const useGanttGroupDrag = () => useContext(GroupDragContext);
+
+/** Consumers own group semantics and persistence; the chart owns only the drag gesture. */
+export function GanttGroupDrag(
+ props: ParentProps<{
+ scope: string;
+ canDrag: (id: string) => boolean;
+ canDrop: (move: GanttGroupMove) => boolean;
+ onMove: (move: GanttGroupMove) => Promise<void>;
+ getPlacement?: (move: GanttGroupMove) => GanttGroupPlacement | undefined;
+ }>
+) {
+ const gantt = useGantt();
+ const [active, setActive] = createSignal<DragItem>();
+ const [target, setTarget] = createSignal<string>();
+ const [pending, setPending] = createSignal<string[]>([]);
+ const [error, setError] = createSignal<string>();
+ const [preview, setPreview] = createSignal<{
+ element: HTMLElement;
+ rect: DOMRectReadOnly;
+ }>();
+ let sourceElement: HTMLElement | undefined;
+ const [origin, setOrigin] = createSignal<{ x: number; y: number }>();
+ let scope: string | undefined;
+ let cancelled = false;
+ let suppressClick = false;
+ let clickTimeout: ReturnType<typeof setTimeout> | undefined;
+ let alive = true;
+ onCleanup(() => {
+ alive = false;
+ clearTimeout(clickTimeout);
+ if (active()) gantt.setEditing(false);
+ });
+
+ const canDrag = (id: string) => props.canDrag(id) && !pending().includes(id);
+ const request = (): GanttGroupMove | undefined => {
+ const item = active();
+ const group = target();
+ if (!item || group === undefined || scope !== props.scope) return;
+ if (item.groupId === group) return;
+ const move = { id: item.id, fromGroup: item.groupId, toGroup: group };
+ return canDrag(item.id) && props.canDrop(move) ? move : undefined;
+ };
+ const collisionDetector: CollisionDetector = (draggable, droppables) => {
+ const reject = () => {
+ setTarget(undefined);
+ return null;
+ };
+ const item = active();
+ const viewport = gantt.viewport();
+ const point = origin();
+ if (!item || !point || !viewport || cancelled || scope !== props.scope)
+ return reject();
+ const x = point.x + draggable.transform.x;
+ const y = point.y + draggable.transform.y;
+ const bounds = viewport.getBoundingClientRect();
+ if (
+ x < bounds.left ||
+ x > bounds.right ||
+ y < bounds.top + HEADER_HEIGHT ||
+ y > bounds.bottom
+ )
+ return reject();
+ const destination = droppables.find((droppable) => {
+ const box = droppable.node.getBoundingClientRect();
+ const group = droppable.data.groupId;
+ return (
+ typeof group === 'string' &&
+ group !== item.groupId &&
+ y >= box.top &&
+ y < box.bottom &&
+ canDrag(item.id) &&
+ props.canDrop({ id: item.id, fromGroup: item.groupId, toGroup: group })
+ );
+ });
+ if (!destination) return reject();
+ setTarget(destination.data.groupId as string);
+ return destination;
+ };
+ const saveMove = async (move: GanttGroupMove) => {
+ const attemptScope = props.scope;
+ setPending((ids) => [...ids, move.id]);
+ try {
+ await props.onMove(move);
+ } catch {
+ if (alive && attemptScope === props.scope) {
+ setError('Could not move item. Try again.');
+ }
+ } finally {
+ if (alive) setPending((ids) => ids.filter((id) => id !== move.id));
+ }
+ };
+ const finish = () => {
+ const move = request();
+ if (!cancelled && move && canDrag(move.id) && props.canDrop(move)) {
+ void saveMove(move);
+ }
+ setActive(undefined);
+ setTarget(undefined);
+ setPreview(undefined);
+ gantt.setEditing(false);
+ clickTimeout = setTimeout(() => {
+ suppressClick = false;
+ }, 0);
+ };
+
+ return (
+ <DragDropProvider
+ collisionDetector={collisionDetector}
+ onDragStart={({ draggable }) => {
+ scope = props.scope;
+ setActive(draggable.data.item as DragItem);
+ if (sourceElement) {
+ const rect = sourceElement.getBoundingClientRect();
+ const viewport = gantt.viewport()?.getBoundingClientRect();
+ const bar = sourceElement.hasAttribute('data-gantt-bar-body');
+ const inset =
+ gantt.labelWidth() ||
+ (gantt.sidebar.open() ? gantt.sidebar.width() : 0);
+ const left =
+ bar && viewport
+ ? Math.max(rect.left, viewport.left + inset)
+ : rect.left;
+ const right = viewport
+ ? Math.min(rect.right, viewport.right)
+ : rect.right;
+ const copy = cloneDragPreview(
+ sourceElement,
+ 'data-gantt-drag-preview'
+ );
+ const width = Math.max(1, right - left);
+ copy.style.width = `${width}px`;
+ const label = copy.querySelector<HTMLElement>(
+ '[data-gantt-bar-label]'
+ );
+ if (label) {
+ label.style.position = 'static';
+ label.style.left = 'auto';
+ label.style.width = '100%';
+ }
+ setPreview({
+ element: copy,
+ rect: new DOMRect(left, rect.top, width, rect.height),
+ });
+ }
+ suppressClick = true;
+ setError(undefined);
+ gantt.setGuide(undefined);
+ gantt.setEditing(true);
+ }}
+ onDragEnd={finish}
+ >
+ <DragSessionSensors
+ getViewport={gantt.viewport}
+ axis="both"
+ activationDistance={10}
+ onCancel={() => {
+ cancelled = true;
+ }}
+ />
+ <GroupDragContext.Provider
+ value={{
+ active,
+ target: () => request()?.toGroup,
+ canDrag,
+ suppressClick: () => suppressClick,
+ move: request,
+ placement: () => {
+ const move = request();
+ return move ? props.getPlacement?.(move) : undefined;
+ },
+ start: (event, element) => {
+ sourceElement = element;
+ setOrigin({ x: event.clientX, y: event.clientY });
+ cancelled = false;
+ clearTimeout(clickTimeout);
+ },
+ }}
+ >
+ {props.children}
+ </GroupDragContext.Provider>
+ <DragOverlay
+ style={{
+ left: `${preview()?.rect.left ?? 0}px`,
+ top: `${preview()?.rect.top ?? 0}px`,
+ 'min-width': '0',
+ 'min-height': '0',
+ 'z-index': 100,
+ 'pointer-events': 'none',
+ }}
+ >
+ <Layer depth={2}>
+ <div aria-hidden="true" class="rounded-md bg-surface shadow-md">
+ {preview()?.element}
+ </div>
+ </Layer>
+ </DragOverlay>
+ <Show when={error()}>
+ <p
+ role="alert"
+ class="absolute bottom-4 left-1/2 z-50 -translate-x-1/2 rounded-md bg-tooltip px-3 py-2 text-xs text-ink shadow-sm"
+ >
+ {error()}
+ </p>
+ </Show>
+ </DragDropProvider>
+ );
+}
+
+/** Wrap an entity row once; both its sidebar item and bar start the same group move. */
+export function GanttDragItem(props: ParentProps<DragItem>) {
+ const drag = useGanttGroupDrag();
+ const gantt = useGantt();
+ if (!drag) return props.children;
+ const draggable = createDraggable(
+ `gantt-item:${typeof props.key}:${props.key}`,
+ {
+ get item() {
+ return {
+ id: props.id,
+ key: props.key,
+ groupId: props.groupId,
+ label: props.label,
+ };
+ },
+ }
+ );
+ return (
+ <div
+ ref={draggable.ref}
+ class={cn(
+ 'relative h-full',
+ draggable.isActiveDraggable &&
+ '[&_[data-gantt-bar-body]]:opacity-35 [&_[data-gantt-label]]:opacity-35'
+ )}
+ onMouseDown={(event) => {
+ if (event.button !== 0 || gantt.editing() || !drag.canDrag(props.id))
+ return;
+ if (
+ !event.target.closest(
+ '[data-gantt-label] button, [data-gantt-bar-body] > button:first-of-type'
+ )
+ )
+ return;
+ if (event.target.closest('[data-gantt-no-drag]')) return;
+ const element = event.target.closest<HTMLElement>(
+ '[data-gantt-bar-body], [data-gantt-label] button'
+ );
+ if (!element) return;
+ drag.start(event, element);
+ draggable.dragActivators.onmousedown?.(event);
+ }}
+ onDragStart={(event) => event.preventDefault()}
+ on:click={{
+ capture: true,
+ handleEvent(event: MouseEvent) {
+ if (!drag.suppressClick()) return;
+ event.preventDefault();
+ event.stopPropagation();
+ },
+ }}
+ >
+ {props.children}
+ </div>
+ );
+}
+
+/** Place inside each group row, including collapsed headers, to receive cross-group drops. */
+export function GanttGroupDrop(props: { id: string; groupId: string }) {
+ const drag = useGanttGroupDrag();
+ if (!drag) return null;
+ const droppable = createDroppable(`gantt-group:${props.id}`, {
+ get groupId() {
+ return props.groupId;
+ },
+ });
+ return (
+ <div
+ ref={droppable.ref}
+ aria-hidden="true"
+ data-gantt-group-drop={props.groupId}
+ class={cn(
+ 'pointer-events-none absolute inset-0 z-30',
+ drag.target() === props.groupId &&
+ 'bg-accent/10 ring-1 ring-inset ring-accent'
+ )}
+ />
+ );
+}
diff --git a/apps/web/src/components/gantt/gantt-group-placement.test.ts b/apps/web/src/components/gantt/gantt-group-placement.test.ts
new file mode 100644
index 0000000000..291df59d68
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-group-placement.test.ts
@@ -0,0 +1,50 @@
+import { expect, it } from 'vitest';
+import { ganttGroupPlacement } from './gantt-group-placement';
+
+type Row = { group?: string; entity?: { id: string; rank: number } };
+const source: Row = { group: 'a', entity: { id: 'one', rank: 2 } };
+const rows: Row[] = [
+ { group: 'a' },
+ source,
+ { group: 'b' },
+ { group: 'b', entity: { id: 'fresh', rank: 1 } },
+ { group: 'b', entity: { id: 'older', rank: 3 } },
+ { group: 'b' },
+ { group: 'c' },
+];
+function placement(items: Row[]) {
+ return ganttGroupPlacement({
+ items,
+ move: { id: 'one', fromGroup: 'a', toGroup: 'b' },
+ getEntity: (row) => row.entity,
+ getGroup: (row) => row.group,
+ compare: (left, right) => left.rank - right.rank,
+ });
+}
+
+it('uses active sorting and keeps the ghost before group pagination', () => {
+ expect(placement(rows)).toEqual({ index: 4 });
+ expect(
+ placement(
+ rows.map((row) =>
+ row === source ? { ...source, entity: { id: 'one', rank: 4 } } : row
+ )
+ )
+ ).toEqual({ index: 5 });
+});
+
+it('places a ghost after a collapsed destination header without expanding the group', () => {
+ expect(
+ placement([{ group: 'a' }, source, { group: 'b' }, { group: 'c' }])
+ ).toEqual({ index: 3 });
+});
+
+it('replaces an already-present assignee placement instead of creating a duplicate', () => {
+ expect(
+ placement([
+ ...rows.slice(0, 4),
+ { group: 'b', entity: source.entity },
+ ...rows.slice(4),
+ ])
+ ).toEqual({ index: 4, replace: true });
+});
diff --git a/apps/web/src/components/gantt/gantt-group-placement.ts b/apps/web/src/components/gantt/gantt-group-placement.ts
new file mode 100644
index 0000000000..7dc7e140bf
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-group-placement.ts
@@ -0,0 +1,34 @@
+import type { GanttGroupMove } from './gantt-group-drag';
+
+export type GanttGroupPlacement = { index: number; replace?: boolean };
+
+/** Group membership stays consumer-owned; insertion follows the consumer's existing sort. */
+export function ganttGroupPlacement<T, E extends { id: string }>(options: {
+ items: readonly T[];
+ move: GanttGroupMove;
+ getEntity: (item: T) => E | undefined;
+ getGroup: (item: T) => string | undefined;
+ compare: (left: E, right: E) => number;
+}): GanttGroupPlacement | undefined {
+ const { items, move, getEntity, getGroup, compare } = options;
+ const source = items.map(getEntity).find((entity) => entity?.id === move.id);
+ if (!source) return;
+ const existing = items.findIndex(
+ (item) => getGroup(item) === move.toGroup && getEntity(item)?.id === move.id
+ );
+ if (existing >= 0) return { index: existing, replace: true };
+ const first = items.findIndex((item) => getGroup(item) === move.toGroup);
+ if (first < 0) return;
+ let index = first;
+ for (
+ ;
+ index < items.length && getGroup(items[index]) === move.toGroup;
+ index++
+ ) {
+ const entity = getEntity(items[index]);
+ if (entity && compare(source, entity) < 0) break;
+ // A continuation stays after the ghost rather than separating the group from its preview.
+ if (!entity && index > first) break;
+ }
+ return { index };
+}
diff --git a/apps/web/src/components/gantt/gantt-header.tsx b/apps/web/src/components/gantt/gantt-header.tsx
new file mode 100644
index 0000000000..9f5fa0ea3f
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-header.tsx
@@ -0,0 +1,171 @@
+import { Key } from '@solid-primitives/keyed';
+import { cn } from '@ui';
+import { createMemo, For, type ParentProps, Show } from 'solid-js';
+import { HEADER_HEIGHT, useGantt } from './gantt-context';
+import {
+ formatGanttMonth,
+ type GanttTick,
+ ganttDateFromDay,
+ ganttTicks,
+} from './gantt-date';
+import { GanttCursorTooltip, GanttTodayLine } from './gantt-markers';
+
+export function GanttHeader(props: ParentProps<{ class?: string }>) {
+ const gantt = useGantt();
+ const months = createMemo(() =>
+ ganttTicks(gantt.range(), 'month', gantt.visibleRange()).map((tick) => ({
+ ...tick,
+ label: formatGanttMonth(
+ tick.start,
+ gantt.scale() === 'month' ? 'short' : 'long'
+ ),
+ }))
+ );
+ const ticks = createMemo(() =>
+ ganttTicks(gantt.range(), gantt.scale(), gantt.visibleRange())
+ );
+ const left = (day: number) =>
+ (day - gantt.range().start) * gantt.pixelsPerDay();
+ const calendarWidth = () =>
+ (gantt.visibleRange().end - gantt.visibleRange().start) *
+ gantt.pixelsPerDay();
+ // The drawer starts below the header; reserve only its toggle in the timeline band.
+ const textInset = () =>
+ gantt.labelWidth() > 0 ? gantt.labelWidth() + 8 : 64;
+ const pinnedMonthLeft = () =>
+ left(gantt.visibleRange().start) + textInset() - gantt.labelWidth();
+ const monthTextWidth = (tick: GanttTick) => tick.label.length * 7;
+ // Center the month text on its date; a trailing year does not shift that anchor.
+ const monthNaturalLeft = (tick: GanttTick) =>
+ left(tick.start) - monthTextWidth(tick) / 2 - 4;
+ const monthYear = (tick: GanttTick) => {
+ const date = ganttDateFromDay(tick.start);
+ return date.getMonth() === 0 || monthNaturalLeft(tick) <= pinnedMonthLeft()
+ ? date.getFullYear()
+ : undefined;
+ };
+ const monthLabelWidth = (tick: GanttTick) =>
+ monthTextWidth(tick) + (monthYear(tick) === undefined ? 8 : 44);
+ const monthLeft = (tick: GanttTick) =>
+ Math.min(
+ Math.max(monthNaturalLeft(tick), pinnedMonthLeft()),
+ left(tick.end) - monthLabelWidth(tick)
+ );
+ const monthOpacity = (tick: GanttTick) =>
+ Math.max(0, 1 - Math.max(0, pinnedMonthLeft() - monthLeft(tick)) / 32);
+ return (
+ <div
+ class={cn(
+ 'sticky top-0 z-30 flex border-b border-edge-muted bg-panel text-xs text-ink-muted',
+ props.class
+ )}
+ data-gantt-header=""
+ style={{ height: `${HEADER_HEIGHT}px`, width: `${gantt.width()}px` }}
+ >
+ <Show when={gantt.labelWidth() > 0}>
+ <div
+ class="sticky left-0 z-10 flex shrink-0 flex-wrap content-center items-center justify-between gap-x-2 gap-y-1 border-r border-edge-muted bg-inherit px-3 font-medium text-ink"
+ style={{ width: `${gantt.labelWidth()}px` }}
+ >
+ {props.children}
+ </div>
+ </Show>
+ <div class="relative isolate flex-1 overflow-clip">
+ <GanttTodayLine header />
+ <For each={ticks()}>
+ {(tick) => (
+ <div
+ data-gantt-date-tick=""
+ class="absolute inset-y-0 flex items-center leading-4 whitespace-nowrap"
+ style={{ left: `${left(tick.start)}px` }}
+ >
+ <span class="relative h-4 -translate-x-1/2">
+ <Show
+ when={
+ gantt.scale() !== 'month' &&
+ !months().some((month) => {
+ const distance = left(tick.start) - monthLeft(month);
+ const halfLabel = tick.label.length * 3 + 4;
+ return (
+ monthOpacity(month) > 0 &&
+ distance > -halfLabel &&
+ distance < monthLabelWidth(month) + halfLabel
+ );
+ })
+ }
+ >
+ {tick.label}
+ </Show>
+ <span
+ aria-hidden="true"
+ data-gantt-date-mark=""
+ class="absolute top-full left-1/2 mt-1 h-1.5 w-px -translate-x-1/2 bg-ink-extra-muted/70"
+ />
+ </span>
+ </div>
+ )}
+ </For>
+ <Key each={months()} by="start">
+ {(tick) => (
+ <div
+ data-gantt-month=""
+ class="pointer-events-none absolute inset-y-0 flex items-center overflow-clip text-ink whitespace-nowrap"
+ style={{
+ left: `${monthNaturalLeft(tick())}px`,
+ width: `${left(tick().end) - monthNaturalLeft(tick())}px`,
+ }}
+ >
+ <span
+ class="sticky z-20 flex shrink-0 items-baseline gap-2 bg-panel px-1 text-xs leading-4"
+ style={{
+ left: `${textInset()}px`,
+ opacity: monthOpacity(tick()),
+ }}
+ >
+ <span
+ class="shrink-0 text-center font-semibold"
+ style={{ width: `${monthTextWidth(tick())}px` }}
+ >
+ {tick().label}
+ </span>
+ <Show when={monthYear(tick()) !== undefined}>
+ <span
+ data-gantt-year=""
+ class="font-medium text-ink tabular-nums"
+ >
+ {monthYear(tick())}
+ </span>
+ </Show>
+ </span>
+ </div>
+ )}
+ </Key>
+ <div
+ aria-hidden="true"
+ data-gantt-timeline-fades=""
+ class="pointer-events-none absolute inset-0 z-10"
+ >
+ <div
+ class="sticky h-full"
+ style={{
+ left: `${gantt.labelWidth()}px`,
+ width: `${calendarWidth()}px`,
+ }}
+ >
+ <div class="absolute inset-y-0 left-0 w-[min(128px,33%)] bg-gradient-to-r from-panel to-transparent" />
+ <div class="absolute inset-y-0 right-0 w-[min(128px,33%)] bg-gradient-to-l from-panel to-transparent" />
+ </div>
+ </div>
+ <Show when={gantt.labelWidth() === 0}>
+ <div class="pointer-events-none absolute inset-0 z-30">
+ <div
+ data-gantt-toggle-mask=""
+ class="sticky left-0 h-full w-14 bg-panel"
+ />
+ </div>
+ </Show>
+ <GanttCursorTooltip />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/gantt/gantt-interaction.test.ts b/apps/web/src/components/gantt/gantt-interaction.test.ts
new file mode 100644
index 0000000000..25cbb390cb
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-interaction.test.ts
@@ -0,0 +1,37 @@
+import { expect, it } from 'vitest';
+import {
+ extendGanttRange,
+ ganttCreationRange,
+ snapGanttGuide,
+} from './gantt-interaction';
+
+it('snaps to the nearest visible start or inclusive end boundary, without inventing undated ends', () => {
+ const targets = [{ start: 10, end: 12 }, { start: 20 }];
+ expect(snapGanttGuide(12.8, 20, targets)).toEqual({ day: 13, edge: 'end' });
+ expect(snapGanttGuide(19.8, 20, targets)).toEqual({ day: 20, edge: 'start' });
+ expect(snapGanttGuide(21, 20, targets)).toEqual({ day: 21 });
+ expect(snapGanttGuide(12.5, 20, targets)).toEqual({ day: 12.5 });
+});
+
+it('creates inclusive calendar-date selections in either drag direction', () => {
+ expect(ganttCreationRange(10.2, 15.9)).toEqual({ start: 10, end: 16 });
+ expect(ganttCreationRange(15.9, 10.2)).toEqual({ start: 10, end: 16 });
+ expect(ganttCreationRange(10.2, 10.8)).toEqual({ start: 10, end: 11 });
+});
+
+it('extends only approached calendar edges, including viewports wider than their initial range', () => {
+ const range = { start: 10, end: 110 };
+ expect(extendGanttRange(range, 400, 1000, 3000, 20)).toBeUndefined();
+ expect(extendGanttRange(range, 10, 1000, 3000, 20)).toEqual({
+ start: -40,
+ end: 110,
+ });
+ expect(extendGanttRange(range, 1990, 1000, 3000, 20)).toEqual({
+ start: 10,
+ end: 160,
+ });
+ expect(extendGanttRange(range, 0, 1000, 1000, 20)).toEqual({
+ start: -40,
+ end: 160,
+ });
+});
diff --git a/apps/web/src/components/gantt/gantt-interaction.ts b/apps/web/src/components/gantt/gantt-interaction.ts
new file mode 100644
index 0000000000..5eda897eed
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-interaction.ts
@@ -0,0 +1,66 @@
+import type { GanttRange } from './gantt-date';
+
+export type GanttGuide = { day: number; edge?: 'start' | 'end' };
+export type GanttSnapTarget = { start: number; end?: number };
+
+export const MIN_GANTT_PIXELS_PER_DAY = 4;
+export const MAX_GANTT_PIXELS_PER_DAY = 80;
+
+/** Wheel zoom stays readable without permitting unbounded chart sizes. */
+export function zoomedGanttPixels(pixels: number, delta: number): number {
+ return Math.min(
+ MAX_GANTT_PIXELS_PER_DAY,
+ Math.max(MIN_GANTT_PIXELS_PER_DAY, pixels * Math.exp(-delta / 300))
+ );
+}
+
+/** End dates are inclusive, so their drawn edge is the next day's boundary. */
+export function snapGanttGuide(
+ day: number,
+ pixelsPerDay: number,
+ targets: readonly GanttSnapTarget[]
+): GanttGuide {
+ let result: GanttGuide = { day };
+ let distance = 8;
+ for (const target of targets) {
+ for (const point of [
+ { day: target.start, edge: 'start' as const },
+ ...(target.end === undefined
+ ? []
+ : [{ day: target.end + 1, edge: 'end' as const }]),
+ ]) {
+ const current = Math.abs(point.day - day) * pixelsPerDay;
+ if (current >= distance) continue;
+ result = point;
+ distance = current;
+ }
+ }
+ return result;
+}
+
+/** Selection direction does not change the selected calendar dates. */
+export function ganttCreationRange(first: number, last: number): GanttRange {
+ return {
+ start: Math.floor(Math.min(first, last)),
+ end: Math.floor(Math.max(first, last)) + 1,
+ };
+}
+
+/** Extend by roughly one viewport at the approached edge, without loading entity data. */
+export function extendGanttRange(
+ range: GanttRange,
+ left: number,
+ viewportWidth: number,
+ contentWidth: number,
+ pixelsPerDay: number
+): GanttRange | undefined {
+ const threshold = Math.min(160, viewportWidth / 4);
+ const before = left < threshold;
+ const after = contentWidth - viewportWidth - left < threshold;
+ if (!before && !after) return;
+ const days = Math.max(30, Math.ceil(viewportWidth / pixelsPerDay));
+ return {
+ start: range.start - (before ? days : 0),
+ end: range.end + (after ? days : 0),
+ };
+}
diff --git a/apps/web/src/components/gantt/gantt-markers.tsx b/apps/web/src/components/gantt/gantt-markers.tsx
new file mode 100644
index 0000000000..c155a3bcad
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-markers.tsx
@@ -0,0 +1,133 @@
+import { Button, cn } from '@ui';
+import { Show } from 'solid-js';
+import { match } from 'ts-pattern';
+import { GanttCalendarScene } from './gantt-clip';
+import { useGantt } from './gantt-context';
+import {
+ formatGanttDay,
+ type GanttDate,
+ ganttBarGeometry,
+ toGanttDay,
+} from './gantt-date';
+
+export function GanttCursorGuide() {
+ const gantt = useGantt();
+ return (
+ <Show when={!gantt.editing() && gantt.guide()}>
+ {(guide) => (
+ <GanttCalendarScene class="z-20">
+ <div
+ data-gantt-cursor-line=""
+ class="absolute inset-y-0 border-l border-dashed border-ink-muted opacity-70"
+ style={{
+ left: `${gantt.labelWidth() + (guide().day - gantt.range().start) * gantt.pixelsPerDay()}px`,
+ }}
+ />
+ </GanttCalendarScene>
+ )}
+ </Show>
+ );
+}
+
+export function GanttCursorTooltip() {
+ const gantt = useGantt();
+ return (
+ <Show when={!gantt.editing() && gantt.guide()}>
+ {(guide) => (
+ <span
+ data-gantt-cursor-label=""
+ class="pointer-events-none absolute bottom-1 z-30 overflow-hidden rounded border border-edge-muted bg-tooltip px-1.5 py-0.5 text-xxs text-ink whitespace-nowrap"
+ style={{
+ left: `${(guide().day - gantt.range().start) * gantt.pixelsPerDay()}px`,
+ 'max-width': `${Math.max(0, (gantt.visibleRange().end - gantt.visibleRange().start) * gantt.pixelsPerDay() - 16)}px`,
+ translate: `clamp(${(gantt.visibleRange().start - guide().day) * gantt.pixelsPerDay() + 8}px, -50%, calc(${(gantt.visibleRange().end - guide().day) * gantt.pixelsPerDay() - 8}px - 100%)) 0`,
+ }}
+ >
+ {formatGanttDay(
+ guide().edge === 'end' ? guide().day - 1 : Math.floor(guide().day),
+ false
+ )}
+ </span>
+ )}
+ </Show>
+ );
+}
+export function GanttTodayButton() {
+ const gantt = useGantt();
+ return (
+ <Button
+ depth={2}
+ size="md"
+ variant="outline"
+ class="bg-surface shadow-sm"
+ onClick={() => gantt.scrollToToday()}
+ >
+ Today
+ </Button>
+ );
+}
+
+/** Compose inside Gantt.Label so invalid-date explanations remain visible while scrolling. */
+export function GanttDateHint(props: {
+ start: GanttDate;
+ end?: GanttDate;
+ class?: string;
+}) {
+ const gantt = useGantt();
+ const problem = () =>
+ match(ganttBarGeometry(props, gantt.range(), gantt.pixelsPerDay()).kind)
+ .with('missing-start', () => 'No start date')
+ .with('invalid-start', () => 'Invalid start date')
+ .with('invalid-end', () => 'Invalid end date')
+ .with('reversed', () => 'End date precedes start')
+ .otherwise(() => '');
+ return (
+ <Show when={problem()}>
+ <span
+ class={cn('block truncate text-xxs text-ink-muted', props.class)}
+ title={problem()}
+ >
+ {problem()}
+ </span>
+ </Show>
+ );
+}
+
+export function GanttTodayLine(props: { date?: GanttDate; header?: boolean }) {
+ const gantt = useGantt();
+ const day = () =>
+ props.date == null ? gantt.today() : toGanttDay(props.date);
+ const visible = () => {
+ const current = day();
+ return (
+ current !== undefined &&
+ current + 0.5 >= gantt.visibleRange().start &&
+ current + 0.5 < gantt.visibleRange().end
+ );
+ };
+ const marker = () => (
+ <div
+ aria-hidden="true"
+ data-gantt-today={props.header ? 'header' : 'body'}
+ class="pointer-events-none absolute inset-y-0 z-0 w-px bg-ink-muted/60"
+ style={{
+ left: `${(props.header ? 0 : gantt.labelWidth()) + (day()! - gantt.range().start + 0.5) * gantt.pixelsPerDay()}px`,
+ }}
+ />
+ );
+ return (
+ <Show when={visible()}>
+ <Show
+ when={props.header}
+ fallback={
+ <GanttCalendarScene class="z-0">{marker()}</GanttCalendarScene>
+ }
+ >
+ {marker()}
+ </Show>
+ </Show>
+ );
+}
+export function GanttTodayMarker(props: { date?: GanttDate }) {
+ return <GanttTodayLine date={props.date} />;
+}
diff --git a/apps/web/src/components/gantt/gantt-rows.tsx b/apps/web/src/components/gantt/gantt-rows.tsx
new file mode 100644
index 0000000000..f57ab389c1
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-rows.tsx
@@ -0,0 +1,237 @@
+import { Key } from '@solid-primitives/keyed';
+import {
+ createVirtualizer,
+ defaultRangeExtractor,
+ type Range,
+} from '@tanstack/solid-virtual';
+import { cn } from '@ui';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ createUniqueId,
+ For,
+ type JSX,
+ on,
+ Show,
+ splitProps,
+} from 'solid-js';
+import { HEADER_HEIGHT, useGantt } from './gantt-context';
+import {
+ GanttGroupDrop,
+ type GanttGroupMove,
+ useGanttGroupDrag,
+} from './gantt-group-drag';
+import { GanttSidebarPanelRow } from './gantt-sidebar';
+
+type RowsProps<T> = {
+ items: readonly T[];
+ getKey: (item: T) => string | number;
+ /** Consecutive sidebar rows with the same key form one visual panel. */
+ getPanelKey?: (item: T) => string | number | undefined;
+ virtualize?: boolean;
+ children: (item: T) => JSX.Element;
+};
+
+function VirtualRows<T>(props: RowsProps<T>) {
+ const gantt = useGantt();
+ const drag = useGanttGroupDrag();
+ const [focusedKey, setFocusedKey] = createSignal<string | number>();
+ const virtualizer = createVirtualizer<HTMLDivElement, HTMLDivElement>({
+ get count() {
+ return props.items.length;
+ },
+ get getItemKey() {
+ const keys = props.items.map(props.getKey);
+ return (index: number) => keys[index];
+ },
+ getScrollElement: () => gantt.viewport() ?? null,
+ estimateSize: () => gantt.rowHeight(),
+ scrollMargin: HEADER_HEIGHT,
+ overscan: 8,
+ get rangeExtractor() {
+ const key = drag?.active()?.key ?? focusedKey();
+ const pinned =
+ key === undefined
+ ? -1
+ : props.items.findIndex((item) => props.getKey(item) === key);
+ return (range: Range) => {
+ const indexes = defaultRangeExtractor(range);
+ return pinned < 0 || indexes.includes(pinned)
+ ? indexes
+ : [...indexes, pinned].sort((a, b) => a - b);
+ };
+ },
+ });
+ createEffect(
+ on(gantt.rowHeight, () => virtualizer.measure(), { defer: true })
+ );
+ return (
+ <div
+ class="relative"
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: `${gantt.width()}px`,
+ }}
+ onFocusIn={(event) => {
+ const row = event.target.closest<HTMLElement>('[data-gantt-row-index]');
+ const index = Number(row?.dataset.ganttRowIndex);
+ const item = props.items[index];
+ if (item !== undefined) setFocusedKey(props.getKey(item));
+ }}
+ onFocusOut={(event) => {
+ if (
+ !(event.relatedTarget instanceof Node) ||
+ !event.currentTarget.contains(event.relatedTarget)
+ )
+ setFocusedKey(undefined);
+ }}
+ >
+ <Key each={virtualizer.getVirtualItems()} by="key">
+ {(virtualRow) => (
+ <div
+ data-gantt-row-index={virtualRow().index}
+ class="absolute left-0"
+ style={{ top: `${virtualRow().start - HEADER_HEIGHT}px` }}
+ >
+ <GanttSidebarPanelRow
+ items={props.items}
+ index={virtualRow().index}
+ getPanelKey={props.getPanelKey}
+ >
+ <For
+ each={props.items.slice(
+ virtualRow().index,
+ virtualRow().index + 1
+ )}
+ >
+ {(item) => props.children(item)}
+ </For>
+ </GanttSidebarPanelRow>
+ </div>
+ )}
+ </Key>
+ </div>
+ );
+}
+
+/** Only this slot chooses virtualization; consumers keep ownership of their data and rows. */
+function Rows<T>(props: RowsProps<T>) {
+ return (
+ <Show
+ when={props.virtualize}
+ fallback={
+ <div class="relative">
+ {/* Keep occurrence keys, but refresh the renderer when an immutable item is replaced. */}
+ <Key each={props.items} by={props.getKey}>
+ {(item, index) => (
+ <GanttSidebarPanelRow
+ items={props.items}
+ index={index()}
+ getPanelKey={props.getPanelKey}
+ >
+ <For each={[item()]}>
+ {(current) => props.children(current)}
+ </For>
+ </GanttSidebarPanelRow>
+ )}
+ </Key>
+ </div>
+ }
+ >
+ <VirtualRows {...props} />
+ </Show>
+ );
+}
+
+export function GanttRow(
+ props: Omit<JSX.HTMLAttributes<HTMLDivElement>, 'style'>
+) {
+ const gantt = useGantt();
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ return (
+ <div
+ {...rest}
+ class={cn(
+ 'relative border-b border-edge-muted/60 text-sm text-ink',
+ local.class
+ )}
+ style={{ width: `${gantt.width()}px`, height: `${gantt.rowHeight()}px` }}
+ >
+ {local.children}
+ </div>
+ );
+}
+
+type RowEntry<T> = {
+ key: string | number;
+ panelKey: string | number | undefined;
+} & ({ kind: 'item'; item: T } | { kind: 'preview'; move: GanttGroupMove });
+
+/** Insertion previews share the row model, so virtualized rows and scroll height stay aligned. */
+export function GanttRows<T>(
+ props: RowsProps<T> & {
+ renderDropPreview?: (move: GanttGroupMove) => JSX.Element;
+ }
+) {
+ const drag = useGanttGroupDrag();
+ const previewKey = `gantt-preview:${createUniqueId()}`;
+ const normal = createMemo<RowEntry<T>[]>((previous) => {
+ const activeKey = drag?.active()?.key;
+ const existing = new Map(previous?.map((row) => [row.key, row]));
+ const rows = props.items.map((item): RowEntry<T> => {
+ const key = props.getKey(item);
+ const row = existing.get(key);
+ const panelKey = props.getPanelKey ? props.getPanelKey(item) : '';
+ if (
+ row?.kind === 'item' &&
+ (key === activeKey || (row.item === item && row.panelKey === panelKey))
+ )
+ return row;
+ return { kind: 'item', item, key, panelKey };
+ });
+ // Keep the drag source registered through immutable updates and page replacement.
+ const source =
+ activeKey === undefined ? undefined : existing.get(activeKey);
+ if (source && !rows.some((row) => row.key === activeKey)) {
+ rows.splice(Math.min(previous!.indexOf(source), rows.length), 0, source);
+ }
+ return rows;
+ });
+ const entries = createMemo(() => {
+ const rows = normal().slice();
+ const move = drag?.move();
+ const placement = drag?.placement();
+ if (!move || !placement || !props.renderDropPreview) return rows;
+ rows.splice(
+ Math.max(0, Math.min(rows.length, placement.index)),
+ placement.replace ? 1 : 0,
+ {
+ kind: 'preview',
+ key: previewKey,
+ panelKey: move.toGroup,
+ move,
+ }
+ );
+ return rows;
+ });
+ return (
+ <Rows
+ items={entries()}
+ getKey={(row) => row.key}
+ getPanelKey={(row) => row.panelKey}
+ virtualize={props.virtualize}
+ >
+ {(row) =>
+ row.kind === 'item' ? (
+ props.children(row.item)
+ ) : (
+ <GanttRow data-gantt-drop-preview="" aria-hidden="true" inert>
+ <GanttGroupDrop id={previewKey} groupId={row.move.toGroup} />
+ {props.renderDropPreview?.(row.move)}
+ </GanttRow>
+ )
+ }
+ </Rows>
+ );
+}
diff --git a/apps/web/src/components/gantt/gantt-settings.tsx b/apps/web/src/components/gantt/gantt-settings.tsx
new file mode 100644
index 0000000000..863d4b97ee
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-settings.tsx
@@ -0,0 +1,87 @@
+import CheckIcon from '@phosphor/check.svg';
+import GearIcon from '@phosphor/gear-six.svg';
+import { Dropdown } from '@ui';
+import { useGantt } from './gantt-context';
+
+function SettingOption(props: { value: string; children: string }) {
+ return (
+ <Dropdown.RadioItem value={props.value} closeOnSelect={false}>
+ <span class="flex-1">{props.children}</span>
+ <Dropdown.ItemIndicator>
+ <CheckIcon class="size-3.5 text-ink" />
+ </Dropdown.ItemIndicator>
+ </Dropdown.RadioItem>
+ );
+}
+
+/** Period changes zoom; grid settings only change calendar decoration. */
+export function GanttSettings() {
+ const gantt = useGantt();
+ return (
+ <Dropdown placement="bottom-end">
+ <Dropdown.Trigger
+ depth={2}
+ variant="outline"
+ size="icon-md"
+ class="bg-surface shadow-sm"
+ aria-label="Timeline settings"
+ tooltip="Timeline settings"
+ >
+ <GearIcon class="size-4" />
+ </Dropdown.Trigger>
+ <Dropdown.Content class="w-60 max-w-[calc(100vw-1rem)]">
+ <Dropdown.Group>
+ <Dropdown.GroupLabel>Period</Dropdown.GroupLabel>
+ <Dropdown.RadioGroup
+ value={gantt.scale()}
+ onChange={(value) => {
+ if (value === 'day' || value === 'week' || value === 'month') {
+ gantt.setScale(value);
+ }
+ }}
+ >
+ <SettingOption value="day">Day</SettingOption>
+ <SettingOption value="week">Week</SettingOption>
+ <SettingOption value="month">Month</SettingOption>
+ </Dropdown.RadioGroup>
+ </Dropdown.Group>
+ <Dropdown.Group>
+ <Dropdown.GroupLabel>Grid spacing</Dropdown.GroupLabel>
+ <Dropdown.CheckboxItem
+ checked={gantt.gridVisible()}
+ onChange={gantt.setGridVisible}
+ closeOnSelect={false}
+ >
+ <span class="flex-1">Show grid lines</span>
+ </Dropdown.CheckboxItem>
+ <Dropdown.RadioGroup
+ value={gantt.gridScale()}
+ onChange={(value) => {
+ if (value === 'day' || value === 'week' || value === 'month') {
+ gantt.setGridScale(value);
+ }
+ }}
+ >
+ <SettingOption value="day">Daily</SettingOption>
+ <SettingOption value="week">Weekly</SettingOption>
+ <SettingOption value="month">Monthly</SettingOption>
+ </Dropdown.RadioGroup>
+ </Dropdown.Group>
+ <Dropdown.Group>
+ <Dropdown.GroupLabel>Line style</Dropdown.GroupLabel>
+ <Dropdown.RadioGroup
+ value={gantt.gridStyle()}
+ onChange={(value) => {
+ if (value === 'solid' || value === 'dashed') {
+ gantt.setGridStyle(value);
+ }
+ }}
+ >
+ <SettingOption value="solid">Solid</SettingOption>
+ <SettingOption value="dashed">Dashed</SettingOption>
+ </Dropdown.RadioGroup>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ );
+}
diff --git a/apps/web/src/components/gantt/gantt-sidebar.tsx b/apps/web/src/components/gantt/gantt-sidebar.tsx
new file mode 100644
index 0000000000..562d6b8a5b
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-sidebar.tsx
@@ -0,0 +1,186 @@
+import SidebarIcon from '@phosphor/sidebar-simple.svg';
+import { Button, cn, Layer, Surface } from '@ui';
+import {
+ type Accessor,
+ createContext,
+ type JSX,
+ onCleanup,
+ type ParentProps,
+ Show,
+ splitProps,
+ useContext,
+} from 'solid-js';
+import { useGantt } from './gantt-context';
+
+/** Compose with labelWidth={0}; row labels share the calendar's native vertical scroll. */
+export function GanttSidebarToggle() {
+ const gantt = useGantt();
+ onCleanup(() => gantt.sidebar.setTrigger(undefined));
+ return (
+ <div class="absolute left-3 top-2 z-40">
+ <Button
+ depth={2}
+ ref={gantt.sidebar.setTrigger}
+ size="icon-md"
+ variant="outline"
+ class="bg-surface shadow-sm"
+ label={
+ gantt.sidebar.open() ? 'Hide timeline items' : 'Show timeline items'
+ }
+ aria-expanded={gantt.sidebar.open()}
+ disabled={gantt.editing()}
+ onClick={() => gantt.sidebar.setOpen(!gantt.sidebar.open())}
+ >
+ <SidebarIcon class="size-4" />
+ </Button>
+ </div>
+ );
+}
+
+const SidebarPanelContext = createContext<{
+ first: Accessor<boolean>;
+ last: Accessor<boolean>;
+}>();
+
+/** Adjacent rows share a panel, even when only part of the group is mounted. */
+export function GanttSidebarPanelRow<T>(
+ props: ParentProps<{
+ items: readonly T[];
+ index: number;
+ getPanelKey?: (item: T) => string | number | undefined;
+ }>
+) {
+ const key = (index: number) => {
+ const item = props.items[index];
+ if (item === undefined) return undefined;
+ return props.getPanelKey ? props.getPanelKey(item) : '';
+ };
+ return (
+ <SidebarPanelContext.Provider
+ value={{
+ first: () =>
+ key(props.index) === undefined ||
+ props.index === 0 ||
+ key(props.index - 1) !== key(props.index),
+ last: () =>
+ key(props.index) === undefined ||
+ props.index === props.items.length - 1 ||
+ key(props.index + 1) !== key(props.index),
+ }}
+ >
+ {props.children}
+ </SidebarPanelContext.Provider>
+ );
+}
+
+/** The panel and its contents clip together in the calendar's native viewport. */
+export function GanttLabel(
+ props: Omit<JSX.HTMLAttributes<HTMLDivElement>, 'style'>
+) {
+ const gantt = useGantt();
+ const panel = useContext(SidebarPanelContext);
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ const drawer = () => gantt.labelWidth() === 0;
+ const first = () => panel?.first() ?? true;
+ const last = () => panel?.last() ?? true;
+ const hidden = () => drawer() && !gantt.sidebar.open();
+ return (
+ <Layer depth={drawer() ? 1 : undefined}>
+ <div
+ {...rest}
+ class={cn(
+ 'sticky z-20 flex min-w-0 items-center overflow-clip px-2 text-xs text-ink',
+ !drawer() && 'left-0 h-full border-r border-edge-muted',
+ drawer() &&
+ 'left-2 border-x border-edge-muted bg-surface light-mode:border-ink/15 light-mode:bg-[color-mix(in_oklch,var(--color-surface)_97%,var(--color-ink))] transition-[translate,visibility] duration-200 ease-out motion-reduce:transition-none',
+ drawer() && first() && 'rounded-t-lg border-t',
+ drawer() && last() && 'rounded-b-lg border-b',
+ hidden() &&
+ 'invisible -translate-x-[calc(100%+8px)] pointer-events-none',
+ local.class
+ )}
+ data-gantt-label=""
+ data-gantt-panel-start={drawer() && first() ? '' : undefined}
+ data-gantt-panel-end={drawer() && last() ? '' : undefined}
+ aria-hidden={hidden() || undefined}
+ inert={hidden()}
+ style={{
+ width: `${gantt.labelWidth() || Math.max(0, gantt.sidebar.width() - 16)}px`,
+ height: drawer()
+ ? `calc(100% - ${(first() ? 4 : 0) + (last() ? 4 : 0)}px)`
+ : '100%',
+ 'margin-top': drawer() && first() ? '4px' : undefined,
+ }}
+ >
+ {local.children}
+ </div>
+ </Layer>
+ );
+}
+
+/** Each child supplies its own surface; the header only arranges the controls. */
+export function GanttControls(props: ParentProps) {
+ return (
+ <div
+ role="group"
+ aria-label="Timeline controls"
+ class="absolute right-3 top-2 z-40 flex items-center gap-2"
+ >
+ {props.children}
+ </div>
+ );
+}
+
+/** Group headings stay visible across the list and calendar, independent of the drawer. */
+export function GanttGroupHeader(
+ props: Omit<JSX.HTMLAttributes<HTMLDivElement>, 'style'>
+) {
+ const gantt = useGantt();
+ const [local, rest] = splitProps(props, ['children', 'class']);
+ const width = () => {
+ const visible = gantt.visibleRange();
+ return (
+ gantt.labelWidth() + (visible.end - visible.start) * gantt.pixelsPerDay()
+ );
+ };
+ return (
+ <Surface
+ {...rest}
+ depth={3}
+ hideBorder
+ data-gantt-group-header=""
+ class={cn(
+ 'group/header sticky left-1 z-[25] my-0.5 flex h-[calc(100%-4px)] items-center rounded-lg border border-edge-muted text-xs font-medium text-ink-muted hover:bg-active',
+ local.class
+ )}
+ style={{ width: `${Math.max(0, width() - 8)}px` }}
+ >
+ {local.children}
+ </Surface>
+ );
+}
+
+/** Pagination stays aligned to the visible calendar edge after horizontal panning. */
+export function GanttPagination(props: ParentProps) {
+ const gantt = useGantt();
+ const inset = () =>
+ gantt.labelWidth() || (gantt.sidebar.open() ? gantt.sidebar.width() : 0);
+ const width = () => {
+ const visible = gantt.visibleRange();
+ return Math.max(
+ 0,
+ gantt.labelWidth() +
+ (visible.end - visible.start) * gantt.pixelsPerDay() -
+ inset()
+ );
+ };
+ return (
+ <div
+ data-gantt-pagination=""
+ class="sticky z-20 flex h-full items-center px-4"
+ style={{ left: `${inset()}px`, width: `${width()}px` }}
+ >
+ <Show when={width() >= 180}>{props.children}</Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/gantt/gantt-zoom-controls.tsx b/apps/web/src/components/gantt/gantt-zoom-controls.tsx
new file mode 100644
index 0000000000..2019692fdf
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt-zoom-controls.tsx
@@ -0,0 +1,90 @@
+import MinusIcon from '@phosphor/minus.svg';
+import PlusIcon from '@phosphor/plus.svg';
+import { Button, cn } from '@ui';
+import { useGantt } from './gantt-context';
+import { ganttPixelsPerDay } from './gantt-date';
+import {
+ MAX_GANTT_PIXELS_PER_DAY,
+ MIN_GANTT_PIXELS_PER_DAY,
+} from './gantt-interaction';
+
+/** Compose beside Gantt.Chart so the controls stay fixed while the calendar scrolls. */
+export function GanttZoomControls() {
+ const gantt = useGantt();
+ const baseline = ganttPixelsPerDay('week');
+ const percentage = () => Math.round((gantt.pixelsPerDay() / baseline) * 100);
+ const unavailable = () => !gantt.viewport() || gantt.editing();
+ const canZoomOut = () =>
+ !unavailable() && gantt.pixelsPerDay() > MIN_GANTT_PIXELS_PER_DAY;
+ const canZoomIn = () =>
+ !unavailable() && gantt.pixelsPerDay() < MAX_GANTT_PIXELS_PER_DAY;
+
+ function zoomTo(pixels: number) {
+ const viewport = gantt.viewport();
+ if (!viewport || unavailable()) return;
+ const bounds = viewport.getBoundingClientRect();
+ const center =
+ bounds.left +
+ gantt.labelWidth() +
+ (viewport.clientWidth - gantt.labelWidth()) / 2;
+ gantt.zoomAt(center, 300 * Math.log(gantt.pixelsPerDay() / pixels));
+ }
+
+ return (
+ <div
+ class="pointer-events-none absolute bottom-3 right-3 z-40 flex justify-end"
+ style={{ left: `${gantt.labelWidth() + 12}px` }}
+ >
+ <div
+ role="group"
+ aria-label="Timeline zoom"
+ class="group/zoom pointer-events-none flex min-w-0 max-w-full flex-wrap items-center justify-center gap-2 hover:pointer-events-auto focus-within:pointer-events-auto"
+ >
+ <div class="flex shrink-0 items-center gap-1">
+ <Button
+ depth={2}
+ size="icon-lg"
+ variant="ghost"
+ label="Zoom out"
+ tooltipDisabled={!canZoomOut()}
+ class={cn(
+ 'invisible border-edge-muted bg-surface opacity-0 shadow-md transition-opacity group-hover/zoom:visible group-hover/zoom:pointer-events-auto group-hover/zoom:opacity-100 group-focus-within/zoom:visible group-focus-within/zoom:pointer-events-auto group-focus-within/zoom:opacity-100 touch:visible touch:pointer-events-auto touch:opacity-100 motion-reduce:transition-none',
+ gantt.scrollZooming() && 'visible pointer-events-auto opacity-100'
+ )}
+ disabled={!canZoomOut()}
+ onClick={() => zoomTo(gantt.pixelsPerDay() / 1.25)}
+ >
+ <MinusIcon class="size-5" />
+ </Button>
+ <Button
+ depth={2}
+ size="icon-lg"
+ variant="ghost"
+ label="Zoom in"
+ tooltipDisabled={!canZoomIn()}
+ class={cn(
+ 'invisible border-edge-muted bg-surface opacity-0 shadow-md transition-opacity group-hover/zoom:visible group-hover/zoom:pointer-events-auto group-hover/zoom:opacity-100 group-focus-within/zoom:visible group-focus-within/zoom:pointer-events-auto group-focus-within/zoom:opacity-100 touch:visible touch:pointer-events-auto touch:opacity-100 motion-reduce:transition-none',
+ gantt.scrollZooming() && 'visible pointer-events-auto opacity-100'
+ )}
+ disabled={!canZoomIn()}
+ onClick={() => zoomTo(gantt.pixelsPerDay() * 1.25)}
+ >
+ <PlusIcon class="size-5" />
+ </Button>
+ </div>
+ <Button
+ depth={2}
+ size="lg"
+ variant="ghost"
+ label="Reset zoom"
+ tooltip="Reset zoom to 100%"
+ disabled={unavailable()}
+ class="pointer-events-auto w-16 shrink-0 border-edge-muted bg-surface px-2 text-sm shadow-md tabular-nums"
+ onClick={() => zoomTo(baseline)}
+ >
+ <span class="truncate">{percentage()}%</span>
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/gantt/gantt.test.ts b/apps/web/src/components/gantt/gantt.test.ts
new file mode 100644
index 0000000000..b1807bd110
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt.test.ts
@@ -0,0 +1,885 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { createComponent, createSignal } from 'solid-js';
+import { insert } from 'solid-js/web';
+import { afterEach, expect, it, vi } from 'vitest';
+import { Gantt } from './gantt';
+import { useGantt } from './gantt-context';
+import { toGanttDay } from './gantt-date';
+import {
+ MAX_GANTT_PIXELS_PER_DAY,
+ MIN_GANTT_PIXELS_PER_DAY,
+} from './gantt-interaction';
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+type Item = { id: string; name: string; group?: string };
+
+it('refreshes immutable rows and panel boundaries when reused keys change order or group', () => {
+ const [items, setItems] = createSignal<Item[]>([
+ { id: 'a', name: 'Old A', group: 'first' },
+ { id: 'b', name: 'Old B', group: 'first' },
+ ]);
+ const view = render(() =>
+ createComponent(Gantt.Root, {
+ labelWidth: 0,
+ range: { start: 0, end: 30 },
+ get children() {
+ return createComponent(Gantt.Rows<Item>, {
+ get items() {
+ return items();
+ },
+ getKey: (item) => item.id,
+ getPanelKey: (item) => item.group,
+ children: (item) =>
+ createComponent(Gantt.Row, {
+ get children() {
+ return createComponent(Gantt.Label, {
+ get children() {
+ return item.name;
+ },
+ });
+ },
+ }),
+ });
+ },
+ })
+ );
+
+ expect(view.container.textContent).toBe('Old AOld B');
+ const panelEdges = (edge: 'start' | 'end') =>
+ [...view.container.querySelectorAll(`[data-gantt-panel-${edge}]`)].map(
+ (label) => label.textContent
+ );
+ expect(panelEdges('start')).toEqual(['Old A']);
+ expect(panelEdges('end')).toEqual(['Old B']);
+ setItems([
+ { id: 'b', name: 'New B', group: 'second' },
+ { id: 'a', name: 'New A', group: 'first' },
+ ]);
+ expect(view.container.textContent).toBe('New BNew A');
+ expect(panelEdges('start')).toEqual(['New B', 'New A']);
+ expect(panelEdges('end')).toEqual(['New B', 'New A']);
+ setItems([{ id: 'a', name: 'Latest A', group: 'first' }]);
+ expect(view.container.textContent).toBe('Latest A');
+ expect(panelEdges('start')).toEqual(['Latest A']);
+ expect(panelEdges('end')).toEqual(['Latest A']);
+});
+
+it.each([1, 100])(
+ 'preserves the date at native scroll edges (range end %i)',
+ async (end) => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ const viewport = document.createElement('div');
+ let left = 0;
+ const writeScroll = vi.fn((value: number) => {
+ left = Math.max(
+ 0,
+ Math.min(value, viewport.scrollWidth - viewport.clientWidth)
+ );
+ });
+ Object.defineProperty(viewport, 'scrollLeft', {
+ get: () => left,
+ set: writeScroll,
+ });
+ Object.defineProperty(viewport, 'clientWidth', { value: 1200 });
+ Object.defineProperty(viewport, 'scrollWidth', {
+ get: () =>
+ Number.parseFloat(
+ (viewport.firstElementChild as HTMLElement).style.width
+ ),
+ });
+ let gantt!: ReturnType<typeof useGantt>;
+ render(() =>
+ createComponent(Gantt.Root, {
+ range: { start: 0, end },
+ get children() {
+ return createComponent(() => {
+ gantt = useGantt();
+ insert(
+ viewport,
+ createComponent(Gantt.Row, { children: 'Extent probe' })
+ );
+ return viewport;
+ }, {});
+ },
+ })
+ );
+ gantt.setViewport(viewport);
+ gantt.updateViewport();
+ viewport.scrollTop = 77;
+ for (const offset of [120.5, 0]) {
+ const before = gantt.range();
+ left = offset;
+ const anchor = before.start + left / gantt.pixelsPerDay();
+ writeScroll.mockClear();
+ gantt.updateViewport();
+ expect(gantt.range().start).toBeLessThan(before.start);
+ expect(gantt.visibleRange().start).toBeCloseTo(anchor);
+ expect(writeScroll).toHaveBeenCalledOnce();
+ expect(viewport.scrollTop).toBe(77);
+ gantt.updateViewport();
+ left -= 20.5;
+ gantt.updateViewport();
+ const moved = gantt.visibleRange().start;
+ await Promise.resolve();
+ vi.advanceTimersByTime(40);
+ expect(gantt.visibleRange().start).toBeCloseTo(moved);
+ expect(writeScroll).toHaveBeenCalledOnce();
+ }
+ const rebased = gantt.range();
+ writeScroll.mockClear();
+ left = viewport.scrollWidth - viewport.clientWidth - 10;
+ gantt.updateViewport();
+ expect(gantt.range().end).toBeGreaterThan(rebased.end);
+ expect(gantt.range().start).toBe(rebased.start);
+ expect(writeScroll).not.toHaveBeenCalled();
+ }
+);
+
+it('pins the correct year and aligns date marks across month boundaries', async () => {
+ const start = toGanttDay('2026-12-01')!;
+ const viewport = document.createElement('div');
+ Object.defineProperty(viewport, 'clientWidth', { value: 1000 });
+ let gantt!: ReturnType<typeof useGantt>;
+ const view = render(() =>
+ createComponent(Gantt.Root, {
+ range: { start, end: toGanttDay('2027-04-01')! },
+ get children() {
+ return createComponent(() => {
+ gantt = useGantt();
+ gantt.setViewport(viewport);
+ gantt.updateViewport();
+ return createComponent(Gantt.Header, {});
+ }, {});
+ },
+ })
+ );
+ const scrollTo = (date: string) => {
+ viewport.scrollLeft = (toGanttDay(date)! - start) * gantt.pixelsPerDay();
+ gantt.updateViewport();
+ };
+ for (const [date, month, year] of [
+ ['2026-12-31', 'December', '2026'],
+ ['2027-01-01', 'January', '2027'],
+ ['2027-02-01', 'February', '2027'],
+ ]) {
+ scrollTo(date);
+ expect(
+ view.getByText(month).parentElement?.querySelector('[data-gantt-year]')
+ ?.textContent
+ ).toBe(year);
+ }
+ expect(
+ view.getByText('March').parentElement?.querySelector('[data-gantt-year]')
+ ).toBeNull();
+ gantt.setScale('month');
+ await Promise.resolve();
+ expect(
+ view.getByText('Feb').parentElement?.querySelector('[data-gantt-year]')
+ ?.textContent
+ ).toBe('2027');
+ gantt.setScale('day');
+ await Promise.resolve();
+ for (const lastDay of ['2026-12-31', '2027-01-31', '2027-02-28']) {
+ scrollTo(lastDay);
+ const position = (toGanttDay(lastDay)! - start) * gantt.pixelsPerDay();
+ const ticks = [
+ ...view.container.querySelectorAll<HTMLElement>('[data-gantt-date-tick]'),
+ ].slice(0, 3);
+ expect(ticks.map((tick) => Number.parseFloat(tick.style.left))).toEqual([
+ position,
+ position + gantt.pixelsPerDay(),
+ position + 2 * gantt.pixelsPerDay(),
+ ]);
+ expect(
+ ticks.map(
+ (tick) => tick.querySelectorAll('[data-gantt-date-mark]').length
+ )
+ ).toEqual([1, 1, 1]);
+ }
+});
+
+it('opens timeline settings without crashing and changes the calendar grid independently of zoom', async () => {
+ vi.stubGlobal('scrollTo', vi.fn());
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ let gantt!: ReturnType<typeof useGantt>;
+ render(() =>
+ createComponent(Gantt.Root, {
+ range: { start: 0, end: 100 },
+ get children() {
+ return createComponent(() => {
+ gantt = useGantt();
+ return createComponent(Gantt.Settings, {});
+ }, {});
+ },
+ })
+ );
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Timeline settings' }), {
+ key: 'ArrowDown',
+ });
+ expect(await screen.findByRole('menu')).not.toBeNull();
+ fireEvent.keyDown(screen.getByRole('menuitemradio', { name: 'Monthly' }), {
+ key: 'Enter',
+ });
+ await waitFor(() => expect(gantt.gridScale()).toBe('month'));
+ expect(gantt.scale()).toBe('week');
+});
+function chartFixture(initialWidth = 1000, drawer = false) {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-10-01T12:00:00'));
+ const today = toGanttDay(new Date())!;
+ const [range, setRange] = createSignal({
+ start: today - 60,
+ end: today + 60,
+ });
+ let width = initialWidth;
+ let gantt!: ReturnType<typeof useGantt>;
+ const measurements: (() => void)[] = [];
+ const item = document.createElement('button');
+ item.type = 'button';
+ item.textContent = 'Item list entry';
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(measure: () => void) {
+ measurements.push(measure);
+ }
+ observe() {}
+ disconnect() {}
+ }
+ );
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(
+ () => width
+ );
+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(600);
+ vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ const content = this.firstElementChild;
+ return content instanceof HTMLElement
+ ? Number.parseFloat(content.style.width) || 0
+ : 0;
+ }
+ );
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(
+ () => new DOMRect(0, 0, width, 600)
+ );
+ const view = render(() =>
+ createComponent(Gantt.Root, {
+ labelWidth: drawer ? 0 : undefined,
+ get range() {
+ return range();
+ },
+ get children() {
+ return createComponent(() => {
+ gantt = useGantt();
+ return [
+ createComponent(Gantt.Chart, {
+ get children() {
+ return [
+ createComponent(Gantt.Header, {}),
+ ...(drawer
+ ? [
+ createComponent(Gantt.Row, {
+ get children() {
+ return [
+ createComponent(Gantt.Label, { children: item }),
+ createComponent(Gantt.Bar, {
+ start: '2026-09-01',
+ end: '2026-10-04',
+ title: 'Timeline item',
+ children: 'Timeline item',
+ }),
+ ];
+ },
+ }),
+ ]
+ : []),
+ createComponent(Gantt.TodayMarker, {}),
+ ];
+ },
+ }),
+ ...(drawer ? [createComponent(Gantt.SidebarToggle, {})] : []),
+ createComponent(Gantt.ZoomControls, {}),
+ ];
+ }, {});
+ },
+ })
+ );
+ const scrollTo = vi.fn((options: ScrollToOptions) => {
+ view.getByLabelText('Gantt timeline').scrollLeft = options.left ?? 0;
+ });
+ Object.defineProperty(view.getByLabelText('Gantt timeline'), 'scrollTo', {
+ value: scrollTo,
+ });
+ return {
+ ...view,
+ gantt,
+ today,
+ viewport: view.getByLabelText('Gantt timeline'),
+ setRange,
+ scrollTo,
+ resize(next: number) {
+ width = next;
+ measurements.forEach((measure) => measure());
+ },
+ };
+}
+
+it('starts middle-button panning from sidebar items and bars without activating them', async () => {
+ const { gantt, viewport, container } = chartFixture(1000, true);
+ await waitFor(() => expect(gantt.viewport()).toBe(viewport));
+ await Promise.resolve();
+ const initialLeft = viewport.scrollLeft;
+ viewport.scrollTop = 200;
+ const targets = [
+ screen.getByText('Item list entry'),
+ container.querySelector<HTMLElement>('[data-gantt-bar-body]')!,
+ ];
+ const activate = vi.fn();
+ for (const target of targets) {
+ target.addEventListener('mousedown', activate);
+ const down = new MouseEvent('mousedown', {
+ bubbles: true,
+ cancelable: true,
+ button: 1,
+ buttons: 4,
+ clientX: 500,
+ clientY: 300,
+ });
+ fireEvent(target, down);
+ expect(down.defaultPrevented).toBe(true);
+ expect(gantt.editing()).toBe(true);
+ fireEvent.mouseMove(window, { buttons: 4, clientX: 450, clientY: 260 });
+ fireEvent.mouseUp(window, { button: 0, buttons: 4 });
+ expect(gantt.editing()).toBe(true);
+ fireEvent.mouseUp(window, { button: 1 });
+ expect(gantt.editing()).toBe(false);
+ }
+ expect(activate).not.toHaveBeenCalled();
+ gantt.setEditing(true);
+ fireEvent.mouseDown(viewport, { button: 1, buttons: 4 });
+ expect(gantt.editing()).toBe(true);
+ const stoppedLeft = viewport.scrollLeft;
+ fireEvent.mouseMove(window, { buttons: 4, clientX: 100, clientY: 0 });
+ expect(viewport.scrollLeft).toBe(stoppedLeft);
+ gantt.setEditing(false);
+ expect(viewport.scrollLeft).toBe(initialLeft + 100);
+ expect(viewport.scrollTop).toBe(280);
+ expect(gantt.sidebar.open()).toBe(true);
+});
+
+it.each(['escape', 'blur', 'release', 'unmount'])(
+ 'cleans up middle-mouse panning on %s',
+ async (reason) => {
+ const { gantt, viewport, unmount } = chartFixture(1000, true);
+ await waitFor(() => expect(gantt.viewport()).toBe(viewport));
+ await Promise.resolve();
+ const events: EventTarget = window;
+ const listeners = vi.spyOn(events, 'addEventListener');
+ const removed = vi.spyOn(events, 'removeEventListener');
+ fireEvent.mouseDown(viewport, {
+ button: 1,
+ buttons: 4,
+ clientX: 500,
+ clientY: 300,
+ });
+ expect(gantt.editing()).toBe(true);
+ const move = listeners.mock.calls.find(
+ ([type]) => type === 'mousemove'
+ )?.[1];
+ const release = listeners.mock.calls.find(
+ ([type]) => type === 'mouseup'
+ )?.[1];
+ if (typeof move !== 'function' || typeof release !== 'function')
+ throw new Error('Pan listeners were not registered');
+
+ if (reason === 'escape') fireEvent.keyDown(viewport, { key: 'Escape' });
+ if (reason === 'blur') fireEvent.blur(window);
+ if (reason === 'release')
+ fireEvent.mouseMove(window, { buttons: 0, clientX: 400, clientY: 200 });
+ if (reason === 'unmount') unmount();
+ expect(gantt.editing()).toBe(false);
+ expect(removed).toHaveBeenCalledWith('mousemove', move, true);
+ expect(removed).toHaveBeenCalledWith('mouseup', release, true);
+
+ const left = viewport.scrollLeft;
+ // A queued callback from the ended gesture must not disturb another editing owner.
+ gantt.setEditing(true);
+ move.call(
+ window,
+ new MouseEvent('mousemove', { buttons: 4, clientX: 400, clientY: 200 })
+ );
+ release.call(window, new MouseEvent('mouseup', { button: 1 }));
+ expect(viewport.scrollLeft).toBe(left);
+ expect(gantt.editing()).toBe(true);
+ gantt.setEditing(false);
+ }
+);
+
+it.each([-5_000, -300, 300, 5_000])(
+ 'preserves the full %ipx middle-drag distance across native scroll boundaries',
+ async (delta) => {
+ const { gantt, viewport } = chartFixture();
+ await waitFor(() => expect(gantt.viewport()).toBe(viewport));
+ await Promise.resolve();
+ let left =
+ delta < 0 ? 170 : viewport.scrollWidth - viewport.clientWidth - 170;
+ Object.defineProperty(viewport, 'scrollLeft', {
+ get: () => left,
+ set: (value: number) => {
+ left = Math.max(
+ 0,
+ Math.min(value, viewport.scrollWidth - viewport.clientWidth)
+ );
+ },
+ configurable: true,
+ });
+ fireEvent.scroll(viewport);
+ const anchor = gantt.visibleRange().start;
+ const pixels = gantt.pixelsPerDay();
+ fireEvent.mouseDown(viewport, {
+ button: 1,
+ buttons: 4,
+ clientX: 500,
+ clientY: 300,
+ });
+ fireEvent.mouseMove(window, {
+ buttons: 4,
+ clientX: 500 - delta,
+ clientY: 300,
+ });
+ expect(gantt.visibleRange().start).toBeCloseTo(anchor + delta / pixels);
+ fireEvent.mouseMove(window, {
+ buttons: 4,
+ clientX: 500 - delta * 1.5,
+ clientY: 300,
+ });
+ expect(gantt.visibleRange().start).toBeCloseTo(
+ anchor + (delta * 1.5) / pixels
+ );
+ fireEvent.mouseUp(window, { button: 1 });
+ }
+);
+
+it('defaults the drawer open and preserves explicit choices across responsive resizing', async () => {
+ const view = chartFixture(1000, true);
+ const { gantt, viewport, resize } = view;
+ await waitFor(() => expect(gantt.viewport()).toBe(viewport));
+ await Promise.resolve();
+ await Promise.resolve();
+ const anchor = gantt.visibleRange().start;
+ expect(gantt.sidebar.open()).toBe(true);
+ const toggle = view.getByRole('button', { name: 'Hide timeline items' });
+ view.getByRole('button', { name: 'Item list entry' }).focus();
+ resize(320);
+ expect(gantt.sidebar.open()).toBe(false);
+ expect(document.activeElement).toBe(toggle);
+ resize(1000);
+ expect(gantt.sidebar.open()).toBe(true);
+ fireEvent.click(toggle);
+ resize(320);
+ resize(1000);
+ expect(gantt.sidebar.open()).toBe(false);
+ fireEvent.click(toggle);
+ resize(320);
+ expect(gantt.sidebar.open()).toBe(true);
+ expect(gantt.visibleRange().start).toBeCloseTo(anchor);
+});
+it('preserves dates and restores focus when the item drawer opens and closes', async () => {
+ const view = chartFixture(1000, true);
+ const { gantt, viewport } = view;
+ await waitFor(() => expect(gantt.viewport()).toBe(viewport));
+ await Promise.resolve();
+ gantt.sidebar.setOpen(false);
+ const anchor = gantt.visibleRange().start;
+ const left = viewport.scrollLeft;
+ const toggle = view.getByRole('button', { name: 'Show timeline items' });
+ expect(view.queryByRole('button', { name: 'Item list entry' })).toBeNull();
+ fireEvent.click(toggle);
+ const item = view.getByRole('button', { name: 'Item list entry' });
+ expect(gantt.visibleRange().start).toBe(anchor);
+ expect(viewport.scrollLeft).toBe(left);
+ expect(gantt.pointToDay(20)).toBeUndefined();
+ const wheel = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX: 20,
+ metaKey: true,
+ deltaY: -100,
+ });
+ fireEvent(item, wheel);
+ expect(wheel.defaultPrevented).toBe(true);
+ expect(gantt.pixelsPerDay()).toBe(20);
+ item.focus();
+ const consume = (event: KeyboardEvent) => event.preventDefault();
+ item.addEventListener('keydown', consume);
+ fireEvent.keyDown(item, { key: 'Escape' });
+ expect(gantt.sidebar.open()).toBe(true);
+ item.removeEventListener('keydown', consume);
+ fireEvent.keyDown(item, { key: 'Escape' });
+ expect(gantt.sidebar.open()).toBe(false);
+ expect(document.activeElement).toBe(toggle);
+ expect(gantt.visibleRange().start).toBe(anchor);
+});
+
+it('keeps the drawer open on chart clicks', async () => {
+ const view = chartFixture(1000, true);
+ await waitFor(() => expect(view.gantt.viewport()).toBe(view.viewport));
+ await Promise.resolve();
+ const bar = view.getByRole('button', { name: /^Timeline item:/ });
+ fireEvent(bar, new MouseEvent('pointerdown', { bubbles: true, button: 0 }));
+ expect(view.gantt.sidebar.open()).toBe(true);
+});
+
+it('bounds Ctrl/Cmd-wheel zoom while retaining the pointer date through rapid wheel events', async () => {
+ const { gantt, viewport } = chartFixture();
+ await waitFor(() => expect(gantt.viewport()).toBe(viewport));
+ await Promise.resolve();
+ await Promise.resolve();
+ const clientX = 760;
+ const day = () => gantt.pointToDay(clientX, undefined, false)!.day;
+ const anchor = day();
+ const wheel = (
+ deltaY: number,
+ ctrlKey = true,
+ deltaMode = 0,
+ metaKey = false
+ ) => {
+ const event = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX,
+ ctrlKey,
+ metaKey,
+ deltaY,
+ deltaMode,
+ });
+ fireEvent(viewport, event);
+ return event;
+ };
+ expect(wheel(-100, false).defaultPrevented).toBe(false);
+ expect(gantt.pixelsPerDay()).toBe(20);
+ expect(wheel(-100).defaultPrevented).toBe(true);
+ for (let i = 0; i < 12; i++) wheel(-100);
+ await Promise.resolve();
+ expect(gantt.pixelsPerDay()).toBe(MAX_GANTT_PIXELS_PER_DAY);
+ expect(day()).toBeCloseTo(anchor);
+ for (let i = 0; i < 12; i++) wheel(100);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(gantt.pixelsPerDay()).toBe(MIN_GANTT_PIXELS_PER_DAY);
+ expect(day()).toBeCloseTo(anchor);
+ expect(wheel(-100, false, 0, true).defaultPrevented).toBe(true);
+ await Promise.resolve();
+ expect(day()).toBeCloseTo(anchor);
+});
+
+it('preserves the date anchor through zoom, resizing, and loading earlier dates', async () => {
+ const { gantt, viewport, resize, setRange } = chartFixture();
+ await waitFor(() => expect(gantt.viewport()).toBe(viewport));
+ const anchor = gantt.visibleRange().start;
+ gantt.setScale('month');
+ await Promise.resolve();
+ expect(gantt.visibleRange().start).toBeCloseTo(anchor);
+ resize(1800);
+ setRange({ start: gantt.range().start - 20, end: gantt.range().end + 365 });
+ await Promise.resolve();
+ expect(gantt.visibleRange().start).toBeCloseTo(anchor);
+ expect(gantt.width() - viewport.clientWidth).toBeGreaterThanOrEqual(
+ viewport.scrollLeft
+ );
+});
+
+it('anchors zoom buttons to the calendar center and blocks them during active edits', async () => {
+ const { gantt, viewport } = chartFixture();
+ await waitFor(() => expect(gantt.viewport()).toBe(viewport));
+ const center = () =>
+ (gantt.visibleRange().start + gantt.visibleRange().end) / 2;
+ const anchor = center();
+ const zoom = screen.getByRole('button', { name: 'Zoom in' });
+ const reset = screen.getByRole('button', { name: 'Reset zoom' });
+ fireEvent.click(zoom);
+ await Promise.resolve();
+ expect(gantt.pixelsPerDay()).toBe(25);
+ expect(center()).toBeCloseTo(anchor);
+ fireEvent.click(reset);
+ await Promise.resolve();
+ expect(gantt.pixelsPerDay()).toBe(20);
+ expect(center()).toBeCloseTo(anchor);
+ gantt.setEditing(true);
+ for (const name of ['Zoom in', 'Zoom out', 'Reset zoom']) {
+ expect(screen.getByRole('button', { name }).hasAttribute('disabled')).toBe(
+ true
+ );
+ }
+});
+it('initializes Today after delayed measurement and respects reduced motion', async () => {
+ const { gantt, viewport, today, resize, setRange, container, scrollTo } =
+ chartFixture(0);
+ await Promise.resolve();
+ expect(viewport.scrollLeft).toBe(0);
+ resize(1200);
+ await waitFor(() =>
+ expect(
+ (gantt.visibleRange().start + gantt.visibleRange().end) / 2
+ ).toBeCloseTo(today + 0.5)
+ );
+ viewport.scrollLeft += 200;
+ fireEvent.scroll(viewport);
+ const anchor = gantt.visibleRange().start;
+ resize(1500);
+ setRange({ start: today - 200, end: today + 100 });
+ await Promise.resolve();
+ expect(gantt.visibleRange().start).toBeCloseTo(anchor);
+ viewport.scrollLeft =
+ (today + 1 - gantt.range().start) * gantt.pixelsPerDay();
+ fireEvent.scroll(viewport);
+ expect(container.querySelector('[data-gantt-today]')).toBeNull();
+ gantt.scrollToToday();
+ await waitFor(() =>
+ expect(
+ (gantt.visibleRange().start + gantt.visibleRange().end) / 2
+ ).toBeCloseTo(today + 0.5)
+ );
+ expect(scrollTo).toHaveBeenLastCalledWith({
+ left: viewport.scrollLeft,
+ behavior: 'smooth',
+ });
+ const left = viewport.scrollLeft;
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn(() => ({ matches: true }))
+ );
+ viewport.scrollLeft += 100;
+ fireEvent.scroll(viewport);
+ gantt.scrollToToday();
+ await Promise.resolve();
+ expect(viewport.scrollLeft).toBe(left);
+ expect(scrollTo).toHaveBeenCalledOnce();
+});
+
+it('pads the complete Today animation path without shifting its start or rebasing during animation frames', async () => {
+ const { gantt, viewport, scrollTo, today } = chartFixture();
+ await waitFor(() => expect(gantt.viewport()).toBe(viewport));
+ await Promise.resolve();
+ gantt.setScale('month');
+ await Promise.resolve();
+ viewport.scrollLeft += 200;
+ fireEvent.scroll(viewport);
+ const anchor = gantt.visibleRange().start;
+ let left = viewport.scrollLeft;
+ const writeScroll = vi.fn((value: number) => {
+ left = Math.max(
+ 0,
+ Math.min(value, viewport.scrollWidth - viewport.clientWidth)
+ );
+ });
+ Object.defineProperty(viewport, 'scrollLeft', {
+ get: () => left,
+ set: writeScroll,
+ });
+ scrollTo.mockImplementationOnce(() => {});
+ gantt.scrollToToday();
+ await Promise.resolve();
+ const days =
+ (viewport.clientWidth - gantt.labelWidth()) / gantt.pixelsPerDay();
+ const padding = Math.max(
+ 30,
+ Math.ceil(viewport.clientWidth / gantt.pixelsPerDay())
+ );
+ const destination = today + 0.5 - days / 2;
+ expect(gantt.range().start).toBeLessThanOrEqual(
+ Math.floor(Math.min(anchor, destination) - padding)
+ );
+ expect(gantt.range().end).toBeGreaterThanOrEqual(
+ Math.ceil(Math.max(anchor, destination) + days + padding)
+ );
+ expect(gantt.range().start + left / gantt.pixelsPerDay()).toBeCloseTo(anchor);
+ const animation = scrollTo.mock.calls[0][0];
+ expect(animation.behavior).toBe('smooth');
+ const start = left;
+ writeScroll.mockClear();
+ for (let frame = 1; frame <= 10; frame++) {
+ left = start + ((animation.left! - start) * frame) / 10;
+ fireEvent.scroll(viewport);
+ await Promise.resolve();
+ }
+ expect(writeScroll).not.toHaveBeenCalled();
+ expect(
+ (gantt.visibleRange().start + gantt.visibleRange().end) / 2
+ ).toBeCloseTo(today + 0.5);
+});
+function creationFixture(minDate?: string) {
+ const onCreate = vi.fn();
+ const [canCreate, setCanCreate] = createSignal(true);
+ const viewport = document.createElement('div');
+ Object.defineProperty(viewport, 'clientWidth', { value: 1000 });
+ viewport.getBoundingClientRect = () => new DOMRect(0, 0, 1000, 600);
+ let gantt!: ReturnType<typeof useGantt>;
+ const view = render(() =>
+ createComponent(Gantt.Root, {
+ range: { start: 0, end: 100 },
+ get children() {
+ return createComponent(() => {
+ gantt = useGantt();
+ gantt.setViewport(viewport);
+ gantt.updateViewport();
+ return [
+ viewport,
+ createComponent(Gantt.CreateArea, {
+ get onCreate() {
+ return canCreate() ? onCreate : undefined;
+ },
+ minDate,
+ }),
+ ];
+ }, {});
+ },
+ })
+ );
+ const pointer = (
+ target: Element | Window,
+ type: string,
+ x: number,
+ y = 200
+ ) => {
+ const event = new MouseEvent(type, {
+ bubbles: true,
+ button: 0,
+ clientX: x,
+ clientY: y,
+ });
+ Object.defineProperty(event, 'pointerId', { value: 1 });
+ fireEvent(target, event);
+ return event;
+ };
+ return { ...view, viewport, gantt, pointer, onCreate, setCanCreate };
+}
+
+it('opens a composer only after a completed range drag, including reverse selections', () => {
+ const { viewport, pointer, onCreate } = creationFixture();
+ pointer(viewport, 'pointerdown', 660);
+ pointer(window, 'pointermove', 580);
+ expect(onCreate).not.toHaveBeenCalled();
+ pointer(window, 'pointerup', 580);
+ expect(onCreate).toHaveBeenCalledOnce();
+ const dates = onCreate.mock.calls[0][0];
+ expect(toGanttDay(dates.start)).toBe(16);
+ expect(toGanttDay(dates.end)).toBe(20);
+});
+
+it('keeps creation within the host minimum date instead of creating reversed intervals', () => {
+ const { viewport, pointer, onCreate } = creationFixture('1970-01-21');
+ pointer(viewport, 'pointerdown', 500);
+ pointer(window, 'pointermove', 700);
+ pointer(window, 'pointerup', 700);
+ expect(onCreate).not.toHaveBeenCalled();
+ pointer(viewport, 'pointerdown', 700);
+ pointer(window, 'pointermove', 500);
+ pointer(window, 'pointerup', 500);
+ expect(toGanttDay(onCreate.mock.calls[0][0].start)).toBe(20);
+ expect(toGanttDay(onCreate.mock.calls[0][0].end)).toBe(22);
+});
+
+it.each(['blur', 'pointercancel', 'unmount', 'viewport-replacement'])(
+ 'cancels creation and invalidates queued callbacks on %s',
+ (reason) => {
+ const { viewport, gantt, pointer, onCreate, unmount } = creationFixture();
+ const events: EventTarget = window;
+ const listeners = vi.spyOn(events, 'addEventListener');
+ const removed = vi.spyOn(events, 'removeEventListener');
+ pointer(viewport, 'pointerdown', 500);
+ pointer(window, 'pointermove', 580);
+ expect(gantt.editing()).toBe(true);
+ const finish = listeners.mock.calls.find(
+ ([type]) => type === 'pointerup'
+ )?.[1];
+ const update = listeners.mock.calls.find(
+ ([type]) => type === 'pointermove'
+ )?.[1];
+ if (typeof finish !== 'function' || typeof update !== 'function')
+ throw new Error('Creation listeners were not registered');
+
+ switch (reason) {
+ case 'blur':
+ fireEvent.blur(window);
+ break;
+ case 'pointercancel':
+ pointer(window, 'pointercancel', 580);
+ break;
+ case 'unmount':
+ unmount();
+ break;
+ case 'viewport-replacement':
+ gantt.setViewport(document.createElement('div'));
+ break;
+ }
+ expect(gantt.editing()).toBe(false);
+ expect(removed).toHaveBeenCalledWith('pointerup', finish);
+ expect(removed).toHaveBeenCalledWith('pointermove', update);
+
+ gantt.setEditing(true);
+ update.call(window, pointer(window, 'pointermove', 620));
+ finish.call(window, pointer(window, 'pointerup', 620));
+ expect(onCreate).not.toHaveBeenCalled();
+ expect(gantt.editing()).toBe(true);
+ gantt.setEditing(false);
+ }
+);
+
+it('cancels range creation and ignores clicks, labels, bars, and header space', () => {
+ const { viewport, gantt, pointer, onCreate, setCanCreate } =
+ creationFixture();
+ pointer(viewport, 'pointerdown', 500);
+ pointer(window, 'pointermove', 580);
+ fireEvent.keyDown(window, { key: 'Escape' });
+ pointer(window, 'pointerup', 580);
+ expect(gantt.editing()).toBe(false);
+ pointer(viewport, 'pointerdown', 500);
+ pointer(window, 'pointerup', 500);
+ pointer(viewport, 'pointerdown', 200);
+ pointer(window, 'pointerup', 500);
+ pointer(viewport, 'pointerdown', 500, 30);
+ pointer(window, 'pointerup', 580, 30);
+ for (const attribute of [
+ 'data-gantt-label',
+ 'data-gantt-bar',
+ 'data-gantt-header',
+ 'data-gantt-pagination',
+ 'data-gantt-group-header',
+ ]) {
+ const item = document.createElement('div');
+ item.setAttribute(attribute, '');
+ viewport.append(item);
+ pointer(item, 'pointerdown', 500);
+ pointer(window, 'pointermove', 580);
+ pointer(window, 'pointerup', 580);
+ }
+ pointer(viewport, 'pointerdown', 500);
+ pointer(window, 'pointermove', 580);
+ setCanCreate(false);
+ pointer(window, 'pointerup', 580);
+ pointer(viewport, 'pointerdown', 500);
+ expect(gantt.editing()).toBe(false);
+ pointer(window, 'pointerup', 580);
+ setCanCreate(true);
+ expect(onCreate).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/components/gantt/gantt.tsx b/apps/web/src/components/gantt/gantt.tsx
new file mode 100644
index 0000000000..28099b3773
--- /dev/null
+++ b/apps/web/src/components/gantt/gantt.tsx
@@ -0,0 +1,441 @@
+import { cn } from '@ui';
+import {
+ batch,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onCleanup,
+ type ParentProps,
+ untrack,
+} from 'solid-js';
+import { createGanttToday } from './create-gantt-today';
+import { GanttBar } from './gantt-bar';
+import { GanttChart } from './gantt-chart';
+import {
+ GanttContextProvider as Context,
+ type GanttContext,
+ HEADER_HEIGHT,
+} from './gantt-context';
+import { GanttCreateArea } from './gantt-create-area';
+import {
+ type GanttRange,
+ type GanttScale,
+ ganttPixelsPerDay,
+ normalizeGanttRange,
+ toGanttDay,
+} from './gantt-date';
+import { GanttDropPreview } from './gantt-drop-preview';
+import {
+ GanttDragItem,
+ GanttGroupDrag,
+ GanttGroupDrop,
+} from './gantt-group-drag';
+import { GanttHeader } from './gantt-header';
+import {
+ extendGanttRange,
+ type GanttGuide,
+ snapGanttGuide,
+ zoomedGanttPixels,
+} from './gantt-interaction';
+import {
+ GanttDateHint,
+ GanttTodayButton,
+ GanttTodayMarker,
+} from './gantt-markers';
+import { GanttRow, GanttRows } from './gantt-rows';
+import { GanttSettings } from './gantt-settings';
+import {
+ GanttControls,
+ GanttGroupHeader,
+ GanttLabel,
+ GanttPagination,
+ GanttSidebarToggle,
+} from './gantt-sidebar';
+import { GanttZoomControls } from './gantt-zoom-controls';
+
+const SIDEBAR_COLLAPSE_WIDTH = 640;
+export function GanttRoot(
+ props: ParentProps<{
+ range: GanttRange;
+ defaultScale?: GanttScale;
+ labelWidth?: number;
+ rowHeight?: number;
+ class?: string;
+ }>
+) {
+ const today = createGanttToday();
+ const dataRange = createMemo(
+ () => normalizeGanttRange(props.range),
+ undefined,
+ {
+ equals: (left, right) =>
+ left.start === right.start && left.end === right.end,
+ }
+ );
+ const [pixelsPerDay, setPixelsPerDay] = createSignal(
+ ganttPixelsPerDay(props.defaultScale ?? 'week')
+ );
+ const scale = (): GanttScale =>
+ pixelsPerDay() >= 32 ? 'day' : pixelsPerDay() >= 12 ? 'week' : 'month';
+ const [gridVisible, setGridVisible] = createSignal(true);
+ const [gridScale, setGridScale] = createSignal<GanttScale>(
+ props.defaultScale ?? 'week'
+ );
+ const [gridStyle, setGridStyle] = createSignal<'solid' | 'dashed'>('solid');
+ const [viewport, setViewport] = createSignal<HTMLDivElement>();
+ const [extent, setExtent] = createSignal<GanttRange>();
+ const [guide, setGuide] = createSignal<GanttGuide>();
+ const [editing, setEditing] = createSignal(false);
+ const [sidebarChoice, setSidebarChoice] = createSignal<boolean>();
+ let sidebarTrigger: HTMLButtonElement | undefined;
+ const [scrollZooming, setScrollZooming] = createSignal(false);
+ let scrollZoomTimeout: ReturnType<typeof setTimeout> | undefined;
+ onCleanup(() => clearTimeout(scrollZoomTimeout));
+ let extending = false;
+ let scrollRevision = 0;
+ const [metrics, setMetrics] = createSignal({
+ left: 0,
+ width: 1_000,
+ start: dataRange().start,
+ pixels: ganttPixelsPerDay(props.defaultScale ?? 'week'),
+ });
+ const rowHeight = () => props.rowHeight ?? 40;
+ // Scroll changes do not resize the calendar; zoom, bounds, and viewport changes do.
+ const viewportWidth = createMemo(() => metrics().width);
+ const labelWidth = () => {
+ if (props.labelWidth !== undefined) return props.labelWidth;
+ const available = viewportWidth() || 1_000;
+ return Math.min(260, Math.max(128, available * 0.3), available / 2);
+ };
+ const sidebarWidth = () => Math.min(280, Math.max(0, viewportWidth() - 40));
+ const sidebarOpen = () =>
+ labelWidth() === 0 &&
+ (sidebarChoice() ?? (viewportWidth() || 1_000) >= SIDEBAR_COLLAPSE_WIDTH);
+ const restoreSidebarFocus = () => {
+ const focused = document.activeElement;
+ if (
+ viewport()?.contains(focused) &&
+ focused instanceof Element &&
+ focused.closest('[data-gantt-label]')
+ ) {
+ sidebarTrigger?.focus({ preventScroll: true });
+ }
+ };
+ const changeSidebar = (open: boolean) => {
+ if (open && editing()) return;
+ if (!open) restoreSidebarFocus();
+ setGuide(undefined);
+ setSidebarChoice(open);
+ };
+ const range = createMemo(() => {
+ const data = dataRange();
+ const extended = extent();
+ const bounds = {
+ start: Math.min(data.start, extended?.start ?? data.start),
+ end: Math.max(data.end, extended?.end ?? data.end),
+ };
+ const days = Math.max(1, viewportWidth() - labelWidth()) / pixelsPerDay();
+ const previous = untrack(metrics);
+ const anchor = previous.start + previous.left / previous.pixels;
+ return {
+ start: bounds.start,
+ end: Math.max(
+ bounds.end,
+ Math.ceil(Math.max(bounds.start, anchor) + days)
+ ),
+ };
+ });
+ const width = () =>
+ labelWidth() + (range().end - range().start) * pixelsPerDay();
+ const updateViewport = () => {
+ const element = viewport();
+ if (!element) return;
+ const wasOpen = sidebarOpen();
+ if (
+ sidebarChoice() === undefined &&
+ wasOpen &&
+ element.clientWidth > 0 &&
+ element.clientWidth < SIDEBAR_COLLAPSE_WIDTH
+ ) {
+ restoreSidebarFocus();
+ }
+ setMetrics({
+ left: element.scrollLeft,
+ width: element.clientWidth,
+ start: range().start,
+ pixels: pixelsPerDay(),
+ });
+ if (wasOpen !== sidebarOpen()) setGuide(undefined);
+ extendViewport();
+ };
+ const extendViewport = () => {
+ const element = viewport();
+ if (
+ !element ||
+ extending ||
+ !element.clientWidth ||
+ Math.abs(element.scrollWidth - width()) > 1
+ )
+ return;
+ const next = extendGanttRange(
+ range(),
+ element.scrollLeft,
+ element.clientWidth,
+ element.scrollWidth,
+ pixelsPerDay()
+ );
+ if (next) extendBounds(next);
+ };
+ function extendBounds(next: GanttRange) {
+ const element = viewport();
+ const current = range();
+ if (!element || (next.start === current.start && next.end === current.end))
+ return;
+ const left = element.scrollLeft;
+ const pixels = pixelsPerDay();
+ extending = true;
+ ++scrollRevision;
+ try {
+ // Commit the new DOM width before compensating, or the browser clamps the offset.
+ setExtent(next);
+ if (range().start !== current.start) {
+ element.scrollLeft = left + (current.start - range().start) * pixels;
+ }
+ updateViewport();
+ } finally {
+ extending = false;
+ }
+ }
+ const visibleRange = () => {
+ const current = metrics();
+ const start = current.start + current.left / current.pixels;
+ return {
+ start,
+ end: start + Math.max(1, current.width - labelWidth()) / pixelsPerDay(),
+ };
+ };
+
+ function restoreScroll(anchor: number, behavior: ScrollBehavior = 'instant') {
+ const element = viewport();
+ if (!element) return;
+ const revision = ++scrollRevision;
+ queueMicrotask(() => {
+ if (viewport() !== element || revision !== scrollRevision) return;
+ const left = Math.max(0, (anchor - range().start) * pixelsPerDay());
+ const reducedMotion = window.matchMedia?.(
+ '(prefers-reduced-motion: reduce)'
+ ).matches;
+ if (behavior === 'smooth' && !reducedMotion) {
+ element.scrollTo({ left, behavior });
+ } else {
+ element.scrollLeft = left;
+ }
+ updateViewport();
+ });
+ }
+ // Preserve the visible calendar position when zooming or loading older items.
+ createEffect(
+ on(
+ () => [range().start, pixelsPerDay()] as const,
+ (_, previous) => {
+ if (!viewport() || !previous || extending) return;
+ const current = metrics();
+ restoreScroll(current.start + current.left / current.pixels);
+ }
+ )
+ );
+
+ const context: GanttContext = {
+ today,
+ range,
+ scale,
+ setScale: (value) => setPixelsPerDay(ganttPixelsPerDay(value)),
+ pixelsPerDay,
+ scrollZooming,
+ markScrollZoom: () => {
+ if (editing()) return;
+ clearTimeout(scrollZoomTimeout);
+ setScrollZooming(true);
+ scrollZoomTimeout = setTimeout(() => setScrollZooming(false), 800);
+ },
+ zoomAt: (clientX, delta) => {
+ const element = viewport();
+ if (!element || extending || editing() || !Number.isFinite(delta)) return;
+ const next = zoomedGanttPixels(pixelsPerDay(), delta);
+ if (next === pixelsPerDay()) return;
+ const offset = Math.max(
+ 0,
+ Math.min(
+ clientX - element.getBoundingClientRect().left - labelWidth(),
+ element.clientWidth - labelWidth()
+ )
+ );
+ const current = metrics();
+ const first = current.start + current.left / current.pixels;
+ const anchor = first + offset / pixelsPerDay() - offset / next;
+ const currentRange = range();
+ const start =
+ anchor < currentRange.start
+ ? Math.floor(anchor) - Math.ceil(element.clientWidth / next)
+ : currentRange.start;
+ // Keep logical metrics current for consecutive wheel events before DOM synchronization.
+ batch(() => {
+ if (start < currentRange.start) {
+ setExtent({ start, end: currentRange.end });
+ }
+ setMetrics({
+ ...current,
+ left: Math.max(0, (anchor - start) * next),
+ start,
+ pixels: next,
+ });
+ setPixelsPerDay(next);
+ });
+ },
+ gridVisible,
+ setGridVisible,
+ gridScale,
+ setGridScale,
+ gridStyle,
+ setGridStyle,
+ labelWidth,
+ rowHeight,
+ sidebar: {
+ open: sidebarOpen,
+ width: sidebarWidth,
+ setOpen: changeSidebar,
+ setTrigger: (element) => {
+ sidebarTrigger = element;
+ },
+ },
+ width,
+ visibleRange,
+ viewport,
+ setViewport,
+ updateViewport,
+ panBy: (deltaX, deltaY) => {
+ const element = viewport();
+ if (!element) return;
+ const current = range();
+ const pixels = pixelsPerDay();
+ const anchor = current.start + (element.scrollLeft + deltaX) / pixels;
+ const days = Math.max(1, element.clientWidth - labelWidth()) / pixels;
+ const padding = Math.max(30, Math.ceil(element.clientWidth / pixels));
+ // Reserve the desired dates before the browser can clamp the drag distance.
+ extendBounds({
+ start:
+ anchor < current.start ? Math.floor(anchor) - padding : current.start,
+ end:
+ anchor + days > current.end
+ ? Math.ceil(anchor + days) + padding
+ : current.end,
+ });
+ element.scrollLeft = (anchor - range().start) * pixels;
+ element.scrollTop += deltaY;
+ updateViewport();
+ },
+ guide,
+ setGuide,
+ editing,
+ setEditing,
+ pointToDay: (clientX, exclude, snap = true) => {
+ const element = viewport();
+ if (!element || extending) return;
+ const rect = element.getBoundingClientRect();
+ const x = clientX - rect.left;
+ if (x < labelWidth() || (sidebarOpen() && x < sidebarWidth())) return;
+ const day =
+ range().start +
+ (element.scrollLeft + Math.min(x, rect.width) - labelWidth()) /
+ pixelsPerDay();
+ if (!snap) return { day };
+ const targets = [
+ ...element.querySelectorAll<HTMLElement>('[data-gantt-bar]'),
+ ].flatMap((bar) => {
+ if (bar === exclude) return [];
+ const box = bar.getBoundingClientRect();
+ if (box.bottom <= rect.top + HEADER_HEIGHT || box.top >= rect.bottom)
+ return [];
+ const start = Number(bar.dataset.ganttStart);
+ const end =
+ bar.dataset.ganttEnd === undefined
+ ? undefined
+ : Number(bar.dataset.ganttEnd);
+ return Number.isFinite(start) ? [{ start, end }] : [];
+ });
+ return snapGanttGuide(day, pixelsPerDay(), targets);
+ },
+ scrollToToday: (behavior = 'smooth') => {
+ const element = viewport();
+ const today = toGanttDay(new Date());
+ if (!element || today === undefined) return;
+ const pixels = pixelsPerDay();
+ const days = Math.max(1, element.clientWidth - labelWidth()) / pixels;
+ const anchor = range().start + element.scrollLeft / pixels;
+ const destination = today + 0.5 - days / 2;
+ const padding = Math.max(30, Math.ceil(element.clientWidth / pixels));
+ const current = range();
+ // Reserve the complete animation path so no edge rebase interrupts smooth scrolling.
+ extendBounds({
+ start: Math.min(
+ current.start,
+ Math.floor(Math.min(anchor, destination) - padding)
+ ),
+ end: Math.max(
+ current.end,
+ Math.ceil(Math.max(anchor, destination) + days + padding)
+ ),
+ });
+ restoreScroll(destination, behavior);
+ },
+ };
+
+ return (
+ <Context.Provider value={context}>
+ <div
+ class={cn(
+ 'relative flex size-full min-h-0 min-w-0 flex-col overflow-hidden',
+ props.class
+ )}
+ onKeyDown={(event) => {
+ if (
+ event.key !== 'Escape' ||
+ event.defaultPrevented ||
+ editing() ||
+ !sidebarOpen()
+ )
+ return;
+ event.preventDefault();
+ changeSidebar(false);
+ }}
+ >
+ {props.children}
+ </div>
+ </Context.Provider>
+ );
+}
+
+export const Gantt = {
+ Root: GanttRoot,
+ TodayButton: GanttTodayButton,
+ Settings: GanttSettings,
+ SidebarToggle: GanttSidebarToggle,
+ Controls: GanttControls,
+ Pagination: GanttPagination,
+ ZoomControls: GanttZoomControls,
+ Chart: GanttChart,
+ Header: GanttHeader,
+ Rows: GanttRows,
+ Row: GanttRow,
+ GroupDrag: GanttGroupDrag,
+ DragItem: GanttDragItem,
+ GroupDrop: GanttGroupDrop,
+ DropPreview: GanttDropPreview,
+ GroupHeader: GanttGroupHeader,
+ Label: GanttLabel,
+ DateHint: GanttDateHint,
+ CreateArea: GanttCreateArea,
+ Bar: GanttBar,
+ TodayMarker: GanttTodayMarker,
+};
diff --git a/apps/web/src/components/ui/components/Scroll.tsx b/apps/web/src/components/ui/components/Scroll.tsx
index ed01ae1730..6639df9361 100644
--- a/apps/web/src/components/ui/components/Scroll.tsx
+++ b/apps/web/src/components/ui/components/Scroll.tsx
@@ -33,6 +33,8 @@ type ScrollProps = JSX.HTMLAttributes<HTMLDivElement> & {
orientation?: Axis | 'both';
/** Which custom scrollbars to show when their content overflows. */
scrollbars?: Axis | 'both' | 'none';
+ /** Reserve space above the vertical scrollbar without changing the scroll viewport. */
+ verticalScrollbarInset?: number;
autoHide?: boolean;
autoHideDelay?: number;
/** Opt in to hover-only reveal instead of revealing on scrolling and mount. */
@@ -75,6 +77,7 @@ export function Scroll(props: ScrollProps) {
'orientation',
'scrollbars',
'autoHide',
+ 'verticalScrollbarInset',
'autoHideDelay',
'revealOn',
'hovered',
@@ -105,6 +108,15 @@ export function Scroll(props: ScrollProps) {
return enabled(axis) && (visibility === 'both' || visibility === axis);
};
+ const verticalInset = (corner: number) => {
+ const inset = local.verticalScrollbarInset ?? 0;
+ return Number.isFinite(inset)
+ ? Math.min(
+ Math.max(0, inset),
+ Math.max(0, (viewport?.clientHeight ?? 0) - corner)
+ )
+ : 0;
+ };
function configure() {
if (!viewport) {
return;
@@ -120,7 +132,8 @@ export function Scroll(props: ScrollProps) {
const overflow = horizontal ? x : y;
const otherOverflow = horizontal ? y : x;
const corner = shown(other) && otherOverflow > 0 ? GUTTER : 0;
- const track = Math.max(0, length - corner - INSET * 2);
+ const inset = horizontal ? 0 : verticalInset(corner);
+ const track = Math.max(0, length - corner - inset - INSET * 2);
const size = Math.min(
track,
Math.max(MIN_THUMB, total ? (track * length) / total : track)
@@ -187,6 +200,7 @@ export function Scroll(props: ScrollProps) {
createEffect(() => {
local.orientation;
local.scrollbars;
+ local.verticalScrollbarInset;
local.autoHide;
local.autoHideDelay;
configure();
@@ -391,7 +405,7 @@ export function Scroll(props: ScrollProps) {
right: horizontal ? `${corner()}px` : '0',
bottom: horizontal ? '0' : `${corner()}px`,
left: horizontal ? '0' : undefined,
- top: horizontal ? undefined : '0',
+ top: horizontal ? undefined : `${verticalInset(corner())}px`,
width: horizontal ? undefined : `${GUTTER}px`,
height: horizontal ? `${GUTTER}px` : undefined,
'touch-action': 'none',
diff --git a/apps/web/src/components/view-shell/ListDropdowns.tsx b/apps/web/src/components/view-shell/ListDropdowns.tsx
index 3e8cfac7ef..25a4dd81bc 100644
--- a/apps/web/src/components/view-shell/ListDropdowns.tsx
+++ b/apps/web/src/components/view-shell/ListDropdowns.tsx
@@ -2,6 +2,7 @@ import {
FilterSubmenu,
SearchableFilterSubmenu,
} from '@app/features/next-soup/soup-view/filters-bar/filter-menu';
+import GanttIcon from '@phosphor/chart-bar-horizontal.svg';
import CheckIcon from '@phosphor/check.svg';
import FilterIcon from '@phosphor/funnel-simple.svg';
import BoardIcon from '@phosphor/kanban.svg';
@@ -93,18 +94,20 @@ function SingleSelectDropdown<TId extends string>(
);
}
-export type ViewLayout = 'list' | 'board';
+export type ViewLayout = 'list' | 'board' | 'gantt';
export type ViewLayoutDropdownProps = Omit<
SingleSelectDropdownProps<ViewLayout>,
'icon' | 'label' | 'options'
> & {
label?: string;
+ layouts?: readonly ViewLayout[];
};
const VIEW_LAYOUT_OPTIONS: ListControlOption<ViewLayout>[] = [
{ id: 'list', label: 'List', icon: () => <ListIcon /> },
{ id: 'board', label: 'Board', icon: () => <BoardIcon /> },
+ { id: 'gantt', label: 'Gantt', icon: () => <GanttIcon /> },
];
export function ViewLayoutDropdown(props: ViewLayoutDropdownProps) {
@@ -112,10 +115,19 @@ export function ViewLayoutDropdown(props: ViewLayoutDropdownProps) {
<SingleSelectDropdown
{...props}
label={props.label ?? 'Layout'}
- options={VIEW_LAYOUT_OPTIONS}
+ options={VIEW_LAYOUT_OPTIONS.filter(
+ (option) => !props.layouts || props.layouts.includes(option.id)
+ )}
icon={
- <Show when={props.value === 'board'} fallback={<ListIcon />}>
- <BoardIcon />
+ <Show
+ when={props.value === 'gantt'}
+ fallback={
+ <Show when={props.value === 'board'} fallback={<ListIcon />}>
+ <BoardIcon />
+ </Show>
+ }
+ >
+ <GanttIcon />
</Show>
}
/>
diff --git a/apps/web/src/features/block-md/component/ComposeTask.tsx b/apps/web/src/features/block-md/component/ComposeTask.tsx
index b2703b1253..5d99e2f1b3 100644
--- a/apps/web/src/features/block-md/component/ComposeTask.tsx
+++ b/apps/web/src/features/block-md/component/ComposeTask.tsx
@@ -349,6 +349,8 @@ export interface ComposeTaskProps {
initialAssigneeIds?: string[];
/** Start in this project, e.g. when composing from the project's page. */
initialProjectId?: string;
+ /** Prefill the visible Due Date control when creating from a timeline. */
+ initialDueDate?: Date;
/**
* When provided, replaces the default success behavior (auto-copy link +
* toast) so the caller can handle the created task however it needs.
@@ -383,18 +385,24 @@ export function ComposeTask(props: ComposeTaskProps) {
return defaultTaskPropertyValues(ids);
};
- // A project the composer opens in applies on top of a restored draft too.
- const withInitialProject = (
+ // Contextual project and date values apply without discarding a restored draft.
+ const withInitialProperties = (
values: Record<string, PropertyApiValues>
- ): Record<string, PropertyApiValues> =>
- props.initialProjectId
- ? {
- ...values,
- [SYSTEM_PROPERTY_IDS.PROJECT]: taskComposerProjectValue(
- props.initialProjectId
- ),
- }
- : values;
+ ): Record<string, PropertyApiValues> => {
+ const next = { ...values };
+ if (props.initialProjectId) {
+ next[SYSTEM_PROPERTY_IDS.PROJECT] = taskComposerProjectValue(
+ props.initialProjectId
+ );
+ }
+ if (props.initialDueDate) {
+ next[SYSTEM_PROPERTY_IDS.DUE_DATE] = {
+ valueType: 'DATE',
+ value: props.initialDueDate,
+ };
+ }
+ return next;
+ };
// draft init logic
const initializeFromDraft = () => {
@@ -409,7 +417,7 @@ export function ComposeTask(props: ComposeTaskProps) {
title: draft.title,
content: draft.content,
editorState: draft.editorState,
- propertyValues: withInitialProject(draft.propertyValues),
+ propertyValues: withInitialProperties(draft.propertyValues),
isDraftLoaded: true,
};
}
@@ -418,7 +426,7 @@ export function ComposeTask(props: ComposeTaskProps) {
title: props.initialTitle ?? '',
content: props.initialContent ?? '',
editorState: undefined,
- propertyValues: withInitialProject(getDefaultPropertyValues()),
+ propertyValues: withInitialProperties(getDefaultPropertyValues()),
isDraftLoaded: false,
};
};
@@ -790,7 +798,7 @@ export function ComposeTask(props: ComposeTaskProps) {
setTitle('');
setContent('');
setPropertyValues(
- reconcile(withInitialProject(getDefaultPropertyValues()))
+ reconcile(withInitialProperties(getDefaultPropertyValues()))
);
setTagLayoutMode('bottom');
setIsDraftLoaded(false);
diff --git a/apps/web/src/features/projects/core/project.ts b/apps/web/src/features/projects/core/project.ts
index 0dbb1c18e8..cd6c5da836 100644
--- a/apps/web/src/features/projects/core/project.ts
+++ b/apps/web/src/features/projects/core/project.ts
@@ -3,6 +3,7 @@ export type Project = {
id: string;
name: string;
updatedAt: string;
+ createdAt?: string;
access?: ProjectAccess;
taskCount?: number;
completedTaskCount?: number;
diff --git a/apps/web/src/features/projects/primitives/project-collection.ts b/apps/web/src/features/projects/primitives/project-collection.ts
index 5e998cea72..2d8af48755 100644
--- a/apps/web/src/features/projects/primitives/project-collection.ts
+++ b/apps/web/src/features/projects/primitives/project-collection.ts
@@ -27,6 +27,7 @@ export type ProjectListGroupBy = 'none' | 'status' | 'priority' | 'assignee';
export type ProjectListActivation = { event?: MouseEvent; newSplit?: boolean };
export type ProjectCollectionSnapshot = {
+ layout?: 'list' | 'gantt';
search: string;
status: string;
priority: string;
@@ -53,6 +54,9 @@ export function createProjectCollection(capabilities: {
captureState?: (read: Accessor<ProjectCollectionSnapshot>) => void;
}) {
const initial = capabilities.initialState;
+ const [layout, setLayout] = createSignal<'list' | 'gantt'>(
+ initial?.layout ?? 'list'
+ );
const [search, setSearch] = createSignal(initial?.search ?? '');
const query = debouncedDependent(search, 150);
const [status, setStatus] = createSignal(initial?.status ?? '');
@@ -193,6 +197,7 @@ export function createProjectCollection(capabilities: {
},
});
capabilities.captureState?.(() => ({
+ layout: layout(),
search: search(),
status: status(),
priority: priority(),
@@ -206,6 +211,8 @@ export function createProjectCollection(capabilities: {
focusKey: list.focus.key(),
}));
return {
+ layout,
+ setLayout: (value: 'list' | 'gantt') => setLayout(value),
state,
search,
setSearch,
diff --git a/apps/web/src/features/projects/primitives/project-gantt-rows.ts b/apps/web/src/features/projects/primitives/project-gantt-rows.ts
new file mode 100644
index 0000000000..e277134d20
--- /dev/null
+++ b/apps/web/src/features/projects/primitives/project-gantt-rows.ts
@@ -0,0 +1,67 @@
+import {
+ buildGroupedSoupRows,
+ isSoupRowVisible,
+} from '@app/features/soup/collection/rows';
+import type { SoupGroup } from '@app/features/soup/collection/types';
+import type { Property } from '@property/types';
+import { type Accessor, createMemo } from 'solid-js';
+import type {
+ ProjectListEntity,
+ ProjectListGroupBy,
+ ProjectListItem,
+} from './project-collection';
+
+/** Gantt-only destinations; the ordinary list keeps its existing loaded groups. */
+export function createProjectGanttRows(options: {
+ grouping: Accessor<ProjectListGroupBy>;
+ groups: Accessor<readonly SoupGroup<ProjectListEntity>[]>;
+ items: Accessor<readonly ProjectListItem[]>;
+ property: Accessor<Property | undefined>;
+ scope: Accessor<string>;
+ isExpanded: (id: string) => boolean;
+}) {
+ // Remember assignees seen in this scope, including a group emptied by a move.
+ const assignees = createMemo<{ scope: string; ids: string[] }>((previous) => {
+ const scope = options.scope();
+ if (options.grouping() !== 'assignee') return { scope, ids: [] };
+ const ids = previous?.scope === scope ? previous.ids.slice() : [];
+ for (const group of options.groups()) {
+ if (group.id && !ids.includes(group.id)) ids.push(group.id);
+ }
+ return { scope, ids };
+ });
+ const groups = createMemo<SoupGroup<ProjectListEntity>[]>(() => {
+ const grouping = options.grouping();
+ if (grouping === 'none') return [];
+ const current = new Map(options.groups().map((group) => [group.id, group]));
+ const add = (id: string, label: string) => {
+ if (!current.has(id))
+ current.set(id, { id, label, count: 0, entities: [] });
+ };
+ const property = options.property();
+ if (grouping === 'assignee') {
+ for (const id of assignees().ids) add(id, id);
+ } else if (property?.valueType === 'SELECT_STRING') {
+ for (const option of property.options ?? []) {
+ if (option.value.type === 'string') add(option.id, option.value.value);
+ }
+ }
+ if (!property?.isRequired) {
+ add('', grouping === 'assignee' ? 'Unassigned' : `No ${grouping}`);
+ }
+ return [...current.values()];
+ });
+ const items = createMemo<ProjectListItem[]>(() => {
+ const current = options.items();
+ if (options.grouping() === 'none') return [...current];
+ return [
+ ...buildGroupedSoupRows(groups()).filter((row) =>
+ isSoupRowVisible(row, options.isExpanded)
+ ),
+ ...current.filter(
+ (row) => row.kind === 'load-more' && row.groupId === undefined
+ ),
+ ];
+ });
+ return { groups, items };
+}
diff --git a/apps/web/src/features/projects/project-collection-persistence.ts b/apps/web/src/features/projects/project-collection-persistence.ts
index 883e5e2fb3..29eb32da8e 100644
--- a/apps/web/src/features/projects/project-collection-persistence.ts
+++ b/apps/web/src/features/projects/project-collection-persistence.ts
@@ -5,6 +5,7 @@ import type { ProjectCollectionSnapshot } from './primitives/project-collection'
const ENTRY_KEY = 'initiatives.collection';
const snapshotSchema = z.object({
+ layout: z.enum(['list', 'gantt']).default('list'),
search: z.string(),
status: z.string(),
priority: z.string(),
diff --git a/apps/web/src/features/projects/project-collection-search.ts b/apps/web/src/features/projects/project-collection-search.ts
new file mode 100644
index 0000000000..d5e4a7dfa0
--- /dev/null
+++ b/apps/web/src/features/projects/project-collection-search.ts
@@ -0,0 +1,11 @@
+import { z } from 'zod';
+
+export const projectCollectionSearch = {
+ namespace: 'projects',
+ schema: z.object({
+ layout: z.enum(['list', 'gantt']).optional(),
+ }),
+ defaults: {
+ layout: undefined as 'list' | 'gantt' | undefined,
+ },
+};
diff --git a/apps/web/src/features/projects/project-detail.tsx b/apps/web/src/features/projects/project-detail.tsx
index 8b8086776c..24cf1219c8 100644
--- a/apps/web/src/features/projects/project-detail.tsx
+++ b/apps/web/src/features/projects/project-detail.tsx
@@ -212,7 +212,7 @@ function ProjectDetailHost(props: ProjectDetailProps) {
route: projectDetailRoute,
params: { projectId: props.route.id, section },
});
- const createTask = () => {
+ const createTask = (dueDate?: Date) => {
const projectId = props.route.id;
layout.popoverSplit({
type: 'component',
@@ -222,6 +222,7 @@ function ProjectDetailHost(props: ProjectDetailProps) {
...args: Parameters<NonNullable<ComposeTaskProps['createTask']>>
) => commands.createTask(projectId, ...args),
initialProjectId: projectId,
+ initialDueDate: dueDate,
onSuccess: () => section('tasks'),
},
});
diff --git a/apps/web/src/features/projects/projects.tsx b/apps/web/src/features/projects/projects.tsx
index 610c5c7810..97aa62295f 100644
--- a/apps/web/src/features/projects/projects.tsx
+++ b/apps/web/src/features/projects/projects.tsx
@@ -4,14 +4,16 @@ import {
makeCopyLinkAction,
} from '@app/features/next-soup/actions';
import { ShowFeatureFlag, useFeatureFlag } from '@app/lib/analytics/posthog';
+import { createSearchParams } from '@app/lib/split-router';
import { globalSplitManager } from '@app/signal/splitLayout';
import { useSplitLayout } from '@components/app/split-layout/layout';
import {
useSplitPanelOrThrow,
withSplitPanelOwner,
} from '@components/app/split-layout/layoutUtils';
-import { enableProjects } from '@core/constant/featureFlags';
+import { enableGantt, enableProjects } from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
+import { usePropertyUserDisplay } from '@property/hooks/usePropertyUserDisplay';
import { queryClient } from '@queries/client';
import {
getGraphqlSoupCacheHost,
@@ -20,8 +22,10 @@ import {
import { initiativeClient } from '@service-storage/initiative';
import { Button } from '@ui';
import {
+ createEffect,
createSignal,
ErrorBoundary,
+ on,
onCleanup,
type ParentProps,
Show,
@@ -37,6 +41,7 @@ import {
type ProjectListActivation,
} from './primitives/project-collection';
import { createProjectCollectionPersistence } from './project-collection-persistence';
+import { projectCollectionSearch } from './project-collection-search';
import { ProjectShareLauncher } from './project-share';
import { createProjectSources } from './queries/project-sources';
import { ProjectAssignment } from './views/project-assignment';
@@ -118,6 +123,8 @@ function ProjectsCollectionHost(props: {
const panel = useSplitPanelOrThrow();
const layout = useSplitLayout();
const context = useProjectsContext();
+ const ganttFlag = useFeatureFlag(enableGantt);
+ const [search, setSearch] = createSearchParams(projectCollectionSearch);
const activation = withSplitPanelOwner(
listOwnedSlotName('initiatives:activation'),
() => ({
@@ -142,6 +149,22 @@ function ProjectsCollectionHost(props: {
onOpen: (id, metadata) => activation.current?.(id, metadata),
})
);
+ // URL history restores the entry snapshot, not the latest layout selection.
+ const entryLayout = collection.layout();
+ createEffect(
+ on(
+ () => search.layout,
+ (layout) => collection.setLayout(layout ?? entryLayout)
+ )
+ );
+ const displayCollection = {
+ ...collection,
+ setLayout: (layout: 'list' | 'gantt') => {
+ const selected = collection.setLayout(layout);
+ setSearch({ layout: selected });
+ return selected;
+ },
+ };
const copyLink = makeCopyLinkAction();
const copyId = makeCopyEntityIdAction();
const [sharing, setSharing] = createSignal<string>();
@@ -149,9 +172,15 @@ function ProjectsCollectionHost(props: {
<>
<ProjectsCollection
onOpen={open}
- collection={collection}
- onCreate={() =>
- layout.popoverSplit({ type: 'component', id: 'project-compose' })
+ collection={displayCollection}
+ ganttEnabled={ganttFlag().enabled}
+ createAssigneeName={(id) => usePropertyUserDisplay(id).name}
+ onCreate={(initialDraft) =>
+ layout.popoverSplit({
+ type: 'component',
+ id: 'project-compose',
+ params: initialDraft ? { initialDraft } : undefined,
+ })
}
scopeId={panel.splitHotkeyScope}
isActive={panel.isPanelActive}
diff --git a/apps/web/src/features/projects/queries/project-group-move.ts b/apps/web/src/features/projects/queries/project-group-move.ts
new file mode 100644
index 0000000000..232be36b0c
--- /dev/null
+++ b/apps/web/src/features/projects/queries/project-group-move.ts
@@ -0,0 +1,61 @@
+import type { GanttGroupMove } from '@app/components/gantt/gantt-group-drag';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import type { Property, PropertyApiValues } from '@property/types';
+import type { ProjectListGroupBy } from '../primitives/project-collection';
+
+export function projectGroupPropertyId(
+ grouping: ProjectListGroupBy
+): string | undefined {
+ return {
+ none: undefined,
+ status: SYSTEM_PROPERTY_IDS.STATUS,
+ priority: SYSTEM_PROPERTY_IDS.PRIORITY,
+ assignee: SYSTEM_PROPERTY_IDS.ASSIGNEES,
+ }[grouping];
+}
+
+/** Replace only the dragged assignee occurrence; keep all other references intact. */
+export function projectGroupMoveValue(
+ properties: readonly Property[],
+ grouping: ProjectListGroupBy,
+ move: GanttGroupMove
+): PropertyApiValues | undefined {
+ if (grouping === 'none' || move.fromGroup === move.toGroup) return;
+ const property = properties.find(
+ (value) => value.propertyDefinitionId === projectGroupPropertyId(grouping)
+ );
+ if (grouping !== 'assignee') {
+ const current =
+ property?.valueType === 'SELECT_STRING'
+ ? (property.value?.[0] ?? '')
+ : '';
+ if (current !== move.fromGroup) return;
+ return {
+ valueType: 'SELECT_STRING',
+ values: move.toGroup ? [move.toGroup] : null,
+ };
+ }
+ const refs = property?.valueType === 'ENTITY' ? (property.value ?? []) : [];
+ const users = refs.filter((ref) => ref.entity_type === 'USER');
+ if (
+ move.fromGroup
+ ? !users.some((ref) => ref.entity_id === move.fromGroup)
+ : users.length > 0
+ )
+ return;
+ if (!move.toGroup) {
+ // Unassigned cannot retain another assignment or discard unrelated references.
+ if (
+ refs.some(
+ (ref) => ref.entity_type !== 'USER' || ref.entity_id !== move.fromGroup
+ )
+ )
+ return;
+ return { valueType: 'ENTITY', refs: null };
+ }
+ const next = refs.filter((ref) => ref.entity_id !== move.fromGroup);
+ if (!next.some((ref) => ref.entity_id === move.toGroup)) {
+ next.push({ entity_id: move.toGroup, entity_type: 'USER' });
+ }
+ return { valueType: 'ENTITY', refs: next };
+}
diff --git a/apps/web/src/features/projects/queries/project-soup.test.ts b/apps/web/src/features/projects/queries/project-soup.test.ts
index 3659ed48e0..0bee044725 100644
--- a/apps/web/src/features/projects/queries/project-soup.test.ts
+++ b/apps/web/src/features/projects/queries/project-soup.test.ts
@@ -276,6 +276,7 @@ describe('project Soup source', () => {
id: 'launch',
name: 'launch',
updatedAt: '2026-09-27',
+ createdAt: '2026-09-26',
access: 'edit',
},
properties: [],
diff --git a/apps/web/src/features/projects/queries/project-soup.ts b/apps/web/src/features/projects/queries/project-soup.ts
index d82974960b..454d873a11 100644
--- a/apps/web/src/features/projects/queries/project-soup.ts
+++ b/apps/web/src/features/projects/queries/project-soup.ts
@@ -101,6 +101,7 @@ export function projectSoupRows(
id: item.id,
name: item.displayName ?? 'Untitled project',
updatedAt: item.metadata.updatedAt ?? '',
+ createdAt: item.metadata.createdAt ?? undefined,
access:
permission?.__typename === 'GraphqlAccessLevelPermission'
? accessLevels[permission.accessLevel]
diff --git a/apps/web/src/features/projects/queries/project-timeline.ts b/apps/web/src/features/projects/queries/project-timeline.ts
new file mode 100644
index 0000000000..29a17195de
--- /dev/null
+++ b/apps/web/src/features/projects/queries/project-timeline.ts
@@ -0,0 +1,17 @@
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import type { Property } from '@property/types';
+import type { Project } from '../core/project';
+
+export function projectTimelineDates(row: {
+ project: Project;
+ properties: readonly Property[];
+}) {
+ const due = row.properties.find(
+ (property) => property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.DUE_DATE
+ );
+
+ return {
+ start: row.project.createdAt,
+ end: due?.valueType === 'DATE' ? due.value : undefined,
+ };
+}
diff --git a/apps/web/src/features/projects/views/project-tasks-list.tsx b/apps/web/src/features/projects/views/project-tasks-list.tsx
index 4cd8345d71..d2c7d8b32a 100644
--- a/apps/web/src/features/projects/views/project-tasks-list.tsx
+++ b/apps/web/src/features/projects/views/project-tasks-list.tsx
@@ -15,6 +15,7 @@ import { createProjectTasksDataSource } from '../queries/project-tasks';
export type ProjectTasksProviderProps = ParentProps<{
projectId: string;
onOpenTask: NonNullable<TasksViewProviderProps['onOpenTask']>;
+ onCreateTask?: (dueDate?: Date) => void;
}>;
export type ProjectTasksListProps = Omit<
@@ -22,7 +23,6 @@ export type ProjectTasksListProps = Omit<
'children'
> & {
projectName: string;
- onCreateTask?: () => void;
addTasksAction?: JSX.Element;
};
@@ -38,6 +38,7 @@ export function ProjectTasksProvider(props: ProjectTasksProviderProps) {
scopeKey={`initiative:${projectId}:tasks`}
searchNamespace="projectTasks"
onOpenTask={props.onOpenTask}
+ onCreateTask={props.onCreateTask}
onCloseTask={() => {}}
sourceFactory={(state, options) =>
createProjectTasksDataSource(
@@ -60,6 +61,7 @@ export function ProjectTasksList(props: ProjectTasksListProps) {
<ProjectTasksProvider
projectId={props.projectId}
onOpenTask={props.onOpenTask}
+ onCreateTask={props.onCreateTask}
>
<ProjectTasksListBody {...props} />
</ProjectTasksProvider>
@@ -80,7 +82,7 @@ function ProjectTasksListBody(props: ProjectTasksListProps) {
<TasksControls />
{props.addTasksAction}
<Show when={props.onCreateTask}>
- <Button variant="outline" onClick={props.onCreateTask}>
+ <Button variant="outline" onClick={() => props.onCreateTask?.()}>
<PlusIcon class="size-4" />
New task
</Button>
diff --git a/apps/web/src/features/projects/views/project-workspace.tsx b/apps/web/src/features/projects/views/project-workspace.tsx
index 347ed8a7f4..9bc2521693 100644
--- a/apps/web/src/features/projects/views/project-workspace.tsx
+++ b/apps/web/src/features/projects/views/project-workspace.tsx
@@ -35,7 +35,7 @@ export function ProjectWorkspace(props: {
commands: ReturnType<ProjectsContext['createCommands']>;
section: ProjectSection;
onOpenTask: ProjectTasksListProps['onOpenTask'];
- onCreateTask(): void;
+ onCreateTask(dueDate?: Date): void;
discussion: JSX.Element;
description: JSX.Element;
}) {
diff --git a/apps/web/src/features/projects/views/projects-collection.test.tsx b/apps/web/src/features/projects/views/projects-collection.test.tsx
index acb33ec505..a05527ceb8 100644
--- a/apps/web/src/features/projects/views/projects-collection.test.tsx
+++ b/apps/web/src/features/projects/views/projects-collection.test.tsx
@@ -10,7 +10,7 @@ import {
screen,
waitFor,
} from '@solidjs/testing-library';
-import { For, type JSX, type ParentProps } from 'solid-js';
+import { createSignal, For, type JSX, type ParentProps } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
type ProjectRow,
@@ -23,6 +23,9 @@ import { ProjectsCollection } from './projects-collection';
const toast = vi.hoisted(() => ({ success: vi.fn(), failure: vi.fn() }));
const device = vi.hoisted(() => ({ mobile: false }));
+const ganttFlag = vi.hoisted(() => ({
+ enabled: (): boolean | undefined => true,
+}));
vi.mock('@core/component/Toast/Toast', () => ({ toast }));
vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => device.mobile }));
// Touch timing is covered by the directive; a test event stands in for it.
@@ -49,6 +52,26 @@ vi.mock('@app/components/view-shell', () => ({
ListSortDropdown: () => null,
ListGroupDropdown: () => null,
ListFilterDropdown: () => null,
+ ViewLayoutDropdown: (props: {
+ label: string;
+ layouts: ('list' | 'board' | 'gantt')[];
+ value: string;
+ onChange: (layout: 'list' | 'board' | 'gantt') => void;
+ }) => (
+ <div role="group" aria-label={props.label}>
+ <For each={props.layouts}>
+ {(layout) => (
+ <button
+ type="button"
+ aria-pressed={props.value === layout}
+ onClick={() => props.onChange(layout)}
+ >
+ {layout}
+ </button>
+ )}
+ </For>
+ </div>
+ ),
useViewControlHotkeys: () => {},
}));
vi.mock('@app/components/view-shell/SidebarCreateButton', () => ({
@@ -117,6 +140,7 @@ beforeEach(() => {
afterEach(() => {
cleanup();
device.mobile = false;
+ ganttFlag.enabled = () => true;
vi.unstubAllGlobals();
animationStyle.remove();
vi.restoreAllMocks();
@@ -198,7 +222,11 @@ function commands() {
function setup(
rows: readonly ProjectRow[],
- options: { canOpenInNewSplit?: boolean; properties?: Property[] } = {}
+ options: {
+ canOpenInNewSplit?: boolean;
+ properties?: Property[];
+ layout?: 'list' | 'gantt';
+ } = {}
) {
const service = commands();
const unused = (): never => {
@@ -236,6 +264,7 @@ function setup(
userId: context.userId,
initialState: {
search: '',
+ layout: options.layout,
status: '',
priority: '',
dueBefore: '',
@@ -255,6 +284,8 @@ function setup(
scopeId="projects"
isActive={() => true}
collection={collection}
+ ganttEnabled={ganttFlag.enabled() === true}
+ createAssigneeName={(id) => id}
canOpenInNewSplit={() => options.canOpenInNewSplit ?? true}
/>
</ProjectsProvider>
@@ -286,6 +317,35 @@ function choose(name: string | RegExp) {
fireEvent.keyDown(screen.getByRole('menuitem', { name }), { key: 'Enter' });
}
+describe('project Gantt rollout', () => {
+ it('derives List while loading or disabled without overwriting saved Gantt', () => {
+ const [enabled, setEnabled] = createSignal<boolean | undefined>(undefined);
+ ganttFlag.enabled = enabled;
+ const view = setup([project('launch', 'Launch', 'owner')], {
+ layout: 'gantt',
+ });
+ expect(view.collection.layout()).toBe('gantt');
+ expect(screen.getByRole('row', { name: 'Launch' })).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'list' }).getAttribute('aria-pressed')
+ ).toBe('true');
+ expect(screen.queryByRole('button', { name: 'gantt' })).toBeNull();
+
+ setEnabled(true);
+ expect(
+ screen.getByRole('button', { name: 'gantt' }).getAttribute('aria-pressed')
+ ).toBe('true');
+ setEnabled(false);
+ expect(view.collection.layout()).toBe('gantt');
+ expect(screen.getByRole('row', { name: 'Launch' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'gantt' })).toBeNull();
+ setEnabled(true);
+ expect(
+ screen.getByRole('button', { name: 'gantt' }).getAttribute('aria-pressed')
+ ).toBe('true');
+ });
+});
+
describe('project row context menu', () => {
it('focuses the row and offers an owner every project action', async () => {
const view = setup([project('launch', 'Launch', 'owner')]);
diff --git a/apps/web/src/features/projects/views/projects-collection.tsx b/apps/web/src/features/projects/views/projects-collection.tsx
index 2c9389fe31..734fb41d84 100644
--- a/apps/web/src/features/projects/views/projects-collection.tsx
+++ b/apps/web/src/features/projects/views/projects-collection.tsx
@@ -1,3 +1,6 @@
+import { Gantt } from '@app/components/gantt/gantt';
+import type { GanttGroupMove } from '@app/components/gantt/gantt-group-drag';
+import { ganttGroupPlacement } from '@app/components/gantt/gantt-group-placement';
import { useListInteractions } from '@app/components/list';
import { ListViewport } from '@app/components/list/ListViewport';
import {
@@ -7,6 +10,7 @@ import {
ListSortDropdown,
SearchBar,
useViewControlHotkeys,
+ ViewLayoutDropdown,
ViewShell,
} from '@app/components/view-shell';
import { SidebarCreateButton } from '@app/components/view-shell/SidebarCreateButton';
@@ -17,18 +21,24 @@ import {
import { TaskGroupHeader } from '@app/features/tasks-view/components/task-list/TaskGroupHeader';
import { taskGridColumnCount } from '@app/features/tasks-view/components/task-list/task-grid-template';
import { toast } from '@core/component/Toast/Toast';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { compareDateDesc } from '@core/util/date';
import { EntitySelectionToolbarModal } from '@entity/EntitySelectionToolbarModal';
import CalendarIcon from '@phosphor/calendar.svg';
import PlusIcon from '@phosphor/plus.svg';
import SpinnerIcon from '@phosphor/spinner.svg';
import { PropertyValueIcon } from '@property/component/propertyValue';
-import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import {
+ PROPERTY_OPTION_IDS,
+ SYSTEM_PROPERTY_IDS,
+} from '@property/identifiers';
import type { Property, PropertyApiValues } from '@property/types';
import { Button, Dropdown, Input } from '@ui';
import {
type Accessor,
batch,
createSignal,
+ type JSX,
Match,
Show,
Switch,
@@ -42,20 +52,31 @@ import {
type ProjectRow as ProjectRowData,
useProjectsContext,
} from '../context/projects-context';
+import { canEditProject } from '../core/project';
+import type { ProjectComposerDraft } from '../primitives/create-project';
import type {
createProjectCollection,
ProjectListActivation,
ProjectListEntity,
} from '../primitives/project-collection';
+import { createProjectGanttRows } from '../primitives/project-gantt-rows';
+import {
+ projectGroupMoveValue,
+ projectGroupPropertyId,
+} from '../queries/project-group-move';
+import { projectTimelineDates } from '../queries/project-timeline';
+import { ProjectsGantt } from './projects-gantt';
type FilterGroup = 'status' | 'priority' | 'assignee';
export function ProjectsCollection(props: {
onOpen(id: string, metadata?: ProjectListActivation): void;
- onCreate(): void;
+ createAssigneeName: (id: Accessor<string>) => Accessor<string>;
+ onCreate(draft?: ProjectComposerDraft): void;
scopeId: string;
isActive: Accessor<boolean>;
collection: ReturnType<typeof createProjectCollection>;
+ ganttEnabled: boolean;
/** Whether the layout has room to open a project beside the list. */
canOpenInNewSplit: Accessor<boolean>;
onCopyLink(id: string): void;
@@ -69,12 +90,23 @@ export function ProjectsCollection(props: {
const definitions = context.createPropertyDefinitionsSource();
const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();
let grid: HTMLDivElement | undefined;
+ let timeline: HTMLDivElement | undefined;
let searchInput: HTMLInputElement | undefined;
const [openMenu, setOpenMenu] = createSignal<'filters' | 'sort'>();
+ const isGantt = () =>
+ props.ganttEnabled && !isTouchDevice() && collection.layout() === 'gantt';
const definition = (id: string) =>
definitions
.properties()
.find((property) => property.propertyDefinitionId === id);
+ const statusOptionId = (entity: ProjectListEntity) => {
+ const status = entity.properties.find(
+ (property) => property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.STATUS
+ );
+ return status?.valueType === 'SELECT_STRING'
+ ? status.value?.[0]
+ : undefined;
+ };
const filters = (): ListFilterGroup<FilterGroup, string>[] => [
...(['status', 'priority'] as const).map((id) => ({
id,
@@ -123,7 +155,7 @@ export function ProjectsCollection(props: {
const interaction = useListInteractions({
controller: list,
scopeId: props.scopeId,
- enabled: props.isActive,
+ enabled: () => props.isActive() && !isGantt(),
scrollHandle: virtualizer,
activation: {
createMetadata: (intent) => ({ newSplit: intent === 'alternate' }),
@@ -163,10 +195,127 @@ export function ProjectsCollection(props: {
// The menu entry that opened a dialog no longer exists when it closes.
const returnFocusToList = (event: Event) => {
event.preventDefault();
- grid?.focus();
+ if (isGantt())
+ timeline?.querySelector<HTMLElement>('[tabindex="0"]')?.focus();
+ else grid?.focus();
};
const menuTargets = (entity: ProjectListEntity) =>
getSoupMenuEntities(entity, getSoupRowEntities(list.selection.items()));
+ const groupProperty = () => {
+ const id = projectGroupPropertyId(collection.groupBy());
+ return id ? definition(id) : undefined;
+ };
+ const groupMoveScope = () =>
+ JSON.stringify([
+ props.scopeId,
+ context.userId(),
+ collection.groupBy(),
+ collection.search(),
+ collection.status(),
+ collection.priority(),
+ collection.mine(),
+ collection.dueBefore(),
+ collection.dueAfter(),
+ ]);
+ const ganttRows = createProjectGanttRows({
+ grouping: collection.groupBy,
+ groups: collection.groups,
+ items: collection.items,
+ property: groupProperty,
+ scope: groupMoveScope,
+ isExpanded: collection.disclosure.isExpanded,
+ });
+ const canDragProject = (id: string) => {
+ const state = collection.state();
+ const project =
+ state.kind === 'ready'
+ ? state.rows.find((row) => row.project.id === id)?.project
+ : undefined;
+ const property = groupProperty();
+ return (
+ !!project &&
+ canEditProject(project) &&
+ !!property &&
+ !property.isMetadata &&
+ !commands.pending() &&
+ property.valueType ===
+ (collection.groupBy() === 'assignee' ? 'ENTITY' : 'SELECT_STRING')
+ );
+ };
+ const resolveGroupMove = (move: GanttGroupMove) => {
+ const current = collection.state();
+ const entity =
+ current.kind === 'ready'
+ ? current.rows.find((row) => row.project.id === move.id)
+ : undefined;
+ const property = groupProperty();
+ if (!entity || !property || !canDragProject(move.id)) return;
+ if (!ganttRows.groups().some((group) => group.id === move.toGroup)) return;
+ if (
+ collection.groupBy() !== 'assignee' &&
+ move.toGroup &&
+ !property.options?.some((option) => option.id === move.toGroup)
+ )
+ return;
+ if (!move.toGroup && property.isRequired) return;
+ const apiValues = projectGroupMoveValue(
+ entity.properties,
+ collection.groupBy(),
+ move
+ );
+ return apiValues ? { property, apiValues } : undefined;
+ };
+ const moveProjectGroup = async (move: GanttGroupMove) => {
+ const update = resolveGroupMove(move);
+ if (!update)
+ throw new Error('Project or destination is no longer editable');
+ await commands.saveProperty(move.id, update.property, update.apiValues);
+ };
+ const createOnTimeline = (date: Date) => {
+ const property = definition(SYSTEM_PROPERTY_IDS.DUE_DATE);
+ if (!property || property.valueType !== 'DATE') return;
+ props.onCreate({
+ name: '',
+ description: '',
+ shareWithTeam: true,
+ properties: [{ property, value: { valueType: 'DATE', value: date } }],
+ });
+ };
+ function ProjectMenu(menu: {
+ entity: ProjectListEntity;
+ rowId?: string;
+ children: JSX.Element;
+ }) {
+ return (
+ <ProjectRowMenu
+ targets={() => (isGantt() ? [menu.entity] : menuTargets(menu.entity))}
+ status={definition(SYSTEM_PROPERTY_IDS.STATUS)}
+ priority={definition(SYSTEM_PROPERTY_IDS.PRIORITY)}
+ canOpenInNewSplit={props.canOpenInNewSplit()}
+ onOpenInNewSplit={(row) =>
+ props.onOpen(row.project.id, { newSplit: true })
+ }
+ onRename={(row) => setRenaming(row)}
+ onSetOption={(rows, property, optionId) =>
+ void setOption(rows, property, optionId)
+ }
+ onCopyLink={(row) => props.onCopyLink(row.project.id)}
+ onCopyId={(row) => props.onCopyId(row.project.id)}
+ onShare={props.onShare && ((row) => props.onShare?.(row.project.id))}
+ onDelete={(rows) => setDeleting({ rows })}
+ onOpenChange={(open) => {
+ if (!open || isGantt() || !menu.rowId) return;
+ list.focus.set(menu.rowId, { reason: 'pointer', force: true });
+ list.selection.setAnchor(menu.rowId);
+ }}
+ onCloseAutoFocus={(event) => {
+ if (renaming() || deleting()) event.preventDefault();
+ }}
+ >
+ {menu.children}
+ </ProjectRowMenu>
+ );
+ }
const setOption = async (
rows: readonly ProjectRowData[],
property: Property,
@@ -284,7 +433,10 @@ export function ProjectsCollection(props: {
Projects
</h1>
<div class="ml-auto shrink-0">
- <SidebarCreateButton label="New" onCreate={props.onCreate} />
+ <SidebarCreateButton
+ label="New"
+ onCreate={() => props.onCreate()}
+ />
</div>
</div>
<div class="flex min-w-0 items-center justify-between gap-3">
@@ -301,6 +453,16 @@ export function ProjectsCollection(props: {
hotkey="cmd+f"
/>
<div class="flex shrink-0 items-center gap-2">
+ <Show when={!isTouchDevice()}>
+ <ViewLayoutDropdown
+ label="Project layout"
+ layouts={props.ganttEnabled ? ['list', 'gantt'] : ['list']}
+ value={isGantt() ? 'gantt' : 'list'}
+ onChange={(layout) => {
+ if (layout !== 'board') collection.setLayout(layout);
+ }}
+ />
+ </Show>
<ListSortDropdown
label="Sort projects"
value={collection.sort()}
@@ -398,7 +560,7 @@ export function ProjectsCollection(props: {
<Button
variant="outline"
class="touch:hidden @max-[720px]/view-shell:hidden"
- onClick={props.onCreate}
+ onClick={() => props.onCreate()}
>
<PlusIcon class="size-4" />
New project
@@ -408,214 +570,284 @@ export function ProjectsCollection(props: {
</div>
</ViewShell.Header>
<ViewShell.Content>
- <div
- ref={(element) => {
- grid = element;
- }}
- role="grid"
- aria-label="Projects"
- aria-multiselectable="true"
- aria-activedescendant={list.focus.key()}
- tabIndex={0}
- class="@container/u-list relative flex size-full min-h-0 min-w-0 flex-col overflow-hidden outline-none"
- >
- <ProjectListHeader />
- <Show when={backgroundError()}>
- <p role="status" class="px-3 text-xs text-ink-muted">
- Could not refresh projects. Showing the last loaded list.
- </p>
- </Show>
- <Switch>
- <Match when={collection.state().kind === 'loading'}>
- <div class="grid flex-1 place-items-center text-ink-muted">
- <SpinnerIcon
- class="size-5 animate-spin"
- aria-label="Loading projects"
- />
- </div>
- </Match>
- <Match when={sourceError()}>
- <div
- role="alert"
- class="grid flex-1 place-items-center gap-3 text-sm text-ink-muted"
- >
- <span>Projects couldn’t be loaded.</span>
- <Button onClick={() => void collection.refresh()}>
- Try again
- </Button>
- </div>
- </Match>
- <Match when={collection.items().length === 0}>
- <div class="flex flex-1 flex-col items-center justify-center gap-3 text-sm text-ink-muted">
- <span>
- {filtered() ? 'No matching projects' : 'No projects yet'}
- </span>
- <Show when={!filtered()}>
- <Button onClick={props.onCreate}>New project</Button>
- </Show>
- </div>
- </Match>
- <Match when={true}>
- <ListViewport
- ref={(handle) => {
- setVirtualizer(handle);
- handle?.scrollTo(collection.scrollOffset());
- }}
- items={collection.items()}
- focusedIndex={list.focus.index()}
- onScroll={checkNearEnd}
- >
- {(row) => (
- <Switch>
- <Match when={row.kind === 'group-header' ? row : undefined}>
- {(group) => (
- <TaskGroupHeader
- row={group()}
- columnCount={taskGridColumnCount(true)}
- groupBy={collection.groupBy()}
- expanded={collection.disclosure.isExpanded(
- group().groupId
- )}
- focused={list.focus.key() === group().id}
- onFocus={() =>
- list.focus.set(group().id, { reason: 'hover' })
- }
- onToggle={() =>
- list.activate.key(group().id, { reason: 'pointer' })
- }
- />
- )}
- </Match>
- <Match when={row.kind === 'entity' ? row : undefined}>
- {(item) => (
- <ProjectRowMenu
- targets={() => menuTargets(item().entity)}
- status={definition(SYSTEM_PROPERTY_IDS.STATUS)}
- priority={definition(SYSTEM_PROPERTY_IDS.PRIORITY)}
- canOpenInNewSplit={props.canOpenInNewSplit()}
- onOpenInNewSplit={(row) =>
- props.onOpen(row.project.id, { newSplit: true })
- }
- onRename={(row) => setRenaming(row)}
- onSetOption={(rows, property, optionId) =>
- void setOption(rows, property, optionId)
- }
- onCopyLink={(row) => props.onCopyLink(row.project.id)}
- onCopyId={(row) => props.onCopyId(row.project.id)}
- onShare={
- props.onShare &&
- ((row) => props.onShare?.(row.project.id))
- }
- onDelete={(rows) => setDeleting({ rows })}
- onOpenChange={(open) => {
- if (!open) return;
- list.focus.set(item().id, {
- reason: 'pointer',
- force: true,
- });
- list.selection.setAnchor(item().id);
- }}
- onCloseAutoFocus={(event) => {
- // Leave focus with a dialog the entry just opened.
- if (renaming() || deleting())
- event.preventDefault();
- }}
+ <Show
+ when={isGantt()}
+ fallback={
+ <div
+ ref={(element) => {
+ grid = element;
+ }}
+ role="grid"
+ aria-label="Projects"
+ aria-multiselectable="true"
+ aria-activedescendant={list.focus.key()}
+ tabIndex={0}
+ class="@container/u-list relative flex size-full min-h-0 min-w-0 flex-col overflow-hidden outline-none"
+ >
+ <ProjectListHeader />
+ <Show when={backgroundError()}>
+ <p role="status" class="px-3 text-xs text-ink-muted">
+ Could not refresh projects. Showing the last loaded list.
+ </p>
+ </Show>
+ <Switch>
+ <Match when={collection.state().kind === 'loading'}>
+ <div class="grid flex-1 place-items-center text-ink-muted">
+ <SpinnerIcon
+ class="size-5 animate-spin"
+ aria-label="Loading projects"
+ />
+ </div>
+ </Match>
+ <Match when={sourceError()}>
+ <div
+ role="alert"
+ class="grid flex-1 place-items-center gap-3 text-sm text-ink-muted"
+ >
+ <span>Projects couldn’t be loaded.</span>
+ <Button onClick={() => void collection.refresh()}>
+ Try again
+ </Button>
+ </div>
+ </Match>
+ <Match when={collection.items().length === 0}>
+ <div class="flex flex-1 flex-col items-center justify-center gap-3 text-sm text-ink-muted">
+ <span>
+ {filtered() ? 'No matching projects' : 'No projects yet'}
+ </span>
+ <Show when={!filtered()}>
+ <Button onClick={() => props.onCreate()}>
+ New project
+ </Button>
+ </Show>
+ </div>
+ </Match>
+ <Match when={true}>
+ <ListViewport
+ ref={(handle) => {
+ setVirtualizer(handle);
+ handle?.scrollTo(collection.scrollOffset());
+ }}
+ items={collection.items()}
+ focusedIndex={list.focus.index()}
+ onScroll={checkNearEnd}
+ >
+ {(row) => (
+ <Switch>
+ <Match
+ when={row.kind === 'group-header' ? row : undefined}
>
- <ProjectRow
- rowId={item().id}
- row={item().entity}
- highlighted={list.focus.key() === item().id}
- checked={list.selection.isSelected(item().id)}
- onFocus={() =>
- list.focus.set(item().id, { reason: 'hover' })
- }
- onChecked={(selected, range) =>
- interaction.selection.set(item().id, selected, {
- range,
- })
- }
- onOpen={(event) => {
- if (event.ctrlKey || event.metaKey)
- interaction.selection.toggle(item().id);
- else
- list.activate.key(item().id, {
- reason: 'pointer',
- metadata: { event, newSplit: event.shiftKey },
- });
- }}
- onSave={(property, value) =>
- commands.saveProperty(
- item().entity.id,
- property,
- value
- )
- }
- />
- </ProjectRowMenu>
- )}
- </Match>
- <Match when={row.kind === 'load-more' ? row : undefined}>
- {(more) => (
- <div role="row" id={more().id}>
- <div
- role="gridcell"
- aria-colspan={taskGridColumnCount(true)}
- class="flex justify-center py-2"
- >
- <Button
- disabled={collection.loadingMore()}
- onClick={() =>
- list.activate.key(more().id, {
+ {(group) => (
+ <TaskGroupHeader
+ row={group()}
+ columnCount={taskGridColumnCount(true)}
+ groupBy={collection.groupBy()}
+ expanded={collection.disclosure.isExpanded(
+ group().groupId
+ )}
+ focused={list.focus.key() === group().id}
+ onFocus={() =>
+ list.focus.set(group().id, {
+ reason: 'hover',
+ })
+ }
+ onToggle={() =>
+ list.activate.key(group().id, {
reason: 'pointer',
})
}
+ />
+ )}
+ </Match>
+ <Match when={row.kind === 'entity' ? row : undefined}>
+ {(item) => (
+ <ProjectMenu
+ entity={item().entity}
+ rowId={item().id}
>
- {collection.loadingMore()
- ? 'Loading…'
- : 'Load more projects'}
- </Button>
- </div>
- </div>
- )}
- </Match>
- </Switch>
- )}
- </ListViewport>
- </Match>
- </Switch>
- <Show when={list.selection.count()}>
- <EntitySelectionToolbarModal
- selectedCount={list.selection.count()}
- onClose={interaction.selection.clear}
- />
- </Show>
- <Show when={renaming()} keyed>
- {(row) => (
- <RenameProjectDialog
- name={row.project.name}
- onOpenChange={(open) => {
- if (!open) setRenaming(undefined);
- }}
- onRename={(name) => commands.rename(row.project.id, name)}
- onCloseAutoFocus={returnFocusToList}
- />
- )}
- </Show>
- <Show when={deleting()}>
- {(request) => (
- <DeleteProjectsDialog
- count={request().rows.length}
- pending={deletePending()}
- error={request().error}
- onOpenChange={(open) => {
- if (!open) setDeleting(undefined);
- }}
- onDelete={() => void deleteProjects(request().rows)}
- onCloseAutoFocus={returnFocusToList}
- />
+ <ProjectRow
+ rowId={item().id}
+ row={item().entity}
+ highlighted={list.focus.key() === item().id}
+ checked={list.selection.isSelected(item().id)}
+ onFocus={() =>
+ list.focus.set(item().id, {
+ reason: 'hover',
+ })
+ }
+ onChecked={(selected, range) =>
+ interaction.selection.set(
+ item().id,
+ selected,
+ {
+ range,
+ }
+ )
+ }
+ onOpen={(event) => {
+ if (event.ctrlKey || event.metaKey)
+ interaction.selection.toggle(item().id);
+ else
+ list.activate.key(item().id, {
+ reason: 'pointer',
+ metadata: {
+ event,
+ newSplit: event.shiftKey,
+ },
+ });
+ }}
+ onSave={(property, value) =>
+ commands.saveProperty(
+ item().entity.id,
+ property,
+ value
+ )
+ }
+ />
+ </ProjectMenu>
+ )}
+ </Match>
+ <Match
+ when={row.kind === 'load-more' ? row : undefined}
+ >
+ {(more) => (
+ <div role="row" id={more().id}>
+ <div
+ role="gridcell"
+ aria-colspan={taskGridColumnCount(true)}
+ class="flex justify-center py-2"
+ >
+ <Button
+ disabled={collection.loadingMore()}
+ onClick={() =>
+ list.activate.key(more().id, {
+ reason: 'pointer',
+ })
+ }
+ >
+ {collection.loadingMore()
+ ? 'Loading…'
+ : 'Load more projects'}
+ </Button>
+ </div>
+ </div>
+ )}
+ </Match>
+ </Switch>
+ )}
+ </ListViewport>
+ </Match>
+ </Switch>
+ <Show when={list.selection.count()}>
+ <EntitySelectionToolbarModal
+ selectedCount={list.selection.count()}
+ onClose={interaction.selection.clear}
+ />
+ </Show>
+ </div>
+ }
+ >
+ <ProjectsGantt
+ collection={collection}
+ items={ganttRows.items}
+ groupMoves={{
+ scope: groupMoveScope(),
+ canDrag: canDragProject,
+ canDrop: (move) => !!resolveGroupMove(move),
+ getPlacement: (move) =>
+ ganttGroupPlacement({
+ items: ganttRows.items(),
+ move,
+ getEntity: (row) =>
+ row.kind === 'entity' ? row.entity : undefined,
+ getGroup: (row) =>
+ row.kind === 'section-header' ? undefined : row.groupId,
+ compare: (left, right) => {
+ const key =
+ collection.sort() === 'created'
+ ? 'createdAt'
+ : 'updatedAt';
+ return compareDateDesc(
+ left.project[key],
+ right.project[key]
+ );
+ },
+ }),
+ onMove: moveProjectGroup,
+ }}
+ onOpen={props.onOpen}
+ createAssigneeName={props.createAssigneeName}
+ onCreate={
+ definition(SYSTEM_PROPERTY_IDS.DUE_DATE)?.valueType === 'DATE'
+ ? (dates) => createOnTimeline(dates.end)
+ : undefined
+ }
+ ref={(element) => {
+ timeline = element;
+ }}
+ renderEntity={(entity, label) => (
+ <ProjectMenu entity={entity()}>
+ <Gantt.Row>
+ {label}
+ <Gantt.Bar
+ {...projectTimelineDates(entity())}
+ title={entity().project.name}
+ deadlineWarning={
+ statusOptionId(entity()) !==
+ PROPERTY_OPTION_IDS.STATUS.COMPLETED &&
+ statusOptionId(entity()) !==
+ PROPERTY_OPTION_IDS.STATUS.CANCELED
+ }
+ onClick={(event) =>
+ props.onOpen(entity().id, {
+ event,
+ newSplit:
+ event.shiftKey ||
+ event.ctrlKey ||
+ event.metaKey ||
+ event.altKey,
+ })
+ }
+ >
+ <PropertyValueIcon
+ optionId={statusOptionId(entity()) ?? ''}
+ class="size-3.5 shrink-0"
+ />
+ <span class="min-w-0 truncate">
+ {entity().project.name}
+ </span>
+ </Gantt.Bar>
+ </Gantt.Row>
+ </ProjectMenu>
)}
- </Show>
- </div>
+ />
+ </Show>
+ <Show when={renaming()} keyed>
+ {(row) => (
+ <RenameProjectDialog
+ name={row.project.name}
+ onOpenChange={(open) => {
+ if (!open) setRenaming(undefined);
+ }}
+ onRename={(name) => commands.rename(row.project.id, name)}
+ onCloseAutoFocus={returnFocusToList}
+ />
+ )}
+ </Show>
+ <Show when={deleting()}>
+ {(request) => (
+ <DeleteProjectsDialog
+ count={request().rows.length}
+ pending={deletePending()}
+ error={request().error}
+ onOpenChange={(open) => {
+ if (!open) setDeleting(undefined);
+ }}
+ onDelete={() => void deleteProjects(request().rows)}
+ onCloseAutoFocus={returnFocusToList}
+ />
+ )}
+ </Show>
</ViewShell.Content>
</>
);
diff --git a/apps/web/src/features/projects/views/projects-gantt.tsx b/apps/web/src/features/projects/views/projects-gantt.tsx
new file mode 100644
index 0000000000..0e39ab95ee
--- /dev/null
+++ b/apps/web/src/features/projects/views/projects-gantt.tsx
@@ -0,0 +1,355 @@
+import type { GanttCreation } from '@app/components/gantt/create-gantt-creation';
+import { Gantt } from '@app/components/gantt/gantt';
+import { deriveGanttRange } from '@app/components/gantt/gantt-date';
+import { STATUS_GROUP_HEADER_TINTS } from '@app/features/tasks-view/components/task-list/TaskGroupHeader';
+import { UserIcon } from '@core/component/UserIcon';
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import CircleDashedIcon from '@phosphor/circle-dashed.svg';
+import SpinnerIcon from '@phosphor/spinner.svg';
+import { PropertyValueIcon } from '@property/component/propertyValue';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import { Button, cn, Layer } from '@ui';
+import {
+ type Accessor,
+ type ComponentProps,
+ createMemo,
+ type JSX,
+ Match,
+ Show,
+ Switch,
+} from 'solid-js';
+import type {
+ createProjectCollection,
+ ProjectListActivation,
+ ProjectListEntity,
+ ProjectListItem,
+} from '../primitives/project-collection';
+import { projectTimelineDates } from '../queries/project-timeline';
+
+function AssigneeLabel(props: {
+ id: string;
+ createName: (id: Accessor<string>) => Accessor<string>;
+}) {
+ const name = props.createName(() => props.id);
+ return <>{name()}</>;
+}
+
+export function ProjectsGantt(props: {
+ createAssigneeName: (id: Accessor<string>) => Accessor<string>;
+ collection: ReturnType<typeof createProjectCollection>;
+ items: Accessor<readonly ProjectListItem[]>;
+ groupMoves: Omit<ComponentProps<typeof Gantt.GroupDrag>, 'children'>;
+ onOpen: (id: string, metadata?: ProjectListActivation) => void;
+ onCreate?: (dates: GanttCreation) => void;
+ /** Compose the complete project row so host-owned menus cover its label and bar. */
+ renderEntity: (
+ entity: Accessor<ProjectListEntity>,
+ label: JSX.Element
+ ) => JSX.Element;
+ ref?: (element: HTMLDivElement) => void;
+}) {
+ const collection = props.collection;
+ const range = createMemo(() => {
+ const state = collection.state();
+ return deriveGanttRange(
+ state.kind === 'ready' ? state.rows.map(projectTimelineDates) : []
+ );
+ });
+ const sourceError = () => {
+ const state = collection.state();
+ return state.kind === 'error' ? state.error : undefined;
+ };
+ const backgroundError = () => {
+ const state = collection.state();
+ return state.kind === 'ready' ? state.backgroundError : undefined;
+ };
+ const open = (id: string, event: MouseEvent) =>
+ props.onOpen(id, {
+ event,
+ newSplit:
+ event.shiftKey || event.metaKey || event.ctrlKey || event.altKey,
+ });
+
+ return (
+ <div ref={props.ref} class="flex size-full min-h-0 min-w-0 flex-1 flex-col">
+ <Switch>
+ <Match when={collection.state().kind === 'loading'}>
+ <div class="grid flex-1 place-items-center text-ink-muted">
+ <SpinnerIcon
+ aria-label="Loading project timeline"
+ class="size-5 animate-spin"
+ />
+ </div>
+ </Match>
+ <Match when={sourceError()}>
+ <div
+ role="alert"
+ class="flex flex-1 flex-col items-center justify-center gap-3 text-sm text-ink-muted"
+ >
+ Projects couldn’t be loaded.
+ <Button variant="outline" onClick={() => void collection.refresh()}>
+ Try again
+ </Button>
+ </div>
+ </Match>
+ <Match when={!props.items().length && !props.onCreate}>
+ <div class="grid flex-1 place-items-center text-sm text-ink-muted">
+ No matching projects
+ </div>
+ </Match>
+ <Match when={true}>
+ <Show when={backgroundError()}>
+ <p role="status" class="px-3 py-2 text-xs text-ink-muted">
+ Could not refresh projects. Showing the last loaded timeline.
+ </p>
+ </Show>
+ <Gantt.Root range={range()} labelWidth={0}>
+ <Gantt.SidebarToggle />
+ <Gantt.Controls>
+ <Gantt.TodayButton />
+ <Gantt.Settings />
+ </Gantt.Controls>
+ <Gantt.GroupDrag {...props.groupMoves}>
+ <Gantt.Chart>
+ <Gantt.Header />
+ <Gantt.Rows
+ items={props.items()}
+ getKey={(row) => row.id}
+ getPanelKey={(row) =>
+ row.kind === 'entity' || row.kind === 'load-more'
+ ? (row.groupId ?? '')
+ : undefined
+ }
+ virtualize
+ renderDropPreview={(move) => {
+ const state = collection.state();
+ const entity =
+ state.kind === 'ready'
+ ? state.rows.find((row) => row.project.id === move.id)
+ : undefined;
+ return (
+ entity && (
+ <Gantt.DropPreview
+ {...projectTimelineDates(entity)}
+ title={entity.project.name}
+ />
+ )
+ );
+ }}
+ >
+ {(row) => (
+ <Switch>
+ <Match when={row.kind === 'entity' ? row : undefined}>
+ {(item) => {
+ const status = () =>
+ item().entity.properties.find(
+ (property) =>
+ property.propertyDefinitionId ===
+ SYSTEM_PROPERTY_IDS.STATUS
+ );
+ const statusId = () => {
+ const property = status();
+ return property?.valueType === 'SELECT_STRING'
+ ? property.value?.[0]
+ : undefined;
+ };
+ return (
+ <Gantt.DragItem
+ id={item().entity.id}
+ key={item().id}
+ groupId={item().groupId ?? ''}
+ label={item().entity.project.name}
+ >
+ {props.renderEntity(
+ () => item().entity,
+ <>
+ <Gantt.GroupDrop
+ id={item().id}
+ groupId={item().groupId ?? ''}
+ />
+ <Gantt.Label>
+ <Layer depth={2}>
+ <button
+ type="button"
+ class="flex h-7 w-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md px-2 text-left text-xs outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
+ title={item().entity.project.name}
+ onClick={(event) =>
+ open(item().entity.id, event)
+ }
+ >
+ <PropertyValueIcon
+ optionId={statusId() ?? ''}
+ class="size-3.5 shrink-0"
+ />
+ <span class="min-w-0 flex-1 leading-3.5">
+ <span class="block truncate">
+ {item().entity.project.name}
+ </span>
+ <Gantt.DateHint
+ {...projectTimelineDates(
+ item().entity
+ )}
+ class="leading-3"
+ />
+ </span>
+ </button>
+ </Layer>
+ </Gantt.Label>
+ </>
+ )}
+ </Gantt.DragItem>
+ );
+ }}
+ </Match>
+ <Match
+ when={row.kind === 'group-header' ? row : undefined}
+ >
+ {(group) => (
+ <Gantt.Row>
+ <Gantt.GroupDrop
+ id={group().id}
+ groupId={group().groupId}
+ />
+ <Gantt.GroupHeader
+ class={
+ collection.groupBy() === 'status'
+ ? STATUS_GROUP_HEADER_TINTS[group().groupId]
+ : undefined
+ }
+ >
+ <button
+ type="button"
+ aria-expanded={collection.disclosure.isExpanded(
+ group().groupId
+ )}
+ class="flex h-full w-full min-w-0 items-center gap-2.5 rounded-[inherit] px-2 py-1.5 text-left text-xs font-semibold tracking-tight outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
+ onClick={() =>
+ collection.disclosure.toggle(group().groupId)
+ }
+ >
+ <Layer depth={3}>
+ <span class="flex size-4.5 shrink-0 items-center justify-center rounded-xs group-hover/header:bg-ink/5">
+ <CaretRightIcon
+ class={cn(
+ 'size-2.5 transition-transform',
+ collection.disclosure.isExpanded(
+ group().groupId
+ ) && 'rotate-90'
+ )}
+ />
+ </span>
+ </Layer>
+ <Switch>
+ <Match when={!group().groupId}>
+ <CircleDashedIcon class="size-3.5 shrink-0 text-ink-extra-muted" />
+ </Match>
+ <Match
+ when={
+ collection.groupBy() === 'status' ||
+ collection.groupBy() === 'priority'
+ }
+ >
+ <PropertyValueIcon
+ optionId={group().groupId}
+ class="size-3.5 shrink-0"
+ />
+ </Match>
+ <Match
+ when={collection.groupBy() === 'assignee'}
+ >
+ <UserIcon
+ id={group().groupId}
+ size="sm"
+ suppressClick
+ showTooltip={false}
+ />
+ </Match>
+ </Switch>
+ <span class="truncate">
+ <Show
+ when={
+ collection.groupBy() === 'assignee' &&
+ group().groupId
+ }
+ fallback={group().label}
+ >
+ <AssigneeLabel
+ id={group().groupId}
+ createName={props.createAssigneeName}
+ />
+ </Show>
+ </span>
+ <Show when={group().count !== undefined}>
+ <span class="shrink-0 rounded-full bg-ink/10 px-1.5 py-px text-xs font-medium tabular-nums text-ink-extra-muted">
+ {group().count}
+ </span>
+ </Show>
+ </button>
+ </Gantt.GroupHeader>
+ </Gantt.Row>
+ )}
+ </Match>
+ <Match when={row.kind === 'load-more' ? row : undefined}>
+ {(more) => (
+ <Gantt.Row>
+ <div class="absolute inset-0">
+ <Gantt.Label>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={more().isLoading}
+ onClick={() => void collection.loadMore()}
+ >
+ <Show when={more().isLoading}>
+ <SpinnerIcon class="size-3 animate-spin" />
+ </Show>
+ {more().isLoading
+ ? 'Loading projects…'
+ : 'Load more projects'}
+ </Button>
+ </Gantt.Label>
+ </div>
+ <Gantt.Pagination>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={more().isLoading}
+ onClick={() => void collection.loadMore()}
+ >
+ <Show when={more().isLoading}>
+ <SpinnerIcon class="size-3 animate-spin" />
+ </Show>
+ {more().isLoading
+ ? 'Loading projects…'
+ : 'Load more projects'}
+ </Button>
+ </Gantt.Pagination>
+ </Gantt.Row>
+ )}
+ </Match>
+ <Match
+ when={row.kind === 'section-header' ? row : undefined}
+ >
+ {(section) => (
+ <Gantt.Row>
+ <Gantt.Label>{section().label}</Gantt.Label>
+ </Gantt.Row>
+ )}
+ </Match>
+ </Switch>
+ )}
+ </Gantt.Rows>
+ <Gantt.TodayMarker />
+ <Gantt.CreateArea
+ minDate={new Date()}
+ onCreate={props.onCreate}
+ />
+ </Gantt.Chart>
+ </Gantt.GroupDrag>
+ <Gantt.ZoomControls />
+ </Gantt.Root>
+ </Match>
+ </Switch>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/tasks-view/components/TasksControls.tsx b/apps/web/src/features/tasks-view/components/TasksControls.tsx
index 1540cac57d..4042b84048 100644
--- a/apps/web/src/features/tasks-view/components/TasksControls.tsx
+++ b/apps/web/src/features/tasks-view/components/TasksControls.tsx
@@ -26,7 +26,8 @@ export function TasksControls() {
function DesktopTasksControls() {
const panel = useSplitPanelOrThrow();
- const { state, setPrimarySort, setState, projectsEnabled } = useTasksView();
+ const { state, setPrimarySort, setState, projectsEnabled, ganttEnabled } =
+ useTasksView();
const filters = useTaskFilters();
const [openMenu, setOpenMenu] = createSignal<'filters' | 'sort'>();
let filterTrigger: HTMLButtonElement | undefined;
@@ -81,6 +82,9 @@ function DesktopTasksControls() {
<ViewLayoutDropdown
label="Task layout"
value={state.layout}
+ layouts={
+ ganttEnabled() ? ['list', 'board', 'gantt'] : ['list', 'board']
+ }
onChange={(layout) => setState('layout', layout)}
/>
<Show
diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx
index 278f372bf4..ead7cdb48f 100644
--- a/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx
+++ b/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx
@@ -13,7 +13,7 @@ import { cn, Layer, Surface } from '@ui';
import { createMemo, Match, Show, Switch } from 'solid-js';
import type { TaskGroupBy } from '../../types';
-const STATUS_GROUP_HEADER_TINTS: Record<string, string> = {
+export const STATUS_GROUP_HEADER_TINTS: Record<string, string> = {
[PROPERTY_OPTION_IDS.STATUS.NOT_STARTED]:
'bg-task/5 border-task/10 data-highlighted:bg-task/10 hover:bg-task/10',
[PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS]:
diff --git a/apps/web/src/features/tasks-view/core/task-board.ts b/apps/web/src/features/tasks-view/core/task-board.ts
index f131eaf6f5..088dc23443 100644
--- a/apps/web/src/features/tasks-view/core/task-board.ts
+++ b/apps/web/src/features/tasks-view/core/task-board.ts
@@ -72,7 +72,9 @@ export function moveTaskAssignees(
const remaining = ids.filter((id) => id !== from);
- return [...new Set([...remaining, to])];
+ return [...remaining, to].filter(
+ (id, index, values) => values.indexOf(id) === index
+ );
}
export function isTaskBoardMove(
diff --git a/apps/web/src/features/tasks-view/persistence.ts b/apps/web/src/features/tasks-view/persistence.ts
index 04aefcf8ff..393ef79526 100644
--- a/apps/web/src/features/tasks-view/persistence.ts
+++ b/apps/web/src/features/tasks-view/persistence.ts
@@ -40,7 +40,7 @@ const taskFacetsSchema = z.record(z.string(), z.array(z.string()));
const tasksEntryStateSchemaWithDefaults = z.object({
version: z.literal(1).default(1),
- layout: z.enum(['list', 'board']).catch('list').default('list'),
+ layout: z.enum(['list', 'board', 'gantt']).catch('list').default('list'),
tab: taskTabSchema.default('my-tasks'),
search: z.string().default(''),
groupBy: taskGroupBySchema.default('priority'),
diff --git a/apps/web/src/features/tasks-view/primitives/create-task-board.ts b/apps/web/src/features/tasks-view/primitives/create-task-board.ts
index 474b8aeed7..d79b0b15f6 100644
--- a/apps/web/src/features/tasks-view/primitives/create-task-board.ts
+++ b/apps/web/src/features/tasks-view/primitives/create-task-board.ts
@@ -32,7 +32,7 @@ export function createTaskBoard(options: {
actions: TaskBoardActions;
compareTasks?: (left: string, right: string) => number;
}) {
- const [pending, setPending] = createSignal<ReadonlySet<string>>(new Set());
+ const [pending, setPending] = createSignal<string[]>([]);
const [error, setError] = createSignal<{ scope: string; text: string }>();
const [placements, setPlacements] = createSignal<readonly Placement[]>([]);
const currentPlacements = createMemo(() =>
@@ -86,7 +86,7 @@ export function createTaskBoard(options: {
});
const canMove = (move: TaskBoardMove) => {
- if (pending().has(move.id) || !options.actions.canEditTask(move.id)) {
+ if (pending().includes(move.id) || !options.actions.canEditTask(move.id)) {
return false;
}
@@ -140,7 +140,7 @@ export function createTaskBoard(options: {
placement,
]);
- setPending((ids) => new Set([...ids, request.id]));
+ setPending((ids) => [...ids, request.id]);
setError(undefined);
try {
@@ -170,7 +170,7 @@ export function createTaskBoard(options: {
});
return false;
} finally {
- setPending((ids) => new Set([...ids].filter((id) => id !== request.id)));
+ setPending((ids) => ids.filter((id) => id !== request.id));
}
};
@@ -188,7 +188,7 @@ export function createTaskBoard(options: {
columns,
canMove,
move,
- pending: (id: string) => pending().has(id),
+ pending: (id: string) => pending().includes(id),
error: currentError,
};
}
diff --git a/apps/web/src/features/tasks-view/primitives/create-tasks-view-search.test.ts b/apps/web/src/features/tasks-view/primitives/create-tasks-view-search.test.ts
index f7da866da0..443999160d 100644
--- a/apps/web/src/features/tasks-view/primitives/create-tasks-view-search.test.ts
+++ b/apps/web/src/features/tasks-view/primitives/create-tasks-view-search.test.ts
@@ -17,7 +17,7 @@ function setup(
search?: Partial<TasksTabSearchParams>;
scopedTab?: TasksTab;
enabled?: boolean;
- boardEnabled?: Accessor<boolean>;
+ nonListLayoutsEnabled?: Accessor<boolean>;
} = {}
) {
return createRoot((dispose) => {
@@ -51,7 +51,7 @@ function setup(
setSearch: writeSearch,
tab: () => options.scopedTab ?? search.tab,
enabled: options.enabled ?? true,
- boardEnabled: options.boardEnabled,
+ nonListLayoutsEnabled: options.nonListLayoutsEnabled,
});
return { state, search, setSearch, writeSearch, ...controls };
@@ -142,45 +142,48 @@ it('leaves embedded entry state and the parent URL untouched without a URL capab
expect(view.search.sort).toBe('created_at');
});
-it('replaces mobile board URLs with list while preserving task controls and entry state', () => {
- const view = setup({
- boardEnabled: () => false,
- search: {
- layout: 'board',
+it.each(['board', 'gantt'] as const)(
+ 'replaces mobile %s URLs with list while preserving task controls and entry state',
+ (layout) => {
+ const view = setup({
+ nonListLayoutsEnabled: () => false,
+ search: {
+ layout,
+ groupBy: 'date',
+ sort: 'created_at',
+ sortReversed: 'true',
+ },
+ });
+
+ expect(view.writeSearch).toHaveBeenCalledExactlyOnceWith(
+ { layout: 'list' },
+ { history: 'replace' }
+ );
+ expect(view.state.layout).toBe('list');
+ expect(view.search).toMatchObject({
+ layout: 'list',
groupBy: 'date',
sort: 'created_at',
sortReversed: 'true',
- },
- });
-
- expect(view.writeSearch).toHaveBeenCalledExactlyOnceWith(
- { layout: 'list' },
- { history: 'replace' }
- );
- expect(view.state.layout).toBe('list');
- expect(view.search).toMatchObject({
- layout: 'list',
- groupBy: 'date',
- sort: 'created_at',
- sortReversed: 'true',
- });
- expect(view.state.groupBy).toBe('date');
- expect(view.state.search).toBe('keep this search');
- expect(view.state.facets).toEqual({ priority: ['high'] });
- expect(view.state.collapsedGroupIds).toEqual(['collapsed']);
-
- view.setSearch('layout', 'board');
- expect(view.state.layout).toBe('list');
- expect(view.search.layout).toBe('list');
- view.setState('layout', 'board');
- expect(view.state.layout).toBe('list');
- expect(view.search.layout).toBe('list');
-});
+ });
+ expect(view.state.groupBy).toBe('date');
+ expect(view.state.search).toBe('keep this search');
+ expect(view.state.facets).toEqual({ priority: ['high'] });
+ expect(view.state.collapsedGroupIds).toEqual(['collapsed']);
+
+ view.setSearch('layout', layout);
+ expect(view.state.layout).toBe('list');
+ expect(view.search.layout).toBe('list');
+ view.setState('layout', layout);
+ expect(view.state.layout).toBe('list');
+ expect(view.search.layout).toBe('list');
+ }
+);
it('falls back from restored board entries and from desktop boards when mobile activates', () => {
const restored = setup({
state: { layout: 'board' },
- boardEnabled: () => false,
+ nonListLayoutsEnabled: () => false,
scopedTab: 'team-tasks',
});
expect(restored.state.layout).toBe('list');
@@ -190,15 +193,15 @@ it('falls back from restored board entries and from desktop boards when mobile a
{ history: 'replace' }
);
- const [boardEnabled, setBoardEnabled] = createSignal(true);
- const desktop = setup({ search: { layout: 'board' }, boardEnabled });
+ const [nonListLayoutsEnabled, setNonListLayoutsEnabled] = createSignal(true);
+ const desktop = setup({ search: { layout: 'board' }, nonListLayoutsEnabled });
expect(desktop.state.layout).toBe('board');
expect(desktop.writeSearch).not.toHaveBeenCalled();
- setBoardEnabled(false);
+ setNonListLayoutsEnabled(false);
expect(desktop.state.layout).toBe('list');
expect(desktop.search.layout).toBe('list');
- setBoardEnabled(true);
+ setNonListLayoutsEnabled(true);
expect(desktop.state.layout).toBe('list');
desktop.setState('layout', 'board');
expect(desktop.state.layout).toBe('board');
diff --git a/apps/web/src/features/tasks-view/primitives/create-tasks-view-search.ts b/apps/web/src/features/tasks-view/primitives/create-tasks-view-search.ts
index 1ee3d8afee..d5bfed390c 100644
--- a/apps/web/src/features/tasks-view/primitives/create-tasks-view-search.ts
+++ b/apps/web/src/features/tasks-view/primitives/create-tasks-view-search.ts
@@ -17,7 +17,7 @@ export function createTasksViewSearch(options: {
) => void;
tab: Accessor<TasksTab>;
enabled: boolean;
- boardEnabled?: Accessor<boolean>;
+ nonListLayoutsEnabled?: Accessor<boolean>;
}) {
const { state, search } = options;
// Missing URL controls restore the entry snapshot, not the latest selection.
@@ -35,9 +35,9 @@ export function createTasksViewSearch(options: {
search.sort,
search.sortReversed,
search.groupBy,
- options.boardEnabled?.() ?? true,
+ options.nonListLayoutsEnabled?.() ?? true,
] as const,
- ([tab, layout, sort, sortReversed, groupBy, boardEnabled]) => {
+ ([tab, layout, sort, sortReversed, groupBy, nonListLayoutsEnabled]) => {
if (!options.enabled) return;
const requestedLayout = layout ?? entryLayout;
@@ -51,7 +51,7 @@ export function createTasksViewSearch(options: {
draft.collapsedGroupIds = [];
}
- draft.layout = boardEnabled ? requestedLayout : 'list';
+ draft.layout = nonListLayoutsEnabled ? requestedLayout : 'list';
draft.groupBy =
groupBy ??
(tab === entryTab ? entryGroupBy : TASK_DEFAULT_GROUP_BY[tab]);
@@ -61,7 +61,7 @@ export function createTasksViewSearch(options: {
})
);
- if (!boardEnabled && requestedLayout === 'board') {
+ if (!nonListLayoutsEnabled && requestedLayout !== 'list') {
options.setSearch({ layout: 'list' }, { history: 'replace' });
}
}
@@ -74,7 +74,7 @@ export function createTasksViewSearch(options: {
if (!options.enabled) return;
if (args[0] === 'layout') {
- if (options.boardEnabled?.() === false) {
+ if (options.nonListLayoutsEnabled?.() === false) {
options.setState('layout', 'list');
}
options.setSearch({ layout: state.layout });
diff --git a/apps/web/src/features/tasks-view/queries/task-board-queries.test.ts b/apps/web/src/features/tasks-view/queries/task-board-queries.test.ts
index 428d8c5f91..03fcbc754a 100644
--- a/apps/web/src/features/tasks-view/queries/task-board-queries.test.ts
+++ b/apps/web/src/features/tasks-view/queries/task-board-queries.test.ts
@@ -1,7 +1,6 @@
import { createSoupEntityRow } from '@app/features/soup/collection/rows';
import { PROPERTY_OPTION_IDS } from '@property/constants';
import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
-import { ok } from 'neverthrow';
import { createRoot } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { boardEntity, boardProperty } from '../tests/task-board-fixture';
@@ -9,18 +8,14 @@ import { createTaskBoardQueries } from './task-board-queries';
const fixture = vi.hoisted(() => ({
definitions: {} as Record<string, unknown>,
- permissions: [] as Record<string, unknown>[],
- ids: undefined as (() => readonly string[]) | undefined,
+ projectQueries: [] as Record<string, unknown>[],
+ projectIds: [] as string[],
save: vi.fn(async (_input: unknown) => {}),
- getProject: vi.fn(async (_id: string) =>
- ok({ id: 'launch', userAccessLevel: 'edit' })
- ),
}));
vi.mock('@queries/storage/document-metadata', () => ({
- useDocumentAccessLevelsQuery: (ids: () => readonly string[]) => {
- fixture.ids = ids;
- return fixture.permissions;
+ useDocumentAccessLevelsQuery: () => {
+ throw new Error('Task permissions must not be prefetched');
},
}));
vi.mock('@queries/properties/definitions', () => ({
@@ -32,11 +27,19 @@ vi.mock('@queries/properties/entity', () => ({
vi.mock('@service-storage/graphql-soup', () => ({
getGraphqlSoupClient: () => ({}),
}));
-vi.mock('@service-storage/initiative', () => ({
- initiativeClient: { get: fixture.getProject },
-}));
vi.mock('@app/features/projects/queries/project-identity', () => ({
- createProjectDetailQuery: () => ({ isSuccess: false, data: undefined }),
+ createProjectDetailQuery: (
+ _client: unknown,
+ _user: unknown,
+ id: () => string
+ ) => {
+ fixture.projectIds.push(id());
+ return (
+ fixture.projectQueries[fixture.projectIds.length - 1] ?? {
+ isSuccess: false,
+ }
+ );
+ },
}));
const disposers: (() => void)[] = [];
@@ -58,9 +61,8 @@ function setup(
}
beforeEach(() => {
- fixture.permissions = [
- { isSuccess: true, data: { documentId: 'one', accessLevel: 'edit' } },
- ];
+ fixture.projectQueries = [];
+ fixture.projectIds = [];
fixture.definitions = {
isSuccess: false,
get data() {
@@ -69,10 +71,6 @@ beforeEach(() => {
};
fixture.save.mockReset();
fixture.save.mockResolvedValue(undefined);
- fixture.getProject.mockReset();
- fixture.getProject.mockResolvedValue(
- ok({ id: 'launch', userAccessLevel: 'edit' })
- );
});
afterEach(() => {
@@ -82,33 +80,16 @@ afterEach(() => {
disposers.length = 0;
});
-it.each(['pending', 'stale'])(
- 'deduplicates permission queries and rejects %s permission data',
- (state) => {
- fixture.permissions = [
- state === 'stale'
- ? { isSuccess: true, data: { documentId: 'old', accessLevel: 'owner' } }
- : {
- isSuccess: false,
- get data() {
- throw new Error('pending permission data must not be read');
- },
- },
- ];
- const entity = boardEntity('one');
- const source = setup({
- rows: () => [
- createSoupEntityRow(entity, { groupId: 'a' }),
- createSoupEntityRow(entity, { groupId: 'b' }),
- ],
- grouping: () => 'assignee',
- });
+it('allows task editing without a permission prefetch and keeps missing-row guards', () => {
+ const source = setup();
- expect(fixture.ids?.()).toEqual(['one']);
- expect(source.actions.canEditTask('one')).toBe(false);
- expect(source.actions.canMoveTo('assignee', 'b')).toBe(false);
- }
-);
+ expect(source.actions.canEditTask('one')).toBe(true);
+ expect(source.actions.canEditTask('missing')).toBe(false);
+ expect(source.canEditProperty('missing', SYSTEM_PROPERTY_IDS.PRIORITY)).toBe(
+ false
+ );
+ expect(fixture.projectIds).toEqual([]);
+});
it('blocks overlapping property writes and restores editability when a write fails', async () => {
fixture.definitions = {
@@ -138,6 +119,12 @@ it('blocks overlapping property writes and restores editability when a write fai
await expect(source.saveProperty('one', property, values)).rejects.toThrow(
'no longer editable'
);
+ await expect(
+ source.actions.save(
+ { id: 'one', fromLane: '', toLane: PROPERTY_OPTION_IDS.PRIORITY.HIGH },
+ 'priority'
+ )
+ ).rejects.toThrow('no longer editable');
reject(new Error('rejected'));
await failed;
@@ -145,28 +132,59 @@ it('blocks overlapping property writes and restores editability when a write fai
expect(source.actions.canEditTask('one')).toBe(true);
});
-it('checks project edit access before writing and releases the task lock on rejection', async () => {
+it('attempts project moves without destination edit access and preserves column labels', async () => {
fixture.definitions = {
isSuccess: true,
data: [boardProperty(SYSTEM_PROPERTY_IDS.PROJECT, null).definition],
};
- fixture.getProject.mockResolvedValueOnce(
- ok({ id: 'launch', userAccessLevel: 'view' })
+ fixture.projectQueries = [
+ {
+ isSuccess: true,
+ data: { project: { id: 'launch', name: 'Launch', access: 'view' } },
+ },
+ ];
+ const source = setup({
+ grouping: () => 'project',
+ rows: () => [
+ createSoupEntityRow(boardEntity('one'), { groupId: 'launch' }),
+ ],
+ });
+
+ expect(source.columns().find((column) => column.id === 'launch')?.label).toBe(
+ 'Launch'
);
- const source = setup();
+ expect(fixture.projectIds).toEqual(['launch']);
+ expect(source.actions.canMoveTo('project', 'launch')).toBe(true);
+ fixture.save.mockRejectedValueOnce(new Error('server rejected'));
await expect(
- source.saveProperty(
- 'one',
- source.property('one', SYSTEM_PROPERTY_IDS.PROJECT)!,
- {
- valueType: 'ENTITY',
- refs: [{ entity_id: 'launch', entity_type: 'INITIATIVE' }],
- }
+ source.actions.save(
+ { id: 'one', fromLane: '', toLane: 'launch' },
+ 'project'
)
- ).rejects.toThrow('not editable');
+ ).rejects.toThrow('server rejected');
+ expect(fixture.save).toHaveBeenCalledOnce();
+});
- expect(fixture.getProject).toHaveBeenCalledWith('launch');
- expect(fixture.save).not.toHaveBeenCalled();
+it('releases the property lock after a server rejects a project write', async () => {
+ fixture.definitions = {
+ isSuccess: true,
+ data: [boardProperty(SYSTEM_PROPERTY_IDS.PROJECT, null).definition],
+ };
+ const source = setup();
+ const property = source.property('one', SYSTEM_PROPERTY_IDS.PROJECT)!;
+ const values = {
+ valueType: 'ENTITY' as const,
+ refs: [{ entity_id: 'launch', entity_type: 'INITIATIVE' as const }],
+ };
+ fixture.save.mockRejectedValueOnce(new Error('server rejected'));
+
+ await expect(source.saveProperty('one', property, values)).rejects.toThrow(
+ 'server rejected'
+ );
expect(source.actions.canEditTask('one')).toBe(true);
+ expect(fixture.save).toHaveBeenCalledOnce();
+
+ await source.saveProperty('one', property, values);
+ expect(fixture.save).toHaveBeenCalledTimes(2);
});
diff --git a/apps/web/src/features/tasks-view/queries/task-board-queries.ts b/apps/web/src/features/tasks-view/queries/task-board-queries.ts
index 7502fd5dd4..54df329fde 100644
--- a/apps/web/src/features/tasks-view/queries/task-board-queries.ts
+++ b/apps/web/src/features/tasks-view/queries/task-board-queries.ts
@@ -1,9 +1,6 @@
-import { canEditProject } from '@app/features/projects/core/project';
import { createProjectDetailQuery } from '@app/features/projects/queries/project-identity';
-import { toProjectDetail } from '@app/features/projects/queries/project-model';
import type { FacetSelection, SortSelection } from '@app/features/soup';
import { sortItems } from '@app/features/soup/collection/transforms';
-import { throwOnErr } from '@core/util/result';
import { soupPropertyToProperty } from '@entity/extractors-property/property-helpers';
import type { TaskEntityWithProperties } from '@entity/types/entity';
import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
@@ -11,9 +8,7 @@ import type { Property, PropertyApiValues } from '@property/types';
import { toPropertyDefinitionDomain } from '@property/utils/transforms';
import { useListPropertiesQuery } from '@queries/properties/definitions';
import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';
-import { useDocumentAccessLevelsQuery } from '@queries/storage/document-metadata';
import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
-import { initiativeClient } from '@service-storage/initiative';
import { type Accessor, createMemo, createSignal, mapArray } from 'solid-js';
import { TASK_SORT_DEFINITIONS } from '../constants';
import type { TaskBoardActions } from '../context/task-board';
@@ -38,9 +33,7 @@ export function createTaskBoardQueries(options: {
facets?: Accessor<FacetSelection>;
sort?: Accessor<SortSelection<TaskSortId>[]>;
}) {
- const [propertySaving, setPropertySaving] = createSignal<ReadonlySet<string>>(
- new Set()
- );
+ const [propertySaving, setPropertySaving] = createSignal<string[]>([]);
const entities = createMemo(() => {
const result = new Map<string, TaskEntityWithProperties>();
@@ -69,23 +62,6 @@ export function createTaskBoardQueries(options: {
return new Map(ordered.map((entity, index) => [entity.id, index]));
});
- const ids = createMemo(() => [...entities().keys()]);
- const permissions = useDocumentAccessLevelsQuery(ids);
- const editableTasks = createMemo(() => {
- const editableIds = permissions.flatMap((query) => {
- if (!query.isSuccess) {
- return [];
- }
-
- const { documentId, accessLevel } = query.data;
- const canEdit = accessLevel === 'edit' || accessLevel === 'owner';
-
- return canEdit ? [documentId] : [];
- });
-
- return new Set(editableIds);
- });
-
const definitions = useListPropertiesQuery(() => ({
scope: 'system',
includeOptions: true,
@@ -164,11 +140,7 @@ export function createTaskBoardQueries(options: {
const actions: TaskBoardActions = {
canEditTask(id) {
- if (!entities().has(id) || !editableTasks().has(id)) {
- return false;
- }
-
- return !propertySaving().has(id);
+ return entities().has(id) && !propertySaving().includes(id);
},
canMoveTo(grouping, id) {
const property = properties().get(taskBoardPropertyId(grouping));
@@ -185,21 +157,7 @@ export function createTaskBoardQueries(options: {
return !id || !!property.options?.some((option) => option.id === id);
}
- if (grouping !== 'project') {
- return true;
- }
-
- if (!options.projectsEnabled()) {
- return false;
- }
-
- if (!id) {
- return true;
- }
-
- const project = projectMap().get(id);
-
- return !!project && canEditProject(project);
+ return grouping !== 'project' || options.projectsEnabled();
},
async save(move, grouping) {
const entity = entities().get(move.id);
@@ -280,29 +238,16 @@ export function createTaskBoardQueries(options: {
throw new Error('Task is no longer editable');
}
- setPropertySaving((ids) => new Set([...ids, id]));
+ setPropertySaving((ids) => [...ids, id]);
try {
if (definition.id === SYSTEM_PROPERTY_IDS.PROJECT) {
if (!options.projectsEnabled() || apiValues.valueType !== 'ENTITY') {
throw new Error('Project editing is unavailable');
}
-
- for (const ref of apiValues.refs ?? []) {
- // A project column already holds this project's live detail.
- const project =
- projectMap().get(ref.entity_id) ??
- toProjectDetail(
- await throwOnErr(() => initiativeClient.get(ref.entity_id))
- );
-
- if (!canEditProject(project)) {
- throw new Error('Project is not editable');
- }
- }
}
- if (!entities().has(id) || !editableTasks().has(id)) {
+ if (!entities().has(id)) {
throw new Error('Task is no longer editable');
}
@@ -312,9 +257,7 @@ export function createTaskBoardQueries(options: {
],
});
} finally {
- setPropertySaving(
- (ids) => new Set([...ids].filter((pendingId) => pendingId !== id))
- );
+ setPropertySaving((ids) => ids.filter((pendingId) => pendingId !== id));
}
};
diff --git a/apps/web/src/features/tasks-view/queries/task-board.ts b/apps/web/src/features/tasks-view/queries/task-board.ts
index bb5fce52fe..076980ae00 100644
--- a/apps/web/src/features/tasks-view/queries/task-board.ts
+++ b/apps/web/src/features/tasks-view/queries/task-board.ts
@@ -77,7 +77,7 @@ function allowedBoardColumns(
return option.propertyOptionId ? [option.propertyOptionId] : [];
});
- return new Set(columnIds);
+ return columnIds;
}
export function filterTaskBoardColumns(
@@ -88,7 +88,9 @@ export function filterTaskBoardColumns(
const allowedColumnIds = allowedBoardColumns(grouping, facets);
return columns.filter((column) => {
- return allowedColumnIds.size === 0 || allowedColumnIds.has(column.id);
+ return (
+ allowedColumnIds.length === 0 || allowedColumnIds.includes(column.id)
+ );
});
}
diff --git a/apps/web/src/features/tasks-view/queries/task-gantt-queries.ts b/apps/web/src/features/tasks-view/queries/task-gantt-queries.ts
new file mode 100644
index 0000000000..a1fc6c7fb9
--- /dev/null
+++ b/apps/web/src/features/tasks-view/queries/task-gantt-queries.ts
@@ -0,0 +1,136 @@
+import type { GanttGroupMove } from '@app/components/gantt/gantt-group-drag';
+import type { TaskEntityWithProperties } from '@entity';
+import { toPropertyDefinitionDomain } from '@property/utils/transforms';
+import { useListPropertiesQuery } from '@queries/properties/definitions';
+import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';
+import { type Accessor, createMemo, createSignal } from 'solid-js';
+import { isTaskBoardMove } from '../core/task-board';
+import type { TaskGroupBy } from '../types';
+import {
+ taskBoardMoveValue,
+ taskBoardPropertyId,
+ toBoardTask,
+} from './task-board';
+import type { TasksDataSourceItem } from './use-tasks-query';
+
+/** Leaves authorization to property saves, matching task-list editing. */
+export function createTaskGanttQueries(options: {
+ rows: Accessor<readonly TasksDataSourceItem[]>;
+ grouping: Accessor<TaskGroupBy>;
+ projectsEnabled: Accessor<boolean>;
+}) {
+ const grouping = () => {
+ const group = options.grouping();
+ return group === 'none' ||
+ group === 'date' ||
+ (group === 'project' && !options.projectsEnabled())
+ ? undefined
+ : group;
+ };
+ const tasks = createMemo(() => {
+ const result = new Map<string, TaskEntityWithProperties>();
+ for (const row of options.rows()) {
+ if (row.kind === 'entity') result.set(row.entity.id, row.entity);
+ }
+ return result;
+ });
+ const definitions = useListPropertiesQuery(
+ () => ({ scope: 'system', includeOptions: true }),
+ () => !!grouping()
+ );
+ const groupProperty = createMemo(() => {
+ const group = grouping();
+ if (!group || !definitions.isSuccess) return;
+ const item = definitions.data.find(
+ (item) =>
+ ('definition' in item ? item.definition : item).id ===
+ taskBoardPropertyId(group)
+ );
+ if (!item) return;
+ const property = toPropertyDefinitionDomain(
+ 'definition' in item ? item.definition : item,
+ 'property_options' in item ? item.property_options : []
+ );
+ const expected =
+ group === 'status' || group === 'priority' ? 'SELECT_STRING' : 'ENTITY';
+ return property.isSystem &&
+ property.owner.scope === 'system' &&
+ !property.isMetadata &&
+ (!property.specificEntityType ||
+ property.specificEntityType === 'TASK') &&
+ property.valueType === expected
+ ? property
+ : undefined;
+ });
+ const destinations = createMemo(() =>
+ options
+ .rows()
+ .flatMap((row) => (row.kind === 'group-header' ? [row.groupId] : []))
+ );
+ const [saving, setSaving] = createSignal<string[]>([]);
+ const save = useBulkSaveEntityPropertiesMutation();
+ const canDrag = (id: string) =>
+ tasks().has(id) && !saving().includes(id) && !!groupProperty();
+
+ const resolveMove = (move: GanttGroupMove) => {
+ const group = grouping();
+ const property = groupProperty();
+ const task = tasks().get(move.id);
+ if (
+ !group ||
+ !property ||
+ !task ||
+ !canDrag(move.id) ||
+ !destinations().includes(move.toGroup)
+ )
+ return;
+ const boardTask = toBoardTask(task);
+ const boardMove = {
+ id: move.id,
+ fromLane: move.fromGroup,
+ toLane: move.toGroup,
+ };
+ if (!isTaskBoardMove(boardTask, group, boardMove)) return;
+ if (
+ group === 'assignee' &&
+ !move.toGroup &&
+ boardTask.assigneeIds.some((id) => id !== move.fromGroup)
+ )
+ return;
+ if (
+ (group === 'status' || group === 'priority') &&
+ !(
+ (!move.toGroup && group === 'priority') ||
+ property.options?.some((option) => option.id === move.toGroup)
+ )
+ )
+ return;
+ return { group, property, task, boardMove };
+ };
+
+ return {
+ canDrag,
+ canMove: (move: GanttGroupMove) => !!resolveMove(move),
+ async moveGroup(move: GanttGroupMove) {
+ const resolved = resolveMove(move);
+ if (!resolved)
+ throw new Error('Task or destination is no longer editable');
+ const { task, group, property, boardMove } = resolved;
+ setSaving((ids) => [...ids, move.id]);
+ try {
+ await save.mutateAsync({
+ properties: [
+ {
+ entityId: move.id,
+ entityType: 'TASK',
+ property,
+ apiValues: taskBoardMoveValue(task, group, boardMove),
+ },
+ ],
+ });
+ } finally {
+ setSaving((ids) => ids.filter((id) => id !== move.id));
+ }
+ },
+ };
+}
diff --git a/apps/web/src/features/tasks-view/queries/task-gantt.ts b/apps/web/src/features/tasks-view/queries/task-gantt.ts
new file mode 100644
index 0000000000..1fc642044f
--- /dev/null
+++ b/apps/web/src/features/tasks-view/queries/task-gantt.ts
@@ -0,0 +1,14 @@
+import type { TaskEntityWithProperties } from '@entity';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+
+/** Timeline dates come from the existing task payload, not another query. */
+export function taskGanttDates(task: TaskEntityWithProperties) {
+ const due = task.properties?.find(
+ (property) => property.definition.id === SYSTEM_PROPERTY_IDS.DUE_DATE
+ )?.value;
+
+ return {
+ start: task.createdAt,
+ end: due?.type === 'Date' ? due.value : undefined,
+ };
+}
diff --git a/apps/web/src/features/tasks-view/tasks-content.tsx b/apps/web/src/features/tasks-view/tasks-content.tsx
index a811aa0b14..0f98e82897 100644
--- a/apps/web/src/features/tasks-view/tasks-content.tsx
+++ b/apps/web/src/features/tasks-view/tasks-content.tsx
@@ -1,7 +1,8 @@
import SpinnerIcon from '@phosphor/spinner.svg';
-import { Show, Suspense } from 'solid-js';
+import { Match, Suspense, Switch } from 'solid-js';
import { TaskList } from './components/task-list/TaskList';
import { TasksBoard } from './tasks-board';
+import { TasksGantt } from './tasks-gantt';
import { useTasksView } from './tasks-view-context';
export function TasksLoading() {
@@ -12,7 +13,7 @@ export function TasksLoading() {
);
}
-/** Renders either layout from the host's task scope and navigation capabilities. */
+/** Renders the selected layout from the host's task scope and navigation capabilities. */
export function TasksContent(props: {
ref?: (element: HTMLDivElement) => void;
}) {
@@ -20,12 +21,17 @@ export function TasksContent(props: {
return (
<Suspense fallback={<TasksLoading />}>
- <Show
- when={state.layout === 'board'}
- fallback={<TaskList ref={props.ref} />}
- >
- <TasksBoard ref={props.ref} />
- </Show>
+ <Switch>
+ <Match when={state.layout === 'board'}>
+ <TasksBoard ref={props.ref} />
+ </Match>
+ <Match when={state.layout === 'gantt'}>
+ <TasksGantt ref={props.ref} />
+ </Match>
+ <Match when={state.layout === 'list'}>
+ <TaskList ref={props.ref} />
+ </Match>
+ </Switch>
</Suspense>
);
}
diff --git a/apps/web/src/features/tasks-view/tasks-gantt.tsx b/apps/web/src/features/tasks-view/tasks-gantt.tsx
new file mode 100644
index 0000000000..00dbfe295a
--- /dev/null
+++ b/apps/web/src/features/tasks-view/tasks-gantt.tsx
@@ -0,0 +1,160 @@
+import { Gantt } from '@app/components/gantt/gantt';
+import { ganttGroupPlacement } from '@app/components/gantt/gantt-group-placement';
+import {
+ resolveEntityActionViewContext,
+ toSingleEntityActionListState,
+} from '@app/features/next-soup/actions';
+import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';
+import { SoupEntityContextMenu } from '@app/features/soup';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { toast } from '@core/component/Toast/Toast';
+import { getTaskStatusOptionId, type TaskEntityWithProperties } from '@entity';
+import { PropertyValueIcon } from '@property/component/propertyValue';
+import { usePropertyUserDisplay } from '@property/hooks/usePropertyUserDisplay';
+import { PROPERTY_OPTION_IDS } from '@property/identifiers';
+import type { Accessor, JSX } from 'solid-js';
+import { TASK_SORT_DEFINITIONS } from './constants';
+import { taskGanttDates } from './queries/task-gantt';
+import { createTaskGanttQueries } from './queries/task-gantt-queries';
+import { useTasksView } from './tasks-view-context';
+import { TaskGanttView } from './views/task-gantt-view';
+
+/** Reuses the host's filtered task source and task-opening capability. */
+export function TasksGantt(props: { ref?: (element: HTMLDivElement) => void }) {
+ const context = useTasksView();
+ const { source, state, setState, openTask } = context;
+ const panel = useSplitPanelOrThrow();
+ const layout = useSplitLayout();
+ const createTask = (dueDate?: Date) =>
+ layout.popoverSplit({
+ type: 'component',
+ id: 'task-compose',
+ params: { initialDueDate: dueDate },
+ });
+ const onCreate = () =>
+ context.createTask ?? (!context.scopeKey ? createTask : undefined);
+ const queries = createTaskGanttQueries({
+ rows: source.boardRows ?? source.items,
+ grouping: () => state.groupBy,
+ projectsEnabled: context.projectsEnabled,
+ });
+ const viewContext = () =>
+ resolveEntityActionViewContext({
+ activeListView: panel.handle.content().id,
+ activeTab: state.tab,
+ });
+ const onOpen = (task: TaskEntityWithProperties, event: MouseEvent) => {
+ const opened = openTask(
+ { id: task.id, fallbackName: task.name },
+ { event }
+ );
+
+ if (opened) return;
+
+ void openEntityInSplitFromUnifiedList(task, {
+ splitHandle: panel.handle,
+ referredFrom: 'tasks',
+ openInNewSplit:
+ event.shiftKey || event.metaKey || event.ctrlKey || event.altKey,
+ });
+ };
+ const renderEntity = (
+ task: Accessor<TaskEntityWithProperties>,
+ label: JSX.Element
+ ) => {
+ const list = toSingleEntityActionListState(task);
+ const deadlineWarning = () => {
+ const entity = task();
+ const status = getTaskStatusOptionId(entity);
+ return (
+ !(entity.subType?.type === 'task' && entity.subType.is_completed) &&
+ status !== PROPERTY_OPTION_IDS.STATUS.COMPLETED &&
+ status !== PROPERTY_OPTION_IDS.STATUS.CANCELED
+ );
+ };
+ return (
+ <SoupEntityContextMenu
+ as="div"
+ entity={task()}
+ list={list}
+ selectedEntities={() => []}
+ viewContext={viewContext()}
+ >
+ {label}
+ <Gantt.Bar
+ {...taskGanttDates(task())}
+ title={task().name}
+ deadlineWarning={deadlineWarning()}
+ onClick={(event) => onOpen(task(), event)}
+ >
+ <PropertyValueIcon
+ optionId={getTaskStatusOptionId(task()) ?? ''}
+ class="size-3.5 shrink-0"
+ />
+ <span class="min-w-0 truncate">{task().name}</span>
+ </Gantt.Bar>
+ </SoupEntityContextMenu>
+ );
+ };
+
+ return (
+ <TaskGanttView
+ ref={props.ref}
+ source={source}
+ groupBy={state.groupBy}
+ groupMoves={{
+ scope: JSON.stringify([
+ context.scopeKey,
+ state.tab,
+ state.groupBy,
+ state.search,
+ state.facets,
+ ]),
+ canDrag: queries.canDrag,
+ canDrop: queries.canMove,
+ getPlacement: (move) =>
+ ganttGroupPlacement({
+ items: source.items(),
+ move,
+ getEntity: (row) =>
+ row.kind === 'entity' ? row.entity : undefined,
+ getGroup: (row) =>
+ row.kind === 'section-header' ? undefined : row.groupId,
+ compare: (left, right) => {
+ for (const selection of state.sort) {
+ const definition = TASK_SORT_DEFINITIONS.find(
+ (value) => value.id === selection.id
+ );
+ const result =
+ (definition?.compare(left, right) ?? 0) *
+ (selection.reversed ? -1 : 1);
+ if (result) return result;
+ }
+ return 0;
+ },
+ }),
+ onMove: async (move) => {
+ await queries.moveGroup(move);
+ try {
+ await source.refresh?.();
+ } catch {
+ toast.failure('Task moved, but the timeline could not refresh');
+ }
+ },
+ }}
+ createAssigneeName={(id) => usePropertyUserDisplay(id).name}
+ isGroupExpanded={(id) => !state.collapsedGroupIds.includes(id)}
+ onToggleGroup={(id) =>
+ setState('collapsedGroupIds', (ids) =>
+ ids.includes(id)
+ ? ids.filter((current) => current !== id)
+ : [...ids, id]
+ )
+ }
+ onCreate={onCreate() && ((dates) => onCreate()?.(dates.end))}
+ onOpen={onOpen}
+ renderEntity={renderEntity}
+ />
+ );
+}
diff --git a/apps/web/src/features/tasks-view/tasks-tab-search.ts b/apps/web/src/features/tasks-view/tasks-tab-search.ts
index c5dc099c44..8d2666c894 100644
--- a/apps/web/src/features/tasks-view/tasks-tab-search.ts
+++ b/apps/web/src/features/tasks-view/tasks-tab-search.ts
@@ -11,7 +11,7 @@ export const tasksTabSearch = {
namespace: 'tasks',
schema: z.object({
tab: z.enum(['my-tasks', 'created-by-me', 'team-tasks', 'projects']),
- layout: z.enum(['list', 'board']).optional(),
+ layout: z.enum(['list', 'board', 'gantt']).optional(),
sort: z.enum(['updated_at', 'created_at', 'viewed_at']).optional(),
sortReversed: z.enum(['true', 'false']).optional(),
groupBy: z
diff --git a/apps/web/src/features/tasks-view/tasks-view-context.tsx b/apps/web/src/features/tasks-view/tasks-view-context.tsx
index 2cf8913f46..43a57e8ec7 100644
--- a/apps/web/src/features/tasks-view/tasks-view-context.tsx
+++ b/apps/web/src/features/tasks-view/tasks-view-context.tsx
@@ -9,7 +9,10 @@ import { setSidebarSectionCollapsed } from '@app/components/view-shell';
import { useMobileSearchText } from '@app/features/command/mobile/use-mobile-search-text';
import { normalizeFacetSelection } from '@app/features/soup';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { enableProjects } from '@app/lib/core/constant/featureFlags';
+import {
+ enableGantt,
+ enableProjects,
+} from '@app/lib/core/constant/featureFlags';
import { makePersistedState } from '@app/lib/persistence';
import {
createSearchParams,
@@ -81,6 +84,8 @@ export type TasksViewProviderProps = ContextProviderProps & {
options?: EntityDetailNavigationOptions
) => boolean;
onCloseTask?: () => void;
+ /** Host-owned task creation, including scope and permissions for embedded views. */
+ onCreateTask?: (dueDate?: Date) => void;
};
export type TasksListActivationMetadata = {
@@ -96,7 +101,9 @@ type TasksListController = ListController<
export type TasksViewContext = {
scopeKey?: string;
state: Store<TasksViewState>;
+ createTask?: (dueDate?: Date) => void;
projectsEnabled: Accessor<boolean>;
+ ganttEnabled: Accessor<boolean>;
setState: SetStoreFunction<TasksViewState>;
selectedTask: Accessor<TaskDetailTarget | undefined>;
source: TasksDataSource;
@@ -150,6 +157,8 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
const tagSetsReady = useTagSetsReady();
const projectsFlag = useFeatureFlag(enableProjects);
const projectsEnabled = () => projectsFlag().enabled;
+ const ganttFlag = useFeatureFlag(enableGantt);
+ const ganttEnabled = () => ganttFlag().enabled;
const initial = props.initialState ?? {};
const initialTab = initial.tab ?? 'my-tasks';
@@ -190,13 +199,19 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
() => persistedState.search,
() => !props.scopeKey && panel.handle.isActive()
);
- // A pending or disabled rollout must not overwrite the saved Projects tab.
+ // Rollout fallbacks must not overwrite saved tab or layout selections.
const state = mergeProps(persistedState, {
get search() {
return searchText();
},
get layout() {
- return isTouchDevice() ? 'list' : persistedState.layout;
+ if (
+ isTouchDevice() ||
+ (persistedState.layout === 'gantt' && !ganttEnabled())
+ ) {
+ return 'list';
+ }
+ return persistedState.layout;
},
get groupBy() {
if (state.layout !== 'board') {
@@ -227,12 +242,13 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
setSearch: setTabSearch,
tab: routeTab,
enabled: syncSearch,
- boardEnabled: () => !isTouchDevice(),
+ nonListLayoutsEnabled: () => !isTouchDevice(),
});
const currentSearch = () =>
tasksTabSearchCodec.serialize({
tab: state.tab,
- layout: state.layout,
+ // Preserve a rollout-hidden Gantt selection across task navigation.
+ layout: isTouchDevice() ? 'list' : persistedState.layout,
sort: state.sort[0]?.id,
sortReversed: state.sort[0]
? state.sort[0].reversed
@@ -412,8 +428,12 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
return {
scopeKey: props.scopeKey,
+ get createTask() {
+ return props.onCreateTask;
+ },
state,
projectsEnabled,
+ ganttEnabled,
setState: setStateWithSearch,
selectedTask,
source,
diff --git a/apps/web/src/features/tasks-view/types.ts b/apps/web/src/features/tasks-view/types.ts
index 0c6d54a114..54b8dadf82 100644
--- a/apps/web/src/features/tasks-view/types.ts
+++ b/apps/web/src/features/tasks-view/types.ts
@@ -35,7 +35,7 @@ export type TaskDetailTarget = {
};
export type TasksViewState = {
- layout: 'list' | 'board';
+ layout: 'list' | 'board' | 'gantt';
tab: TasksTab;
search: string;
groupBy: TaskGroupBy;
diff --git a/apps/web/src/features/tasks-view/views/task-gantt-view.tsx b/apps/web/src/features/tasks-view/views/task-gantt-view.tsx
new file mode 100644
index 0000000000..676f2af16d
--- /dev/null
+++ b/apps/web/src/features/tasks-view/views/task-gantt-view.tsx
@@ -0,0 +1,400 @@
+import type { GanttCreation } from '@app/components/gantt/create-gantt-creation';
+import { Gantt } from '@app/components/gantt/gantt';
+import { deriveGanttRange } from '@app/components/gantt/gantt-date';
+import { UserIcon } from '@core/component/UserIcon';
+import {
+ getPropertyOptionLabel,
+ getTaskStatusOptionId,
+ type TaskEntityWithProperties,
+} from '@entity';
+import CalendarIcon from '@phosphor/calendar-blank.svg';
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import CircleDashedIcon from '@phosphor/circle-dashed.svg';
+import FolderIcon from '@phosphor/folder-simple.svg';
+import SpinnerIcon from '@phosphor/spinner.svg';
+import { PropertyValueIcon } from '@property/component/propertyValue';
+import { Button, cn, Layer } from '@ui';
+import type { ComponentProps } from 'solid-js';
+import {
+ type Accessor,
+ createMemo,
+ type JSX,
+ Match,
+ Show,
+ Switch,
+} from 'solid-js';
+import { STATUS_GROUP_HEADER_TINTS } from '../components/task-list/TaskGroupHeader';
+import { taskGanttDates } from '../queries/task-gantt';
+import type {
+ TasksDataSource,
+ TasksDataSourceItem,
+} from '../queries/use-tasks-query';
+import type { TaskGroupBy } from '../types';
+
+function AssigneeLabel(props: {
+ id: string;
+ createName: (id: Accessor<string>) => Accessor<string>;
+}) {
+ const name = props.createName(() => props.id);
+ return <>{name()}</>;
+}
+
+export function TaskGanttView(props: {
+ createAssigneeName: (id: Accessor<string>) => Accessor<string>;
+ source: TasksDataSource;
+ groupBy: TaskGroupBy;
+ groupMoves: Omit<ComponentProps<typeof Gantt.GroupDrag>, 'children'>;
+ isGroupExpanded: (id: string) => boolean;
+ onToggleGroup: (id: string) => void;
+ onOpen: (task: TaskEntityWithProperties, event: MouseEvent) => void;
+ onCreate?: (dates: GanttCreation) => void;
+ renderEntity: (
+ task: Accessor<TaskEntityWithProperties>,
+ label: JSX.Element
+ ) => JSX.Element;
+ ref?: (element: HTMLDivElement) => void;
+}) {
+ const dates = createMemo(() =>
+ (props.source.boardRows ?? props.source.items)().flatMap((row) =>
+ row.kind === 'entity' ? [taskGanttDates(row.entity)] : []
+ )
+ );
+ const range = createMemo(() => deriveGanttRange(dates()));
+ const error = () => props.source.error?.();
+ const hasGlobalLoadMoreRow = () =>
+ props.source
+ .items()
+ .some((row) => row.kind === 'load-more' && row.groupId === undefined);
+ const loadMore = (row: TasksDataSourceItem) => {
+ if (row.kind !== 'load-more') return;
+
+ if (row.groupId !== undefined) {
+ void props.source.loadMoreGroup(row.groupId);
+ return;
+ }
+
+ void props.source.loadMore?.();
+ };
+
+ return (
+ <div ref={props.ref} class="flex size-full min-h-0 min-w-0 flex-col">
+ <Switch>
+ <Match when={props.source.isLoading?.()}>
+ <div class="grid flex-1 place-items-center text-ink-muted">
+ <SpinnerIcon
+ aria-label="Loading timeline"
+ class="size-5 animate-spin"
+ />
+ </div>
+ </Match>
+ <Match when={error() && !props.source.items().length}>
+ <div
+ role="alert"
+ class="flex flex-1 flex-col items-center justify-center gap-3 text-sm text-ink-muted"
+ >
+ Tasks couldn’t be loaded.
+ <Button onClick={() => void props.source.refresh?.()}>
+ Try again
+ </Button>
+ </div>
+ </Match>
+ <Match when={!props.source.items().length && !props.onCreate}>
+ <div class="grid flex-1 place-items-center text-sm text-ink-muted">
+ No matching tasks
+ </div>
+ </Match>
+ <Match when={true}>
+ <Show when={error()}>
+ <p role="status" class="px-3 py-2 text-xs text-ink-muted">
+ Could not refresh tasks. Showing the last loaded timeline.
+ </p>
+ </Show>
+ <Gantt.Root range={range()} labelWidth={0}>
+ <Gantt.SidebarToggle />
+ <Gantt.Controls>
+ <Gantt.TodayButton />
+ <Gantt.Settings />
+ </Gantt.Controls>
+ <Gantt.GroupDrag {...props.groupMoves}>
+ <Gantt.Chart>
+ <Gantt.Header />
+ <Gantt.Rows
+ items={props.source.items()}
+ getKey={(row) => row.id}
+ getPanelKey={(row) =>
+ row.kind === 'entity' || row.kind === 'load-more'
+ ? (row.groupId ?? '')
+ : undefined
+ }
+ virtualize
+ renderDropPreview={(move) => {
+ const task = (
+ props.source.boardRows ?? props.source.items
+ )().find(
+ (row) =>
+ row.kind === 'entity' && row.entity.id === move.id
+ );
+ return (
+ task?.kind === 'entity' && (
+ <Gantt.DropPreview
+ {...taskGanttDates(task.entity)}
+ title={task.entity.name}
+ />
+ )
+ );
+ }}
+ >
+ {(row) => (
+ <Gantt.Row>
+ <Show
+ when={
+ row.kind !== 'section-header' &&
+ row.groupId !== undefined
+ }
+ >
+ <Gantt.GroupDrop
+ id={row.id}
+ groupId={'groupId' in row ? (row.groupId ?? '') : ''}
+ />
+ </Show>
+ <Switch>
+ <Match when={row.kind === 'entity' ? row : undefined}>
+ {(item) => (
+ <Gantt.DragItem
+ id={item().entity.id}
+ key={item().id}
+ groupId={item().groupId ?? ''}
+ label={item().entity.name}
+ >
+ {props.renderEntity(
+ () => item().entity,
+ <Gantt.Label>
+ <Layer depth={2}>
+ <button
+ type="button"
+ class="flex h-7 w-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md px-2 text-left text-xs outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
+ title={item().entity.name}
+ onClick={(event) =>
+ props.onOpen(item().entity, event)
+ }
+ >
+ <PropertyValueIcon
+ optionId={
+ getTaskStatusOptionId(
+ item().entity
+ ) ?? ''
+ }
+ class="size-3.5 shrink-0"
+ />
+ <span class="min-w-0 flex-1 leading-3.5">
+ <span class="block truncate">
+ {item().entity.name}
+ </span>
+ <Gantt.DateHint
+ {...taskGanttDates(item().entity)}
+ class="leading-3"
+ />
+ </span>
+ </button>
+ </Layer>
+ </Gantt.Label>
+ )}
+ </Gantt.DragItem>
+ )}
+ </Match>
+ <Match
+ when={row.kind === 'group-header' ? row : undefined}
+ >
+ {(group) => (
+ <Gantt.GroupHeader
+ class={
+ props.groupBy === 'status'
+ ? STATUS_GROUP_HEADER_TINTS[group().groupId]
+ : undefined
+ }
+ >
+ <button
+ type="button"
+ aria-expanded={props.isGroupExpanded(
+ group().groupId
+ )}
+ class="flex h-full w-full min-w-0 items-center gap-2.5 rounded-[inherit] px-2 py-1.5 text-left text-xs font-semibold tracking-tight outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
+ onClick={() =>
+ props.onToggleGroup(group().groupId)
+ }
+ >
+ <Layer depth={3}>
+ <span class="flex size-4.5 shrink-0 items-center justify-center rounded-xs group-hover/header:bg-ink/5">
+ <CaretRightIcon
+ class={cn(
+ 'size-2.5 transition-transform',
+ props.isGroupExpanded(
+ group().groupId
+ ) && 'rotate-90'
+ )}
+ />
+ </span>
+ </Layer>
+ <Switch>
+ <Match when={!group().groupId}>
+ <CircleDashedIcon class="size-3.5 shrink-0 text-ink-extra-muted" />
+ </Match>
+ <Match
+ when={
+ props.groupBy === 'status' ||
+ props.groupBy === 'priority'
+ }
+ >
+ <PropertyValueIcon
+ optionId={group().groupId}
+ class="size-3.5 shrink-0"
+ />
+ </Match>
+ <Match when={props.groupBy === 'assignee'}>
+ <UserIcon
+ id={group().groupId}
+ size="sm"
+ suppressClick
+ showTooltip={false}
+ />
+ </Match>
+ <Match when={props.groupBy === 'project'}>
+ <FolderIcon class="size-3.5 shrink-0" />
+ </Match>
+ <Match when={props.groupBy === 'date'}>
+ <CalendarIcon class="size-3.5 shrink-0" />
+ </Match>
+ </Switch>
+ <span class="truncate">
+ <Show
+ when={
+ props.groupBy === 'assignee' &&
+ group().groupId
+ }
+ fallback={
+ props.groupBy === 'status' ||
+ props.groupBy === 'priority'
+ ? (getPropertyOptionLabel(
+ group().groupId
+ ) ?? group().label)
+ : group().label
+ }
+ >
+ <AssigneeLabel
+ id={group().groupId}
+ createName={props.createAssigneeName}
+ />
+ </Show>
+ </span>
+ <Show when={group().count !== undefined}>
+ <span class="shrink-0 rounded-full bg-ink/10 px-1.5 py-px text-xs font-medium tabular-nums text-ink-extra-muted">
+ {group().count}
+ </span>
+ </Show>
+ </button>
+ </Gantt.GroupHeader>
+ )}
+ </Match>
+ <Match
+ when={row.kind === 'load-more' ? row : undefined}
+ >
+ {(more) => (
+ <>
+ <div class="absolute inset-0">
+ <Gantt.Label>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={more().isLoading}
+ onClick={() => loadMore(more())}
+ >
+ <Show when={more().isLoading}>
+ <SpinnerIcon class="size-3 animate-spin" />
+ </Show>
+ {more().isLoading
+ ? 'Loading tasks…'
+ : 'Load more tasks'}
+ </Button>
+ </Gantt.Label>
+ </div>
+ <Gantt.Pagination>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={more().isLoading}
+ onClick={() => loadMore(more())}
+ >
+ <Show when={more().isLoading}>
+ <SpinnerIcon class="size-3 animate-spin" />
+ </Show>
+ {more().isLoading
+ ? 'Loading tasks…'
+ : 'Load more tasks'}
+ </Button>
+ </Gantt.Pagination>
+ </>
+ )}
+ </Match>
+ <Match
+ when={row.kind === 'section-header' ? row : undefined}
+ >
+ {(section) => (
+ <Gantt.Label>{section().label}</Gantt.Label>
+ )}
+ </Match>
+ </Switch>
+ </Gantt.Row>
+ )}
+ </Gantt.Rows>
+ <Show
+ when={props.source.hasMore?.() && !hasGlobalLoadMoreRow()}
+ >
+ <Gantt.Row>
+ <div class="absolute inset-0">
+ <Gantt.Label>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={props.source.isLoadingMore?.()}
+ onClick={() => void props.source.loadMore?.()}
+ >
+ <Show when={props.source.isLoadingMore?.()}>
+ <SpinnerIcon class="size-3 animate-spin" />
+ </Show>
+ {props.source.isLoadingMore?.()
+ ? 'Loading tasks…'
+ : 'Load more tasks'}
+ </Button>
+ </Gantt.Label>
+ </div>
+ <Gantt.Pagination>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={props.source.isLoadingMore?.()}
+ onClick={() => void props.source.loadMore?.()}
+ >
+ <Show when={props.source.isLoadingMore?.()}>
+ <SpinnerIcon class="size-3 animate-spin" />
+ </Show>
+ {props.source.isLoadingMore?.()
+ ? 'Loading tasks…'
+ : 'Load more tasks'}
+ </Button>
+ </Gantt.Pagination>
+ </Gantt.Row>
+ </Show>
+ <Gantt.TodayMarker />
+ <Gantt.CreateArea
+ minDate={new Date()}
+ onCreate={props.onCreate}
+ />
+ </Gantt.Chart>
+ </Gantt.GroupDrag>
+ <Gantt.ZoomControls />
+ </Gantt.Root>
+ </Match>
+ </Switch>
+ </div>
+ );
+}
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index f79319b449..5da71fcb75 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -1296,6 +1296,14 @@ html[data-touch-device='true'] :is(
to { height: 0; }
}
+/* Match the item panels' 200ms exit; the inset follows responsive width changes. */
+@keyframes gantt-scene-close {
+ from,
+ to {
+ left: var(--gantt-closing-inset);
+ }
+}
+
@keyframes typing-dot {
0% { transform: scale(1) translateY(0 ); }
50% { transform: scale(1.5) translateY(-2px); }
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index d6536396ea..ab759c2df8 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -163,6 +163,12 @@ export const enableTasksReviews = defineFlag({
default: onInDev,
});
+/** Gantt layouts stay hidden until enabled remotely or with a local override. */
+export const enableGantt = defineFlag({
+ key: 'enable-gantt',
+ env: 'ENABLE_GANTT',
+});
+
// Claude Cloud: the built-in @claude mention and agent assignee, its Runtimes
// connection card, and harness/model discovery. Off until PostHog enables it,
// including in dev; override locally with VITE_CLAUDE_CLOUD.
diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.md
index 82f6d9c8cd..52860298d7 100644
--- a/docs/AGENT_GUIDE/tasks.md
+++ b/docs/AGENT_GUIDE/tasks.md
@@ -48,10 +48,15 @@ Filters (including Tags). The mobile bottom dock has the Ask AI input, a separat
button, and Search.
Mobile does not show the separate layout, sort, group, and filter toolbar.
Use the compact sliders drawer for task-list controls; project task lists use the
-same drawer. Mobile supports List only. Opening a Board link or restoring a Board
-entry automatically selects List and replaces that host's layout URL parameter,
-without adding a history entry or clearing search, sorting, grouping, or filters.
-The desktop Board layout remains available.
+same drawer. Mobile supports List only. Opening a Board or Gantt link, or
+restoring either layout, automatically selects List and replaces that host's
+layout URL parameter without adding history or clearing search, sorting,
+grouping, or filters. Desktop supports List and Board, plus Gantt when the
+PostHog `enable-gantt` flag is enabled. This flag also gates project-task and
+Projects collection timelines. When the flag is disabled or still loading,
+saved Gantt layouts and Gantt URLs render List without clearing the selected
+layout, so enabling the flag restores Gantt. The local override is
+`VITE_ENABLE_GANTT=true` (or `false` to force it off).
**Keyboard:** **H** and **←** collapse the focused item or its parent group.
On a focused group header, **H** collapses only that group; pressing it again
@@ -88,6 +93,144 @@ should appear immediately and stay visible through both responses in the list,
task header, side panel, and a reopened picker. A rejected save should remove only
the optimistic tag. Repeat with an existing assignment and with removal.
+## Gantt layout
+
+Choose **Gantt** from the **Task layout** dropdown to see task timelines.
+The same option is available in a project's Tasks section. The timeline uses
+Created at as the start and Due date as the end; no separate Start date is
+created or saved. Bars without a due date fade to transparent at the right edge.
+The fade affects only the bar fill; labels remain visible.
+Their displayed tail is a visual placeholder, not a saved deadline. Invalid or
+missing start dates and due dates before creation are identified rather than
+silently displayed as valid intervals.
+The calendar fills the available pane width and height, including empty space
+below loaded rows. Zooming, pane resizing, and loading earlier items preserve the
+visible calendar position. On first load, the chart centers on today after its
+viewport is measurable. Refetches and later resizes do not reset the scroll.
+Bars use the app's neutral depth-two surface without an outline, with a small
+status-colored indicator. In light mode, bars have a stronger solid neutral fill,
+and item panels have a subtle neutral fill and clearer border.
+Dark-mode base surfaces stay unchanged. Active items due within seven calendar
+days use a danger-color background gradient at the due-date edge, blending into
+the neutral fill toward the left and strengthening as the deadline approaches.
+Due-today and overdue items use the strongest tint; completed, canceled, and
+undated items stay neutral.
+Deadline tints and the Today marker refresh at local midnight and when a tab
+becomes visible or focused again.
+The tint only appears when the actual end is inside the calendar range.
+Bar text stays inside the visible portion of its bar as you scroll, zoom, or
+open the item drawer, and truncates in narrow segments.
+The full-width date header stays visible during vertical scrolling; the pointer's
+date label stays in that header, and the vertical scrollbar begins below it.
+Timeline-edge fades stay within the date header, beneath its floating buttons.
+Fades start at the calendar edges, span up to 128px, and shrink in narrow calendars.
+The floating item list uses separate rounded, bordered, low-contrast panels for
+consecutive groups. Items clip inside their panels and use the same height and
+padding as bars, with transparent backgrounds and hover-only highlighting.
+Group headers match the normal list's rounded surfaces, status tints, disclosure
+controls, and count pills.
+The list starts expanded in wide panes and collapses automatically below 640px
+until you explicitly choose open or closed. That choice stays in effect across
+pane resizes while the chart is mounted. Use the top-left toggle to change it.
+The drawer slides in and out, respecting reduced motion, and shares vertical
+scrolling with the bars without shifting dates or reserving calendar width.
+Clicking or focusing the calendar keeps the list open.
+Escape or the toggle closes it; focus returns to the toggle when closing a focused
+item. Closed drawer items are not focusable.
+Task and project context menus remain available on drawer items. **Today** and
+timeline settings are separate floating buttons at the top right.
+Hold **Ctrl** or **Cmd** and scroll to zoom between 4 and 80 pixels per day, keeping the date
+under the pointer in place. Hold the middle mouse button and drag to pan both axes,
+including from bars or item panels, without changing dates or grouping properties.
+Release the button, press Escape, or move focus away from the window to stop panning.
+Ordinary scrolling is unchanged. Period presets in the settings menu also set zoom;
+calendar labels adapt to the zoom level.
+Floating controls at the chart's bottom right zoom out/in around the visible
+calendar's center. The percentage/reset button stays visible; adjacent minus/plus
+buttons sit to its left and appear on hover, keyboard focus, or during Ctrl/Cmd scroll zoom.
+Minus/plus controls have no invisible hit area while auto-hidden; when revealed,
+they remain visible but disabled at zoom limits or during edits.
+The reset/value button matches the zoom buttons' height and has a fixed width
+for the full percentage range. Click it to reset to 100%; the same zoom limits apply.
+Controls stay fixed during scrolling and are disabled during date drags.
+
+**Today** smoothly centers the current day, except when reduced motion is enabled;
+initial centering is immediate. Its line extends into the calendar header, stays
+behind bars, and clips outside the left item panels, including their gaps and
+rounded corners, until the drawer finishes sliding closed. Only items and bars
+have hover feedback, not full calendar rows.
+The settings menu
+changes the displayed period (Day, Week, Month), toggles calendar lines, and
+changes their spacing (Daily, Weekly, Monthly) and
+style (Solid, Dashed). Grid settings do not change item dates. Compact bold month
+names share the main date band and switch from abbreviated names at Month zoom
+to full names at Week/Day zoom. The pinned month always includes its year; other
+months show the year after January only, when a new year starts. Unpinned month
+text is centered on its date mark; a trailing year does not shift that center.
+Short, higher-contrast date marks stay anchored to their calendar dates, even
+when month text hides an overlapping day number. Marks do not move with the sticky month
+labels, so daily gaps stay equal across month boundaries. Month/year labels fade
+as the next month pushes them toward the left edge, before the expand/collapse
+button.
+Week-scale date marks divide each month into four near-even calendar-day sections,
+not Monday-based weeks. Weekly grid lines use the same sections. Day spacing and
+month widths still follow the real calendar, including leap-year February.
+Labels remain visible during horizontal scrolling,
+and the date header remains visible during vertical scrolling. The calendar
+extends as you approach either horizontal edge, even during continuous scrolling.
+Left-edge rebasing preserves the current visible date immediately; right-edge
+extension does not write the scroll position. Click a task label or bar to open
+the task; right-click either for the same actions as its list item.
+
+Timeline dates are read-only: bars have no resize handles or end-date editing.
+Created at stays fixed, and moving a bar between groups does not shift its dates.
+
+When grouped by Status, Priority, Assignee, or Project, drag a task's list item or
+bar into another visible group to change that property. Projects support Status,
+Priority, and Assignee moves. Move at least 10px to start a drag; ordinary clicks
+still open items. The drag overlay snapshots the visible item or bar; the original
+placement dims, and a dashed ghost reserves the destination's sorted row. Drag
+sources stay mounted during virtual scrolling and immutable row updates.
+If the item already belongs to the destination assignee group, its existing row
+becomes the ghost instead of creating a duplicate. Drop on a group's header
+(including collapsed groups) or its rows. The active sort determines the resulting order; same-group reordering is
+not supported. Assignee moves replace only the source assignee and preserve other
+assignments. Unassigned accepts only a sole-assignee item; mixed-assignee drops
+are rejected so they cannot clear other assignments. Creation-date grouping
+and ungrouped views do not accept group moves. Membership and destination checks
+run again on release. Escape cancels, failed saves show an error, and neither
+Created at nor Due date changes during a group move. Active filters still apply.
+Task group moves follow the task list's editing policy: no task or destination
+permission prefetch is required before attempting a save. The backend authorizes
+property writes; rejected saves roll back, show an error, and release the task lock.
+Project Gantt also shows empty Status/Priority destinations from property options,
+Unassigned when allowed, and assignees already seen in the current collection
+scope. An emptied assignee group remains available for another drop. The ordinary
+project list still shows only its loaded groups.
+
+Drag horizontally across empty calendar space to open the task composer with
+Due date prefilled and visible. Past dates and permission-disabled creation remain
+unavailable, without a diagonal-line pattern.
+This works with no loaded rows too. Release opens the composer rather than
+immediately creating a task; Escape cancels the selection.
+In a project's Tasks section, creation preserves that project and its edit gate.
+The Projects collection offers the same interaction with the project composer.
+There is no Start date property, so the selection sets only Due date; Created at
+remains automatic. New selections begin today or later, so creation never produces
+an end before Created at. Existing overdue items remain unchanged.
+
+The timeline reuses the list's filtered, sorted, grouped rows and collapsed
+state. Sidebar items fill the list's inset width and share vertical scrolling with
+bars. Compact group headers show the grouping's icon and span both the list and
+calendar; they remain visible when the list is collapsed.
+Pagination remains available in the item list and as a quiet, labeled action at
+the visible calendar's left edge outside the open list, even after horizontal
+panning. Group pagination stays after its group; the global continuation appears
+once after the loaded rows. Loading shows a spinner and disables both actions;
+pagination and group headers do not start range creation.
+The chart contains loaded results, not an implied complete schedule. Selecting
+Gantt persists in `tasks.layout` or `projectTasks.layout`, just like List and Board.
+
## Board layout
Open the icon-only **Task layout** dropdown in the toolbar and choose **Board**
@@ -146,15 +289,15 @@ An icon-only status pill appears before the task title, and an icon-only assigne
pill appears to its right in every grouping. The lower row omits status, assignee,
and the grouping property. The remaining properties use standard pill controls
and icons. Priority uses a compact icon-only pill; due date and project appear
-when set. Read-only tasks keep passive property pills.
+when set. Metadata properties stay read-only, and pending writes disable editing.
A task assigned to multiple people appears in each person's column. Moving it
from Alice to Bob replaces Alice while keeping the other assignees. Moving to
**Unassigned** clears all assignees. Project moves change the task's Project
property (an initiative), never its legacy folder.
-Only editable tasks can move. Access checks and property definitions can keep
-moves unavailable while loading. A destination project also requires edit
-access. A pending move disables further moves of the same task in every column;
+Task moves and property pills follow the list's editing policy without permission
+prefetches. Property definitions and valid destinations must still be available.
+A pending move disables further moves of the same task in every column;
failed writes use the shared property mutation's rollback and show an error.
A valid destination highlights and shows the sort overlay only while dragging
inside that column, not in gaps or outside the board. Drops move the card
@@ -400,6 +543,16 @@ end loads more projects; `Load more projects` also continues the list.
Keyboard movement changes focus; Enter opens the focused project and
Shift-selection opens it in a new split. Folders remain separate in Files.
+On desktop, **Project layout** offers **List** and **Gantt**. Gantt shows one
+bar per visible project from Created at to Due date, using the same search,
+filters, sort, grouping, and pagination as the project list. Click a project
+label or bar to open its overview. Right-click either for its project list menu.
+The same timeline settings and read-only dates apply as in task Gantt.
+**Load more projects** continues the chart.
+The selection persists in `projects.layout` and restores with the navigation
+entry. Projects without a due date have explicitly open-ended bars. Mobile
+continues to render the project list.
+
Right-click a project row for its context menu; the row takes focus, as in
Tasks. Every project offers `Open in new split` (disabled when no split fits),
`Copy Link` (the Overview link), `Copy ID`, and `Share`, which opens the same