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 kanban board view (#7716)

dev-rb486f63753250
diff --git a/apps/web/src/components/drag-drop/create-distance-pointer-sensor.test.ts b/apps/web/src/components/drag-drop/create-distance-pointer-sensor.test.ts
new file mode 100644
index 0000000000..d26b5fc87e
--- /dev/null
+++ b/apps/web/src/components/drag-drop/create-distance-pointer-sensor.test.ts
@@ -0,0 +1,209 @@
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createDistancePointerSensor } from './create-distance-pointer-sensor';
+
+const mock = vi.hoisted(() => {
+ let activator: ((event: MouseEvent, id: string | number) => void) | undefined;
+ let sensorId: string | null = null;
+ let draggable: object | null = null;
+ const actions = {
+ addSensor: vi.fn(
+ (sensor: { activators: { mousedown: typeof activator } }) => {
+ activator = sensor.activators.mousedown;
+ }
+ ),
+ removeSensor: vi.fn(),
+ sensorStart: vi.fn((id: string) => {
+ sensorId = id;
+ }),
+ sensorMove: vi.fn(),
+ sensorEnd: vi.fn(() => {
+ sensorId = null;
+ }),
+ dragStart: vi.fn(() => {
+ draggable = {};
+ }),
+ dragEnd: vi.fn(() => {
+ draggable = null;
+ }),
+ };
+ return {
+ actions,
+ state: {
+ active: {
+ get sensorId() {
+ return sensorId;
+ },
+ get sensor() {
+ return sensorId ? {} : null;
+ },
+ get draggable() {
+ return draggable;
+ },
+ },
+ },
+ press: (event: MouseEvent, id: string | number) => activator?.(event, id),
+ reset: () => {
+ activator = undefined;
+ sensorId = null;
+ draggable = null;
+ },
+ };
+});
+vi.mock('@thisbeyond/solid-dnd', () => ({
+ useDragDropContext: () => [mock.state, mock.actions],
+}));
+
+let dispose: (() => void) | undefined;
+const onCancel = vi.fn();
+function setup(distance = 10) {
+ let sensor!: ReturnType<typeof createDistancePointerSensor>;
+ createRoot((cleanup) => {
+ dispose = cleanup;
+ sensor = createDistancePointerSensor(distance, onCancel);
+ });
+ const press = (x = 10, y = 20, button = 0) =>
+ mock.press(
+ new MouseEvent('mousedown', { clientX: x, clientY: y, button }),
+ 'item'
+ );
+ const move = (x: number, y: number) => {
+ const event = new MouseEvent('mousemove', {
+ clientX: x,
+ clientY: y,
+ cancelable: true,
+ });
+ document.dispatchEvent(event);
+ return event;
+ };
+ const up = () => {
+ const event = new MouseEvent('mouseup', { cancelable: true });
+ document.dispatchEvent(event);
+ return event;
+ };
+ return { sensor, press, move, up };
+}
+afterEach(() => {
+ dispose?.();
+ dispose = undefined;
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ mock.reset();
+ for (const action of Object.values(mock.actions)) action.mockClear();
+ onCancel.mockClear();
+});
+
+describe('distance-only mouse sensor', () => {
+ it('ignores other buttons, time, and movement up to the threshold', () => {
+ vi.useFakeTimers();
+ const { press, move, up } = setup();
+ press(10, 20, 2);
+ move(100, 100);
+ expect(mock.actions.dragStart).not.toHaveBeenCalled();
+ press();
+ vi.advanceTimersByTime(5000);
+ move(16, 28);
+ expect(mock.actions.dragStart).not.toHaveBeenCalled();
+ expect(up().defaultPrevented).toBe(false);
+ expect(mock.actions.dragStart).not.toHaveBeenCalled();
+ });
+
+ it('starts beyond the threshold with the press coordinates and clears selection', () => {
+ const selection = vi.spyOn(window, 'getSelection');
+ const removeAllRanges = vi.fn();
+ selection.mockReturnValue({ removeAllRanges } as unknown as Selection);
+ const { press, move, up } = setup();
+ press();
+ expect(move(16, 29).defaultPrevented).toBe(true);
+ expect(mock.actions.sensorStart).toHaveBeenCalledWith(
+ 'distance-pointer-sensor',
+ { x: 10, y: 20 }
+ );
+ expect(mock.actions.dragStart).toHaveBeenCalledWith('item');
+ expect(mock.actions.sensorMove).toHaveBeenCalledWith({ x: 16, y: 29 });
+ document.dispatchEvent(new Event('selectionchange'));
+ expect(removeAllRanges).toHaveBeenCalledTimes(2);
+ expect(up().defaultPrevented).toBe(true);
+ expect(mock.actions.dragEnd).toHaveBeenCalledTimes(1);
+ expect(mock.actions.sensorEnd).toHaveBeenCalledTimes(1);
+ document.dispatchEvent(new Event('selectionchange'));
+ expect(removeAllRanges).toHaveBeenCalledTimes(2);
+ });
+
+ it('cancels a pending press and does not activate on later movement', () => {
+ const { sensor, press, move, up } = setup();
+ press();
+ expect(sensor.cancel()).toBe(true);
+ expect(sensor.cancel()).toBe(false);
+ move(100, 100);
+ up();
+ expect(mock.actions.dragStart).not.toHaveBeenCalled();
+ expect(onCancel).not.toHaveBeenCalled();
+ press();
+ move(100, 100);
+ expect(mock.actions.dragStart).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not restart a cancelled drag until mouseup, then permits a new press', () => {
+ const { sensor, press, move, up } = setup();
+ press();
+ move(100, 100);
+ expect(sensor.cancel()).toBe(true);
+ move(120, 120);
+ expect(mock.actions.dragStart).toHaveBeenCalledTimes(1);
+ expect(mock.actions.sensorMove).toHaveBeenCalledTimes(1);
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ expect(mock.actions.dragEnd).toHaveBeenCalledTimes(1);
+ up();
+ expect(mock.actions.sensorEnd).toHaveBeenCalledTimes(1);
+ press();
+ move(100, 100);
+ expect(mock.actions.dragStart).toHaveBeenCalledTimes(2);
+ });
+
+ it('releases the sensor on blur and cancels active work on cleanup', () => {
+ const { sensor, press, move } = setup();
+ press();
+ move(100, 100);
+ expect(sensor.cancel(true)).toBe(true);
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ expect(mock.actions.sensorEnd).toHaveBeenCalledTimes(1);
+ press();
+ move(100, 100);
+ dispose?.();
+ dispose = undefined;
+ expect(onCancel).toHaveBeenCalledTimes(2);
+ expect(mock.actions.removeSensor).toHaveBeenCalledWith(
+ 'distance-pointer-sensor'
+ );
+ document.dispatchEvent(new MouseEvent('mouseup'));
+ expect(mock.actions.sensorEnd).toHaveBeenCalledTimes(2);
+ });
+
+ it('releases a pending press on blur and cleans its listeners on disposal', () => {
+ const { sensor, press, move } = setup();
+ press();
+ expect(sensor.cancel(true)).toBe(true);
+ move(100, 100);
+ expect(mock.actions.dragStart).not.toHaveBeenCalled();
+ press();
+ dispose?.();
+ dispose = undefined;
+ move(100, 100);
+ expect(mock.actions.dragStart).not.toHaveBeenCalled();
+ expect(onCancel).not.toHaveBeenCalled();
+ expect(mock.actions.removeSensor).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not cancel twice when disposal follows Escape', () => {
+ const { sensor, press, move } = setup();
+ press();
+ move(100, 100);
+ sensor.cancel();
+ dispose?.();
+ dispose = undefined;
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ expect(mock.actions.dragEnd).toHaveBeenCalledTimes(1);
+ expect(mock.actions.sensorEnd).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/web/src/components/drag-drop/create-distance-pointer-sensor.ts b/apps/web/src/components/drag-drop/create-distance-pointer-sensor.ts
new file mode 100644
index 0000000000..d76a0323c0
--- /dev/null
+++ b/apps/web/src/components/drag-drop/create-distance-pointer-sensor.ts
@@ -0,0 +1,94 @@
+import { useDragDropContext } from '@thisbeyond/solid-dnd';
+import { onCleanup, onMount } from 'solid-js';
+
+/** The stock pointer sensor activates after 250ms or 10px. This one has no timer. */
+export function createDistancePointerSensor(
+ distance: number,
+ onCancel: () => void
+) {
+ const context = useDragDropContext();
+ if (!context)
+ throw new Error('Distance pointer sensor requires DragDropProvider');
+ const [state, actions] = context;
+ const id = 'distance-pointer-sensor';
+ let pendingId: string | number | undefined;
+ let origin = { x: 0, y: 0 };
+ let cancelled = false;
+ let attached = false;
+ const isActive = () => state.active.sensorId === id;
+ const clearSelection = () => window.getSelection()?.removeAllRanges();
+
+ const detach = () => {
+ document.removeEventListener('mousemove', move);
+ document.removeEventListener('mouseup', up);
+ document.removeEventListener('selectionchange', clearSelection);
+ attached = false;
+ pendingId = undefined;
+ cancelled = false;
+ };
+ const attach = (event: MouseEvent, draggableId: string | number) => {
+ if (event.button !== 0 || attached) return;
+ origin = { x: event.clientX, y: event.clientY };
+ pendingId = draggableId;
+ attached = true;
+ document.addEventListener('mousemove', move);
+ document.addEventListener('mouseup', up);
+ };
+ const move = (event: MouseEvent) => {
+ if (cancelled) return;
+ const coordinates = { x: event.clientX, y: event.clientY };
+ if (!state.active.sensor && pendingId !== undefined) {
+ if (
+ Math.hypot(coordinates.x - origin.x, coordinates.y - origin.y) >
+ distance
+ ) {
+ actions.sensorStart(id, origin);
+ actions.dragStart(pendingId);
+ clearSelection();
+ document.addEventListener('selectionchange', clearSelection);
+ }
+ } else if (state.active.sensor && !isActive()) {
+ detach();
+ return;
+ }
+ if (isActive()) {
+ event.preventDefault();
+ actions.sensorMove(coordinates);
+ }
+ };
+ const up = (event: MouseEvent) => {
+ const active = isActive();
+ detach();
+ if (active) {
+ event.preventDefault();
+ if (state.active.draggable) actions.dragEnd();
+ actions.sensorEnd();
+ }
+ };
+ /** Escape keeps the active sensor claimed until mouseup. Blur releases it immediately. */
+ const cancel = (release = false) => {
+ if (!attached) return false;
+ const active = isActive();
+ if (active) {
+ const firstCancellation = !cancelled;
+ cancelled = true;
+ if (firstCancellation && state.active.draggable) {
+ onCancel();
+ actions.dragEnd();
+ }
+ if (release) {
+ detach();
+ actions.sensorEnd();
+ }
+ } else {
+ detach();
+ }
+ return true;
+ };
+ onMount(() => actions.addSensor({ id, activators: { mousedown: attach } }));
+ onCleanup(() => {
+ cancel(true);
+ actions.removeSensor(id);
+ });
+ return { cancel };
+}
diff --git a/apps/web/src/components/drag-drop/create-drag-auto-scroll.test.ts b/apps/web/src/components/drag-drop/create-drag-auto-scroll.test.ts
index ad97ded8fd..16445f04e3 100644
--- a/apps/web/src/components/drag-drop/create-drag-auto-scroll.test.ts
+++ b/apps/web/src/components/drag-drop/create-drag-auto-scroll.test.ts
@@ -35,7 +35,10 @@ afterEach(() => {
drag.detectCollisions.mockClear();
});
-function setup(axis: 'x' | 'both' = 'x') {
+function setup(
+ axis: 'x' | 'both' = 'x',
+ nestedScroll?: { viewportSelector: string; horizontalOutside: boolean }
+) {
const frames = new Map<number, FrameRequestCallback>();
let sequence = 0;
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
@@ -58,7 +61,7 @@ function setup(axis: 'x' | 'both' = 'x') {
drag.pointer = { x: 390, y: 200 };
createRoot((cleanup) => {
dispose = cleanup;
- createDragAutoScroll({ getViewport: () => viewport, axis });
+ createDragAutoScroll({ getViewport: () => viewport, axis, nestedScroll });
});
const frame = (time: number) => {
const pending = [...frames.values()];
@@ -120,3 +123,110 @@ describe('drag auto-scroll', () => {
expect(frames.size).toBe(0);
});
});
+
+function addLane(viewport: HTMLElement, left: number) {
+ const lane = document.createElement('div');
+ lane.dataset.taskBoardScroll = String(left);
+ viewport.append(lane);
+ vi.spyOn(lane, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(left, 140, 180, 300)
+ );
+ Object.defineProperties(lane, {
+ scrollHeight: { value: 1000 },
+ clientHeight: { value: 300 },
+ });
+ return lane;
+}
+
+const nestedScroll = {
+ viewportSelector: '[data-task-board-scroll]',
+ horizontalOutside: true,
+};
+
+describe('nested drag auto-scroll', () => {
+ it('scrolls only the lane under the pointer, clips to the board, and switches lanes', () => {
+ const { viewport, setActive, frame } = setup('x', nestedScroll);
+ const first = addLane(viewport, 0);
+ const second = addLane(viewport, 200);
+ drag.pointer = { x: 90, y: 430 };
+ setActive(true);
+ frame(0);
+ frame(16);
+ expect(first.scrollTop).toBeGreaterThan(0);
+ expect(second.scrollTop).toBe(0);
+ expect(viewport.scrollTop).toBe(0);
+ const offset = first.scrollTop;
+ drag.pointer = { x: 290, y: 430 };
+ frame(32);
+ expect(first.scrollTop).toBe(offset);
+ expect(second.scrollTop).toBeGreaterThan(0);
+ drag.pointer = { x: 290, y: 490 };
+ frame(48);
+ expect(second.scrollTop).toBeGreaterThan(0);
+ const clipped = second.scrollTop;
+ drag.pointer = { x: 290, y: 120 };
+ frame(64);
+ expect(second.scrollTop).toBe(clipped);
+ expect(drag.detectCollisions).toHaveBeenCalledTimes(2);
+ });
+
+ it('ignores nested options without a marked lane', () => {
+ const { viewport, setActive, frame } = setup('both', nestedScroll);
+ drag.pointer = { x: 410, y: 490 };
+ setActive(true);
+ frame(0);
+ frame(16);
+ expect(viewport.scrollLeft).toBe(0);
+ expect(viewport.scrollTop).toBe(0);
+ expect(drag.detectCollisions).not.toHaveBeenCalled();
+ });
+
+ it('clips lane edges to the visible board and stops after unmount', () => {
+ const { viewport, setActive, frame, frames } = setup('both', nestedScroll);
+ const lane = addLane(viewport, 200);
+ vi.spyOn(lane, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(200, 140, 180, 600)
+ );
+ drag.pointer = { x: 290, y: 490 };
+ setActive(true);
+ frame(0);
+ frame(16);
+ expect(lane.scrollTop).toBeGreaterThan(0);
+ expect(viewport.scrollTop).toBe(0);
+ const first = lane.scrollTop;
+ drag.pointer = { x: 290, y: 530 };
+ frame(32);
+ expect(lane.scrollTop).toBe(first);
+ lane.scrollTop = 699;
+ drag.pointer = { x: 290, y: 499 };
+ frame(48);
+ expect(lane.scrollTop).toBe(700);
+ dispose?.();
+ dispose = undefined;
+ expect(frames.size).toBe(0);
+ frame(64);
+ expect(lane.scrollTop).toBe(700);
+ });
+
+ it('scrolls horizontally past the viewport and screen, clamps velocity, and stops on drag end', () => {
+ const { viewport, setActive, frame, frames } = setup('x', nestedScroll);
+ addLane(viewport, 200);
+ drag.pointer = { x: 1000, y: -40 };
+ setActive(true);
+ frame(0);
+ frame(16);
+ expect(viewport.scrollLeft).toBeCloseTo(11.2);
+ expect(viewport.scrollTop).toBe(0);
+ drag.pointer = { x: -100, y: 900 };
+ frame(32);
+ expect(viewport.scrollLeft).toBe(0);
+ viewport.scrollLeft = 599;
+ drag.pointer = { x: 1000, y: 900 };
+ frame(48);
+ expect(viewport.scrollLeft).toBe(600);
+ setActive(false);
+ expect(frames.size).toBe(0);
+ frame(64);
+ expect(viewport.scrollLeft).toBe(600);
+ });
+});
diff --git a/apps/web/src/components/drag-drop/create-drag-auto-scroll.ts b/apps/web/src/components/drag-drop/create-drag-auto-scroll.ts
index 2ead7aab55..6458f1e238 100644
--- a/apps/web/src/components/drag-drop/create-drag-auto-scroll.ts
+++ b/apps/web/src/components/drag-drop/create-drag-auto-scroll.ts
@@ -1,10 +1,117 @@
import { useDragDropContext } from '@thisbeyond/solid-dnd';
import { createEffect, on, onCleanup } from 'solid-js';
+type NestedScroll = {
+ viewportSelector: string;
+ horizontalOutside: boolean;
+};
+
+type Point = { x: number; y: number };
+type Edges = { left: number; right: number; top: number; bottom: number };
+
+function edgeVelocity(position: number, start: number, end: number) {
+ const edge = Math.min(48, (end - start) / 4);
+ if (edge <= 0) return 0;
+ if (position < start + edge)
+ return Math.max(-1, -(1 - (position - start) / edge));
+ if (position > end - edge) return Math.min(1, 1 - (end - position) / edge);
+ return 0;
+}
+
+function scrollLane(
+ viewport: HTMLElement,
+ selector: string,
+ pointer: Point,
+ edges: Edges,
+ elapsed: number
+) {
+ for (const lane of viewport.querySelectorAll<HTMLElement>(selector)) {
+ const rect = lane.getBoundingClientRect();
+ const left = Math.max(rect.left, edges.left);
+ const right = Math.min(rect.right, edges.right);
+ const top = Math.max(rect.top, edges.top);
+ const bottom = Math.min(rect.bottom, edges.bottom);
+ if (
+ pointer.x < left ||
+ pointer.x > right ||
+ pointer.y < top ||
+ pointer.y > bottom
+ )
+ continue;
+ const previous = lane.scrollTop;
+ lane.scrollTop = Math.max(
+ 0,
+ Math.min(
+ lane.scrollHeight - lane.clientHeight,
+ previous + edgeVelocity(pointer.y, top, bottom) * elapsed * 0.7
+ )
+ );
+ return lane.scrollTop !== previous;
+ }
+ return false;
+}
+
+function scrollDragFrame(
+ viewport: HTMLElement,
+ pointer: Point,
+ elapsed: number,
+ options: { axis: 'x' | 'both'; nestedScroll?: NestedScroll }
+) {
+ const bounds = viewport.getBoundingClientRect();
+ const edges = {
+ left: Math.max(bounds.left, 0),
+ right: Math.min(bounds.right, window.innerWidth),
+ top: Math.max(bounds.top, 0),
+ bottom: Math.min(bounds.bottom, window.innerHeight),
+ };
+ const inside =
+ pointer.x >= edges.left &&
+ pointer.x <= edges.right &&
+ pointer.y >= edges.top &&
+ pointer.y <= edges.bottom;
+ // The marker opts a board into nested scrolling without changing other surfaces.
+ const nested =
+ options.nestedScroll &&
+ viewport.querySelector(options.nestedScroll.viewportSelector)
+ ? options.nestedScroll
+ : undefined;
+ const beforeX = viewport.scrollLeft;
+ if (inside || nested?.horizontalOutside) {
+ viewport.scrollLeft = Math.max(
+ 0,
+ Math.min(
+ viewport.scrollWidth - viewport.clientWidth,
+ beforeX +
+ edgeVelocity(pointer.x, edges.left, edges.right) * elapsed * 0.7
+ )
+ );
+ }
+ let scrolled = viewport.scrollLeft !== beforeX;
+ if (inside && options.axis === 'both' && !nested) {
+ const beforeY = viewport.scrollTop;
+ viewport.scrollTop = Math.max(
+ 0,
+ Math.min(
+ viewport.scrollHeight - viewport.clientHeight,
+ beforeY +
+ edgeVelocity(pointer.y, edges.top, edges.bottom) * elapsed * 0.7
+ )
+ );
+ scrolled ||= viewport.scrollTop !== beforeY;
+ }
+ if (nested) {
+ scrolled =
+ scrollLane(viewport, nested.viewportSelector, pointer, edges, elapsed) ||
+ scrolled;
+ }
+ return scrolled;
+}
+
/** Scroll the active solid-dnd surface while the pointer rests near its edge. */
export function createDragAutoScroll(options: {
getViewport: () => HTMLElement | undefined;
axis: 'x' | 'both';
+ nestedScroll?: NestedScroll;
}) {
const context = useDragDropContext();
if (!context) throw new Error('Drag auto-scroll requires DragDropProvider');
@@ -22,53 +129,8 @@ export function createDragAutoScroll(options: {
const viewport = options.getViewport();
const pointer = state.active.sensor?.coordinates.current;
if (viewport && pointer) {
- const bounds = viewport.getBoundingClientRect();
- const left = Math.max(bounds.left, 0);
- const right = Math.min(bounds.right, window.innerWidth);
- const top = Math.max(bounds.top, 0);
- const bottom = Math.min(bounds.bottom, window.innerHeight);
- if (
- pointer.x >= left &&
- pointer.x <= right &&
- pointer.y >= top &&
- pointer.y <= bottom
- ) {
- const velocity = (
- position: number,
- start: number,
- end: number
- ) => {
- const edge = Math.min(48, (end - start) / 4);
- if (edge <= 0) return 0;
- if (position < start + edge)
- return -(1 - (position - start) / edge);
- if (position > end - edge) return 1 - (end - position) / edge;
- return 0;
- };
- const beforeX = viewport.scrollLeft;
- const beforeY = viewport.scrollTop;
- viewport.scrollLeft = Math.max(
- 0,
- Math.min(
- viewport.scrollWidth - viewport.clientWidth,
- beforeX + velocity(pointer.x, left, right) * elapsed * 0.7
- )
- );
- if (options.axis === 'both') {
- viewport.scrollTop = Math.max(
- 0,
- Math.min(
- viewport.scrollHeight - viewport.clientHeight,
- beforeY + velocity(pointer.y, top, bottom) * elapsed * 0.7
- )
- );
- }
- if (
- viewport.scrollLeft !== beforeX ||
- viewport.scrollTop !== beforeY
- )
- actions.detectCollisions();
- }
+ if (scrollDragFrame(viewport, pointer, elapsed, options))
+ actions.detectCollisions();
}
frame = requestAnimationFrame(tick);
};
diff --git a/apps/web/src/components/drag-drop/drag-session-sensors.tsx b/apps/web/src/components/drag-drop/drag-session-sensors.tsx
index 5c5c23961b..f2d3a2599f 100644
--- a/apps/web/src/components/drag-drop/drag-session-sensors.tsx
+++ b/apps/web/src/components/drag-drop/drag-session-sensors.tsx
@@ -1,5 +1,6 @@
import { DragDropSensors, useDragDropContext } from '@thisbeyond/solid-dnd';
import { onCleanup } from 'solid-js';
+import { createDistancePointerSensor } from './create-distance-pointer-sensor';
import { createDragAutoScroll } from './create-drag-auto-scroll';
/**
@@ -10,27 +11,54 @@ import { createDragAutoScroll } from './create-drag-auto-scroll';
export function DragSessionSensors(props: {
getViewport: () => HTMLElement | undefined;
axis: 'x' | 'both';
+ nestedScroll?: { viewportSelector: string; horizontalOutside: boolean };
+ /** Use a distance-only mouse sensor instead of the default 250ms-or-10px sensor. */
+ activationDistance?: number;
onCancel: () => void;
}) {
const context = useDragDropContext();
if (!context) throw new Error('DragSessionSensors requires DragDropProvider');
const [state, actions] = context;
- createDragAutoScroll({ getViewport: props.getViewport, axis: props.axis });
+ const distanceSensor =
+ props.activationDistance === undefined
+ ? undefined
+ : createDistancePointerSensor(props.activationDistance, props.onCancel);
+ createDragAutoScroll({
+ getViewport: props.getViewport,
+ axis: props.axis,
+ nestedScroll: props.nestedScroll,
+ });
const cancelDrag = () => {
+ if (distanceSensor?.cancel(true)) return;
if (!state.active.draggable) return;
props.onCancel();
// Keep the sensor until mouseup so its next mousemove cannot restart a drag.
actions.dragEnd();
};
const cancelOnEscape = (event: KeyboardEvent) => {
- if (event.key !== 'Escape' || !state.active.draggable) return;
+ if (event.key !== 'Escape') return;
+ if (distanceSensor) {
+ if (!distanceSensor.cancel()) return;
+ } else if (state.active.draggable) {
+ cancelDrag();
+ } else return;
event.preventDefault();
event.stopPropagation();
- cancelDrag();
};
const updateDrop = (event: Event) => {
- if (event.target === props.getViewport() && state.active.draggable)
+ if (!state.active.draggable) return;
+
+ const viewport = props.getViewport();
+ if (event.target === viewport) {
actions.detectCollisions();
+ return;
+ }
+
+ if (!props.nestedScroll || !(event.target instanceof Element)) return;
+ if (!viewport?.contains(event.target)) return;
+ if (!event.target.matches(props.nestedScroll.viewportSelector)) return;
+
+ actions.detectCollisions();
};
document.addEventListener('keydown', cancelOnEscape, true);
document.addEventListener('scroll', updateDrop, true);
@@ -40,5 +68,5 @@ export function DragSessionSensors(props: {
document.removeEventListener('scroll', updateDrop, true);
window.removeEventListener('blur', cancelDrag);
});
- return <DragDropSensors />;
+ return distanceSensor ? null : <DragDropSensors />;
}
diff --git a/apps/web/src/components/kanban/kanban-animation-merge.test.ts b/apps/web/src/components/kanban/kanban-animation-merge.test.ts
new file mode 100644
index 0000000000..2b1c829d79
--- /dev/null
+++ b/apps/web/src/components/kanban/kanban-animation-merge.test.ts
@@ -0,0 +1,155 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import {
+ createKanbanAnimation,
+ type KanbanAnimationItem,
+} from './kanban-animation';
+
+let cancel: (() => void) | undefined;
+const originalAnimate = Object.getOwnPropertyDescriptor(
+ HTMLElement.prototype,
+ 'animate'
+);
+
+afterEach(() => {
+ cancel?.();
+ document.body.replaceChildren();
+
+ if (originalAnimate) {
+ Object.defineProperty(HTMLElement.prototype, 'animate', originalAnimate);
+ } else {
+ delete (HTMLElement.prototype as Partial<HTMLElement>).animate;
+ }
+
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+function fixture() {
+ vi.useFakeTimers();
+ vi.stubGlobal('matchMedia', () => ({ matches: false }));
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
+ window.setTimeout(() => callback(0), 16)
+ );
+ vi.stubGlobal('cancelAnimationFrame', (id: number) =>
+ window.clearTimeout(id)
+ );
+
+ const animate = vi.fn(() => ({
+ cancel: vi.fn(),
+ finished: new Promise(() => {}),
+ }));
+ Object.defineProperty(HTMLElement.prototype, 'animate', {
+ configurable: true,
+ value: animate,
+ });
+ const viewport = document.createElement('div');
+ viewport.getBoundingClientRect = () => new DOMRect(0, 0, 900, 600);
+ document.body.append(viewport);
+ let items: KanbanAnimationItem[] = [];
+
+ function placement(key: string, x: number, parentKey?: string) {
+ const layout = document.createElement('div');
+ const element = document.createElement('article');
+ element.textContent = key;
+ let top = 0;
+ let offset = 0;
+ layout.getBoundingClientRect = () => new DOMRect(x, top, 100, 80);
+ element.getBoundingClientRect = () => new DOMRect(x, top + offset, 100, 80);
+ layout.append(element);
+ viewport.append(layout);
+ const item = { key, identity: 'task', parentKey, element, layout };
+ items.push(item);
+
+ return {
+ ...item,
+ move(nextTop: number, animationOffset = 0) {
+ top = nextTop;
+ offset = animationOffset;
+ layout.style.transform = `translateY(${top}px)`;
+ },
+ remove() {
+ items = items.filter((entry) => entry !== item);
+ layout.remove();
+ },
+ };
+ }
+
+ const motion = createKanbanAnimation({
+ viewport: () => viewport,
+ items: () => items,
+ });
+ cancel = motion.cancel;
+ return { motion, animate, placement };
+}
+
+async function frame() {
+ await Promise.resolve();
+ vi.advanceTimersByTime(16);
+}
+
+it('animates a removed assignee placement into an existing destination placement', async () => {
+ const board = fixture();
+ const alice = board.placement('alice:task', 0, 'alice');
+ const bob = board.placement('bob:task', 300, 'bob');
+ const carol = board.placement('carol:task', 600, 'carol');
+ const finish = board.motion.begin('task', 'bob', {
+ key: alice.key,
+ element: alice.element,
+ rect: new DOMRect(280, 50, 100, 80),
+ parentKey: 'alice',
+ });
+ alice.remove();
+ await frame();
+
+ const ghost = document.body.querySelector<HTMLElement>(
+ '[aria-hidden="true"]'
+ );
+ expect(ghost).not.toBeNull();
+ expect(ghost?.textContent).toBe('alice:task');
+ expect(ghost?.inert).toBe(true);
+ expect(ghost?.style.left).toBe('280px');
+ expect(ghost?.style.top).toBe('50px');
+ expect(board.animate.mock.contexts).toContain(bob.element);
+ expect(board.animate.mock.contexts).not.toContain(carol.element);
+ finish();
+});
+
+it('retargets from the old visual position, not the already updated layout', async () => {
+ const board = fixture();
+ const card = board.placement('alice:task', 0);
+ board.motion.begin('task');
+ card.move(120);
+ await frame();
+
+ // The old animation is halfway from 0 to 120 when layout changes to 240.
+ // The DOM now reports 240 - 60, but the user last saw 120 - 60 = 60.
+ card.move(240, -60);
+ await frame();
+
+ expect(board.animate).toHaveBeenLastCalledWith(
+ [{ transform: 'translate(0px, -180px)' }, { transform: 'translate(0, 0)' }],
+ expect.anything()
+ );
+});
+
+it('does not animate a child twice when its parent FLIP is interrupted', async () => {
+ const board = fixture();
+ const column = board.placement('lane', 0);
+ const card = board.placement('lane:task', 0, 'lane');
+ board.motion.begin('task');
+ column.move(120);
+ card.move(120);
+ await frame();
+ expect(board.animate).toHaveBeenCalledTimes(1);
+
+ column.move(240, -60);
+ card.move(240);
+ // Even an unanimated child wrapper inherits its parent's running transform.
+ card.layout.getBoundingClientRect = () => new DOMRect(0, 180, 100, 80);
+ card.element.getBoundingClientRect = card.layout.getBoundingClientRect;
+ await frame();
+
+ expect(board.animate).toHaveBeenCalledTimes(2);
+ expect(board.animate.mock.contexts).toEqual([column.element, column.element]);
+});
diff --git a/apps/web/src/components/kanban/kanban-animation.test.ts b/apps/web/src/components/kanban/kanban-animation.test.ts
new file mode 100644
index 0000000000..13612a4102
--- /dev/null
+++ b/apps/web/src/components/kanban/kanban-animation.test.ts
@@ -0,0 +1,572 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ createKanbanAnimation,
+ type KanbanAnimationItem,
+} from './kanban-animation';
+
+const cleanups: (() => void)[] = [];
+let animate: ReturnType<typeof vi.fn>;
+let cancellations: ReturnType<typeof vi.fn>[];
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ cancellations = [];
+ animate = vi.fn(() => {
+ const cancel = vi.fn();
+ cancellations.push(cancel);
+ return { cancel, finished: new Promise(() => {}) };
+ });
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
+ window.setTimeout(() => callback(0), 16)
+ );
+ vi.stubGlobal('cancelAnimationFrame', (id: number) =>
+ window.clearTimeout(id)
+ );
+ vi.stubGlobal('matchMedia', () => ({ matches: false }));
+ Object.defineProperty(HTMLElement.prototype, 'animate', {
+ configurable: true,
+ value: animate,
+ });
+});
+
+afterEach(() => {
+ for (const cleanup of cleanups.splice(0)) {
+ cleanup();
+ }
+
+ document.body.replaceChildren();
+ delete (HTMLElement.prototype as Partial<HTMLElement>).animate;
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+function fixture() {
+ const viewport = document.createElement('div');
+ viewport.getBoundingClientRect = () => new DOMRect(0, 0, 800, 600);
+ document.body.append(viewport);
+ let items: KanbanAnimationItem[] = [];
+ const motion = createKanbanAnimation({
+ viewport: () => viewport,
+ items: () => items,
+ });
+ cleanups.push(motion.cancel);
+
+ function item(
+ key: string,
+ x: number,
+ y: number,
+ identity?: string,
+ parentKey?: string,
+ placeholder = false
+ ) {
+ const layout = document.createElement('div');
+ const element = document.createElement('article');
+ layout.append(element);
+ viewport.append(layout);
+ let rect = new DOMRect(x, y, 100, 80);
+ layout.getBoundingClientRect = () => rect;
+ const entry = { key, identity, parentKey, placeholder, element, layout };
+ items = [...items, entry];
+
+ return {
+ ...entry,
+ move(left: number, top: number) {
+ rect = new DOMRect(left, top, 100, 80);
+ layout.style.transform = `translate(${left}px, ${top}px)`;
+ },
+ remove() {
+ items = items.filter((item) => item !== entry);
+ layout.remove();
+ },
+ };
+ }
+
+ return { viewport, motion, item };
+}
+
+async function frame() {
+ await Promise.resolve();
+ vi.advanceTimersByTime(16);
+}
+
+describe('Kanban layout animation', () => {
+ it('animates inner cards without touching virtualizer transforms', async () => {
+ const board = fixture();
+ const card = board.item('a:task', 0, 0, 'task');
+ const finish = board.motion.begin('task');
+ card.move(0, 120);
+ await frame();
+
+ expect(animate).toHaveBeenCalledWith(
+ [
+ { transform: 'translate(0px, -120px)' },
+ { transform: 'translate(0, 0)' },
+ ],
+ expect.objectContaining({ duration: 200 })
+ );
+ expect(animate.mock.contexts[0]).toBe(card.element);
+ expect(card.layout.style.transform).toBe('translate(0px, 120px)');
+ finish();
+ });
+
+ it('does not animate ordinary virtualization or scrolling', async () => {
+ const board = fixture();
+ const card = board.item('a:task', 0, 0, 'task');
+ card.move(0, 120);
+ await frame();
+ expect(animate).not.toHaveBeenCalled();
+
+ board.motion.begin('task');
+ card.move(0, 240);
+ board.viewport.dispatchEvent(new Event('scroll'));
+ await frame();
+ expect(animate).not.toHaveBeenCalled();
+ });
+
+ it('animates remounted cross-column cards with inert visual copies', async () => {
+ const board = fixture();
+ const source = board.item('a:task', 0, 0, 'task');
+ source.element.id = 'original';
+ board.motion.begin('task');
+ source.remove();
+ board.item('b:task', 300, 100, 'task');
+ await frame();
+
+ const ghost = document.body.querySelector<HTMLElement>(
+ '[aria-hidden="true"]'
+ );
+ expect(ghost?.inert).toBe(true);
+ expect(ghost?.id).toBe('');
+ expect(ghost?.style.pointerEvents).toBe('none');
+ expect(animate).toHaveBeenCalledTimes(2);
+ board.motion.cancel();
+ expect(ghost?.isConnected).toBe(false);
+ });
+
+ it('settles one opaque card from the released preview instead of its original lane', async () => {
+ const board = fixture();
+ const source = board.item('a:task', 0, 0, 'task', 'a');
+ const preview = document.createElement('article');
+ preview.textContent = 'Released card';
+ board.motion.begin('task', 'b', {
+ key: source.key,
+ element: preview,
+ rect: new DOMRect(280, 180, 100, 80),
+ parentKey: 'a',
+ });
+ source.remove();
+ const destination = board.item('b:task', 300, 100, 'task', 'b');
+ await frame();
+
+ const ghost = document.body.querySelector<HTMLElement>(
+ '[aria-hidden="true"]'
+ );
+ expect(ghost?.textContent).toBe('Released card');
+ expect(ghost?.style.left).toBe('280px');
+ expect(ghost?.style.top).toBe('180px');
+ expect(animate).toHaveBeenCalledWith(
+ [
+ { transform: 'translate(0, 0)', opacity: 1 },
+ { transform: 'translate(20px, -80px)', opacity: 1 },
+ ],
+ expect.anything()
+ );
+ expect(animate.mock.contexts.at(-1)).toBe(destination.element);
+ expect(animate.mock.calls.at(-1)?.[0]).toEqual([
+ { opacity: 0 },
+ { opacity: 0 },
+ ]);
+ });
+
+ it('keeps the release preview when edge scrolling unpins the source before the drop callback', async () => {
+ const board = fixture();
+ const source = board.item('a:task', -400, 0, 'task', 'a');
+ board.motion.beginHover();
+ source.remove();
+ board.motion.begin('task', 'b', {
+ key: source.key,
+ element: source.element,
+ rect: new DOMRect(300, 0, 100, 80),
+ parentKey: 'a',
+ });
+ board.item('b:task', 300, 100, 'task', 'b');
+ await frame();
+
+ const ghost = document.body.querySelector<HTMLElement>(
+ '[aria-hidden="true"]'
+ );
+ expect(ghost?.style.left).toBe('300px');
+ expect(animate).toHaveBeenCalledWith(
+ [
+ { transform: 'translate(0, 0)', opacity: 1 },
+ { transform: 'translate(0px, 100px)', opacity: 1 },
+ ],
+ expect.anything()
+ );
+ });
+
+ it('retargets an in-flight card when its sorted destination moves without flashing a second copy', async () => {
+ const board = fixture();
+ const source = board.item('a:task', 0, 0, 'task');
+ board.motion.begin('task');
+ source.remove();
+ const destination = board.item('b:task', 300, 100, 'task');
+ await frame();
+
+ const ghost = document.body.querySelector<HTMLElement>(
+ '[aria-hidden="true"]'
+ )!;
+ ghost.getBoundingClientRect = () => new DOMRect(180, 60, 100, 80);
+ destination.move(300, 220);
+ await frame();
+
+ const nextGhost = document.body.querySelector<HTMLElement>(
+ '[aria-hidden="true"]'
+ );
+ expect(ghost.isConnected).toBe(false);
+ expect(nextGhost?.style.left).toBe('180px');
+ expect(nextGhost?.style.top).toBe('60px');
+ expect(animate).toHaveBeenCalledWith(
+ [
+ { transform: 'translate(0, 0)', opacity: 1 },
+ { transform: 'translate(120px, 160px)', opacity: 1 },
+ ],
+ expect.anything()
+ );
+ expect(animate.mock.calls.at(-1)?.[0]).toEqual([
+ { opacity: 0 },
+ { opacity: 0 },
+ ]);
+ });
+
+ it('returns a rejected drop from the release position using an unclipped visual copy', async () => {
+ const board = fixture();
+ const source = board.item('a:task', 0, 0, 'task', 'a');
+ const finish = board.motion.begin('task', 'b', {
+ key: source.key,
+ element: source.element,
+ rect: new DOMRect(300, 100, 100, 80),
+ parentKey: 'a',
+ });
+ finish();
+ await frame();
+
+ expect(animate.mock.contexts[0]?.parentElement).toBe(document.body);
+ expect(animate).toHaveBeenCalledWith(
+ [
+ { transform: 'translate(0, 0)', opacity: 1 },
+ { transform: 'translate(-300px, -100px)', opacity: 1 },
+ ],
+ expect.anything()
+ );
+ expect(animate.mock.contexts.at(-1)).toBe(source.element);
+ });
+
+ it('subtracts parent movement to avoid moving nested cards twice', async () => {
+ const board = fixture();
+ const column = board.item('a', 0, 0);
+ const card = board.item('a:task', 0, 40, 'task', 'a');
+ board.motion.begin('task');
+ column.move(300, 0);
+ card.move(300, 40);
+ await frame();
+ expect(animate).toHaveBeenCalledTimes(1);
+ expect(animate.mock.contexts[0]).toBe(column.element);
+ });
+
+ it('respects reduced motion', async () => {
+ vi.stubGlobal('matchMedia', () => ({ matches: true }));
+ const board = fixture();
+ const card = board.item('a:task', 0, 0, 'task');
+ const finish = board.motion.begin('task');
+ card.move(200, 100);
+ finish();
+ await frame();
+ expect(animate).not.toHaveBeenCalled();
+ });
+
+ it('ignores stale completion after cancellation', async () => {
+ const board = fixture();
+ const card = board.item('a:task', 0, 0, 'task');
+ const finish = board.motion.begin('task');
+ board.motion.cancel();
+ card.move(300, 100);
+ finish();
+ await frame();
+ expect(animate).not.toHaveBeenCalled();
+ });
+
+ it('keeps observing concurrent moves until all finish', async () => {
+ const board = fixture();
+ const card = board.item('a:task', 0, 0, 'task');
+ const first = board.motion.begin('task');
+ const second = board.motion.begin('task');
+ first();
+ await frame();
+ card.move(0, 120);
+ await frame();
+ expect(animate).toHaveBeenCalledTimes(1);
+ second();
+ await frame();
+ card.move(0, 240);
+ await frame();
+ expect(animate).toHaveBeenCalledTimes(1);
+ });
+
+ it('animates rollback to the original placement', async () => {
+ const board = fixture();
+ const source = board.item('a:task', 0, 0, 'task');
+ const finish = board.motion.begin('task');
+ source.remove();
+ const destination = board.item('b:task', 300, 0, 'task');
+ await frame();
+ destination.remove();
+ board.item('a:task', 0, 0, 'task');
+ finish();
+ await frame();
+ expect(animate).toHaveBeenCalledTimes(4);
+ expect(cancellations[0]).toHaveBeenCalled();
+ });
+
+ it('copies only moving cards and preserves other assignee placements', async () => {
+ const board = fixture();
+ const alice = board.item('alice:task', 0, 0, 'task');
+ const carol = board.item('carol:task', 600, 0, 'task');
+ const unrelated = board.item('alice:other', 0, 100, 'other');
+ const clone = vi.spyOn(unrelated.element, 'cloneNode');
+ board.motion.begin('task');
+ alice.remove();
+ board.item('bob:task', 300, 0, 'task');
+ await frame();
+
+ expect(clone).not.toHaveBeenCalled();
+ expect(animate).toHaveBeenCalledTimes(2);
+ expect(animate.mock.contexts).not.toContain(carol.element);
+ clone.mockRestore();
+ });
+
+ it('animates hover placeholder and displaced cards without moving layout wrappers', async () => {
+ const board = fixture();
+ const first = board.item('lane:first', 0, 0);
+ const second = board.item('lane:second', 0, 116);
+ const endHover = board.motion.beginHover();
+ const placeholder = board.item(
+ 'lane:placeholder',
+ 0,
+ 116,
+ undefined,
+ undefined,
+ true
+ );
+ second.move(0, 232);
+ await frame();
+
+ expect(animate.mock.contexts).toContain(second.element);
+ expect(animate.mock.contexts).toContain(placeholder.element);
+ expect(animate.mock.contexts).not.toContain(second.layout);
+ expect(animate.mock.contexts).not.toContain(first.element);
+ endHover();
+ });
+
+ it('retargets a moving hover slot from its current visual position', async () => {
+ const board = fixture();
+ board.motion.beginHover();
+ const slot = board.item(
+ 'lane:placeholder',
+ 0,
+ 116,
+ undefined,
+ undefined,
+ true
+ );
+ await frame();
+
+ // After layout moves to 232, the current local residual is +34.
+ slot.element.getBoundingClientRect = () => new DOMRect(0, 266, 100, 80);
+ slot.move(0, 232);
+ await frame();
+ expect(cancellations[0]).toHaveBeenCalledOnce();
+ expect(animate).toHaveBeenLastCalledWith(
+ [
+ { transform: 'translate(0px, -82px)' },
+ { transform: 'translate(0, 0)' },
+ ],
+ expect.objectContaining({ duration: 200 })
+ );
+ expect(animate.mock.contexts.at(-1)).toBe(slot.element);
+ });
+
+ it('flies hover placeholders across clipped columns and clears invalid flights', async () => {
+ const board = fixture();
+ const source = board.item(
+ 'a:placeholder',
+ 0,
+ 116,
+ undefined,
+ undefined,
+ true
+ );
+ board.motion.beginHover();
+ source.remove();
+ const destination = board.item(
+ 'b:placeholder',
+ 300,
+ 232,
+ undefined,
+ undefined,
+ true
+ );
+ await frame();
+
+ const ghost = document.body.querySelector<HTMLElement>(
+ '[aria-hidden="true"]'
+ );
+ expect(ghost).not.toBeNull();
+ expect(ghost?.inert).toBe(true);
+ expect(ghost?.style.position).toBe('fixed');
+ expect(ghost?.style.pointerEvents).toBe('none');
+ expect(animate.mock.contexts).toContain(ghost);
+ expect(animate).toHaveBeenCalledWith(
+ [
+ { transform: 'translate(0, 0)', opacity: 1 },
+ { transform: 'translate(300px, 116px)', opacity: 0 },
+ ],
+ expect.anything()
+ );
+
+ destination.remove();
+ await frame();
+ expect(ghost?.isConnected).toBe(false);
+ expect(document.body.querySelector('[aria-hidden="true"]')).toBeNull();
+ });
+
+ it('retargets an interrupted placeholder flight from its live ghost rectangle and opacity', async () => {
+ const board = fixture();
+ const source = board.item(
+ 'a:placeholder',
+ 0,
+ 116,
+ undefined,
+ undefined,
+ true
+ );
+ board.motion.beginHover();
+ source.remove();
+ const middle = board.item(
+ 'b:placeholder',
+ 300,
+ 232,
+ undefined,
+ undefined,
+ true
+ );
+ await frame();
+
+ const ghost = document.body.querySelector<HTMLElement>(
+ '[aria-hidden="true"]'
+ )!;
+ ghost.style.opacity = '0.6';
+ ghost.getBoundingClientRect = () => new DOMRect(150, 174, 100, 80);
+ middle.remove();
+ board.item('c:placeholder', 600, 300, undefined, undefined, true);
+ await frame();
+
+ expect(ghost.isConnected).toBe(false);
+ const newGhost = document.body.querySelector<HTMLElement>(
+ '[aria-hidden="true"]'
+ );
+ expect(newGhost).not.toBeNull();
+ expect(newGhost?.style.left).toBe('150px');
+ expect(newGhost?.style.top).toBe('174px');
+ expect(newGhost?.style.opacity).toBe('0.6');
+ expect(animate).toHaveBeenCalledWith(
+ [
+ { transform: 'translate(0, 0)', opacity: 0.6 },
+ { transform: 'translate(450px, 126px)', opacity: 0 },
+ ],
+ expect.anything()
+ );
+ });
+
+ it('retargets an interrupted transition from the current visual position', async () => {
+ const board = fixture();
+ const card = board.item('lane:card', 0, 0);
+ board.motion.beginHover();
+ card.move(0, 120);
+ await frame();
+
+ // After layout moves to 240, the current local residual is -50.
+ card.element.getBoundingClientRect = () => new DOMRect(0, 190, 100, 80);
+ card.move(0, 240);
+ await frame();
+ expect(cancellations[0]).toHaveBeenCalledOnce();
+ expect(animate).toHaveBeenLastCalledWith(
+ [
+ { transform: 'translate(0px, -170px)' },
+ { transform: 'translate(0, 0)' },
+ ],
+ expect.objectContaining({ duration: 200 })
+ );
+ });
+
+ it('removes a cleared hover placeholder without leaving a ghost', async () => {
+ const board = fixture();
+ const card = board.item('lane:card', 0, 116);
+ board.motion.beginHover();
+ const placeholder = board.item('lane:placeholder', 0, 0);
+ card.move(0, 232);
+ await frame();
+ placeholder.remove();
+ card.move(0, 116);
+ await frame();
+
+ expect(placeholder.element.isConnected).toBe(false);
+ expect(document.body.querySelector('[aria-hidden="true"]')).toBeNull();
+ expect(cancellations.some((cancel) => cancel.mock.calls.length > 0)).toBe(
+ true
+ );
+ });
+
+ it('skips hover transitions for reduced motion', async () => {
+ vi.stubGlobal('matchMedia', () => ({ matches: true }));
+ const board = fixture();
+ const card = board.item('lane:card', 0, 0);
+ board.motion.beginHover();
+ card.move(0, 116);
+ await frame();
+ expect(animate).not.toHaveBeenCalled();
+ });
+
+ it('cancels a completed move flight when reveal scrolling changes its viewport', async () => {
+ const board = fixture();
+ const source = board.item('a:task', 0, 0, 'task');
+ const finish = board.motion.begin('task');
+ source.remove();
+ board.item('b:task', 300, 100, 'task');
+ await frame();
+ const ghost = document.body.querySelector<HTMLElement>(
+ '[aria-hidden="true"]'
+ )!;
+ finish();
+ await frame();
+
+ board.viewport.dispatchEvent(new Event('scroll'));
+ expect(ghost.isConnected).toBe(false);
+ expect(cancellations[0]).toHaveBeenCalledOnce();
+ expect(cancellations[1]).toHaveBeenCalledOnce();
+ });
+ it('cancels a settling animation on a new pointer interaction even after the save finishes', async () => {
+ const board = fixture();
+ const card = board.item('a:task', 0, 0, 'task');
+ const finish = board.motion.begin('task');
+ card.move(0, 120);
+ await frame();
+ finish();
+ await frame();
+ board.viewport.dispatchEvent(new Event('pointerdown', { bubbles: true }));
+
+ expect(cancellations[0]).toHaveBeenCalledOnce();
+ await frame();
+ expect(animate).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/web/src/components/kanban/kanban-animation.ts b/apps/web/src/components/kanban/kanban-animation.ts
new file mode 100644
index 0000000000..e63ce494b3
--- /dev/null
+++ b/apps/web/src/components/kanban/kanban-animation.ts
@@ -0,0 +1,565 @@
+export type KanbanAnimationItem = {
+ /** Unique placement, including the lane for cards with several placements. */
+ key: string;
+ /** Shared identity lets a card animate across remounted placements. */
+ identity?: string;
+ placeholder?: boolean;
+ parentKey?: string;
+ element: HTMLElement;
+ /** Unanimated positioning wrapper, used for stable virtualized measurements. */
+ layout: HTMLElement;
+};
+
+export type KanbanAnimationOrigin = {
+ /** Placement identity survives source virtualization at drag release. */
+ key: string;
+ element: HTMLElement;
+ rect: DOMRectReadOnly;
+ parentKey: string;
+};
+
+type Snapshot = KanbanAnimationItem & {
+ rect: DOMRect;
+ clone?: HTMLElement;
+ dragOrigin?: boolean;
+};
+
+const DURATION = 200;
+const TIMING: KeyframeAnimationOptions = {
+ duration: DURATION,
+ easing: 'cubic-bezier(0.2, 0, 0, 1)',
+};
+
+/** Observe layout during a drag hover or host-owned move, never ordinary paging. */
+export function createKanbanAnimation(options: {
+ viewport(): HTMLElement | undefined;
+ items(): KanbanAnimationItem[];
+}) {
+ let snapshots = new Map<string, Snapshot>();
+ let observer: MutationObserver | undefined;
+ let observedViewport: HTMLElement | undefined;
+ let frame: number | undefined;
+ let moves = 0;
+ let hovering = false;
+ let generation = 0;
+ const animations = new Set<Animation>();
+ const activeElements = new Map<HTMLElement, Animation>();
+ const ghosts = new Set<HTMLElement>();
+ const movingIdentities = new Set<string>();
+ const destinations = new Map<string, string>();
+ const flights = new Map<string, HTMLElement>();
+
+ const reducedMotion = () =>
+ window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
+
+ function clearAnimations() {
+ for (const animation of animations) {
+ animation.cancel();
+ }
+
+ animations.clear();
+ activeElements.clear();
+
+ for (const ghost of ghosts) {
+ ghost.remove();
+ }
+
+ ghosts.clear();
+ flights.clear();
+ }
+
+ function capture() {
+ const viewport = options.viewport();
+ const result = new Map<string, Snapshot>();
+
+ if (!viewport) {
+ return result;
+ }
+
+ const bounds = viewport.getBoundingClientRect();
+ const items = options.items();
+ const byKey = new Map(items.map((item) => [item.key, item]));
+
+ for (const item of items) {
+ const rect = normalizedRect(item, byKey);
+
+ if (
+ rect.width === 0 ||
+ rect.height === 0 ||
+ rect.right <= bounds.left ||
+ rect.left >= bounds.right ||
+ rect.bottom <= bounds.top ||
+ rect.top >= bounds.bottom
+ ) {
+ continue;
+ }
+
+ result.set(item.key, {
+ ...item,
+ rect,
+ clone:
+ (item.placeholder && hovering) ||
+ (item.identity && movingIdentities.has(item.identity))
+ ? (item.element.cloneNode(true) as HTMLElement)
+ : undefined,
+ });
+ }
+
+ return result;
+ }
+
+ // A wrapper inherits every animated ancestor, although it has no local animation.
+ function normalizedRect(
+ item: KanbanAnimationItem,
+ byKey: Map<string, KanbanAnimationItem>
+ ): DOMRect {
+ const rect = item.layout.getBoundingClientRect();
+ let x = rect.left;
+ let y = rect.top;
+ let parentKey = item.parentKey;
+ const seen = new Set<string>();
+
+ while (parentKey && !seen.has(parentKey)) {
+ seen.add(parentKey);
+ const parent = byKey.get(parentKey);
+ if (!parent) {
+ break;
+ }
+
+ if (activeElements.has(parent.element)) {
+ const layout = parent.layout.getBoundingClientRect();
+ const visible = parent.element.getBoundingClientRect();
+ x -= visible.left - layout.left;
+ y -= visible.top - layout.top;
+ }
+ parentKey = parent.parentKey;
+ }
+
+ return new DOMRect(x, y, rect.width, rect.height);
+ }
+
+ function residuals(items: Map<string, Snapshot>) {
+ const result = new Map<string, { x: number; y: number }>();
+ for (const item of items.values()) {
+ if (!activeElements.has(item.element) || !item.element.isConnected) {
+ continue;
+ }
+ const layout = item.layout.getBoundingClientRect();
+ const visible = item.element.getBoundingClientRect();
+ result.set(item.key, {
+ x: visible.left - layout.left,
+ y: visible.top - layout.top,
+ });
+ }
+ return result;
+ }
+
+ function totalResidual(
+ item: Snapshot,
+ values: Map<string, { x: number; y: number }>,
+ items: Map<string, Snapshot>
+ ) {
+ let x = 0;
+ let y = 0;
+ let key: string | undefined = item.key;
+ const seen = new Set<string>();
+ while (key && !seen.has(key)) {
+ seen.add(key);
+ const value = values.get(key);
+ x += value?.x ?? 0;
+ y += value?.y ?? 0;
+ key = items.get(key)?.parentKey;
+ }
+ return { x, y };
+ }
+
+ function animate(
+ element: HTMLElement,
+ keyframes: Keyframe[],
+ done?: () => void
+ ) {
+ if (!element.animate) {
+ done?.();
+ return;
+ }
+
+ const animation = element.animate(keyframes, TIMING);
+ animations.add(animation);
+ activeElements.set(element, animation);
+ const finish = async () => {
+ try {
+ await animation.finished;
+ } catch {
+ // Cancellation rejects finished; both paths release the visual state.
+ } finally {
+ animations.delete(animation);
+ if (activeElements.get(element) === animation) {
+ activeElements.delete(element);
+ }
+ done?.();
+
+ if (!observer && !hovering && moves === 0 && animations.size === 0) {
+ detachViewport();
+ }
+ }
+ };
+ void finish();
+ }
+
+ function fly(
+ from: Snapshot,
+ to: Snapshot,
+ start?: { rect: DOMRect; clone: HTMLElement; opacity: string },
+ placeholder = false
+ ) {
+ const ghost = start?.clone ?? from.clone;
+ if (!ghost) {
+ return;
+ }
+
+ const rect = start?.rect ?? from.rect;
+ const opacity = start?.opacity ?? '1';
+ ghost.inert = true;
+ ghost.setAttribute('aria-hidden', 'true');
+ ghost.removeAttribute('id');
+
+ for (const child of ghost.querySelectorAll('[id]')) {
+ child.removeAttribute('id');
+ }
+
+ Object.assign(ghost.style, {
+ position: 'fixed',
+ pointerEvents: 'none',
+ margin: '0',
+ left: `${rect.left}px`,
+ top: `${rect.top}px`,
+ width: `${rect.width}px`,
+ height: `${rect.height}px`,
+ zIndex: '1000',
+ opacity,
+ });
+ document.body.append(ghost);
+ ghosts.add(ghost);
+ flights.set(to.key, ghost);
+ animate(
+ ghost,
+ [
+ { transform: 'translate(0, 0)', opacity: Number(opacity) },
+ {
+ transform: `translate(${to.rect.left - rect.left}px, ${to.rect.top - rect.top}px)`,
+ opacity: placeholder ? 0 : 1,
+ },
+ ],
+ () => {
+ ghost.remove();
+ ghosts.delete(ghost);
+ if (flights.get(to.key) === ghost) {
+ flights.delete(to.key);
+ }
+ }
+ );
+ // Cards hand off at landing instead of showing two cross-fading copies.
+ animate(to.element, [{ opacity: 0 }, { opacity: placeholder ? 1 : 0 }]);
+ }
+
+ function play() {
+ frame = undefined;
+ const next = capture();
+ const changed =
+ next.size !== snapshots.size ||
+ [...next.values()].some((item) => {
+ const previous = snapshots.get(item.key);
+ return (
+ !previous ||
+ previous.rect.left !== item.rect.left ||
+ previous.rect.top !== item.rect.top
+ );
+ });
+
+ if (!changed) {
+ snapshots = next;
+ if (!hovering && moves === 0) disconnect();
+ return;
+ }
+
+ // Sample every active element and ghost before cancelling any animation.
+ const residual = residuals(snapshots);
+ const flightStarts = new Map<
+ string,
+ {
+ rect: DOMRect;
+ clone: HTMLElement;
+ opacity: string;
+ }
+ >();
+ for (const [key, ghost] of flights) {
+ const rect = ghost.getBoundingClientRect();
+ flightStarts.set(key, {
+ rect:
+ rect.width && rect.height
+ ? rect
+ : new DOMRect(
+ Number.parseFloat(ghost.style.left),
+ Number.parseFloat(ghost.style.top),
+ Number.parseFloat(ghost.style.width),
+ Number.parseFloat(ghost.style.height)
+ ),
+ clone: ghost.cloneNode(true) as HTMLElement,
+ opacity: getComputedStyle(ghost).opacity || ghost.style.opacity || '1',
+ });
+ }
+ clearAnimations();
+
+ if (!reducedMotion()) {
+ const removed = [...snapshots.values()].filter(
+ (item) => !next.has(item.key)
+ );
+ const used = new Set<Snapshot>();
+ const displacement = (item: Snapshot, previous: Snapshot) => {
+ const remaining = totalResidual(previous, residual, snapshots);
+ return {
+ x: previous.rect.left + remaining.x - item.rect.left,
+ y: previous.rect.top + remaining.y - item.rect.top,
+ };
+ };
+
+ for (const item of next.values()) {
+ const previous = snapshots.get(item.key);
+ if (previous && flightStarts.has(item.key)) {
+ fly(previous, item, flightStarts.get(item.key), !!item.placeholder);
+ continue;
+ }
+
+ if (previous?.dragOrigin) {
+ fly(previous, item);
+ continue;
+ }
+
+ if (!previous) {
+ if (item.placeholder && hovering) {
+ const source = removed.find(
+ (candidate) => candidate.placeholder && !used.has(candidate)
+ );
+ if (source) {
+ fly(source, item, flightStarts.get(source.key), true);
+ used.add(source);
+ } else {
+ animate(item.element, [{ opacity: 0 }, { opacity: 1 }]);
+ }
+ }
+ const source = item.identity
+ ? removed.find(
+ (candidate) =>
+ candidate.identity === item.identity && !used.has(candidate)
+ )
+ : undefined;
+ if (
+ source &&
+ (!destinations.has(item.identity!) ||
+ item.parentKey === destinations.get(item.identity!))
+ ) {
+ fly(source, item, flightStarts.get(source.key));
+ used.add(source);
+ }
+ continue;
+ }
+
+ const total = displacement(item, previous);
+ const oldParent = item.parentKey
+ ? snapshots.get(item.parentKey)
+ : undefined;
+ const newParent = item.parentKey ? next.get(item.parentKey) : undefined;
+ const parent =
+ oldParent && newParent
+ ? displacement(newParent, oldParent)
+ : { x: 0, y: 0 };
+ const x = total.x - parent.x;
+ const y = total.y - parent.y;
+
+ if (Math.abs(x) < 1 && Math.abs(y) < 1) {
+ continue;
+ }
+
+ animate(item.element, [
+ { transform: `translate(${x}px, ${y}px)` },
+ { transform: 'translate(0, 0)' },
+ ]);
+ }
+
+ // A removed placement can merge into an already mounted destination.
+ for (const source of removed) {
+ if (!source.identity || used.has(source)) {
+ continue;
+ }
+ const destinationKey = destinations.get(source.identity);
+ if (!destinationKey) {
+ continue;
+ }
+ const target = [...next.values()].find(
+ (item) =>
+ item.identity === source.identity &&
+ item.parentKey === destinationKey
+ );
+ if (target) {
+ fly(source, target, flightStarts.get(source.key));
+ used.add(source);
+ }
+ }
+ }
+
+ snapshots = next;
+ if (!hovering && moves === 0) disconnect();
+ }
+
+ function schedule() {
+ if (frame !== undefined) {
+ return;
+ }
+
+ frame = requestAnimationFrame(play);
+ }
+
+ // Scrolling and fresh pointer interactions must not animate virtualized mounts.
+ function resetLayout() {
+ if (frame !== undefined) {
+ cancelAnimationFrame(frame);
+ frame = undefined;
+ }
+
+ clearAnimations();
+ if (!observer && !hovering && moves === 0) detachViewport();
+ snapshots.clear();
+ schedule();
+ }
+
+ function disconnect() {
+ observer?.disconnect();
+ observer = undefined;
+ // A completed save can still have a flying card when reveal scrolling runs.
+ if (animations.size === 0) detachViewport();
+ }
+
+ function detachViewport() {
+ observedViewport?.removeEventListener('scroll', resetLayout, true);
+ observedViewport?.removeEventListener('pointerdown', resetLayout, true);
+ observedViewport = undefined;
+ }
+
+ function cancel() {
+ generation += 1;
+ moves = 0;
+ disconnect();
+
+ if (frame !== undefined) {
+ cancelAnimationFrame(frame);
+ frame = undefined;
+ }
+
+ clearAnimations();
+ detachViewport();
+ snapshots.clear();
+ movingIdentities.clear();
+ destinations.clear();
+ hovering = false;
+ }
+
+ function observe(viewport: HTMLElement) {
+ detachViewport();
+ observedViewport = viewport;
+ observer = new MutationObserver(schedule);
+ observer.observe(viewport, {
+ subtree: true,
+ childList: true,
+ attributes: true,
+ attributeFilter: ['style'],
+ });
+ viewport.addEventListener('scroll', resetLayout, true);
+ viewport.addEventListener('pointerdown', resetLayout, true);
+ }
+
+ function beginHover() {
+ const viewport = options.viewport();
+ if (!viewport || reducedMotion() || hovering) return () => {};
+
+ hovering = true;
+ if (moves === 0) {
+ movingIdentities.clear();
+ destinations.clear();
+ snapshots = capture();
+ if (!observer) observe(viewport);
+ }
+ const started = generation;
+ return () => {
+ if (generation !== started) return;
+ hovering = false;
+ schedule();
+ };
+ }
+
+ function begin(
+ identity: string,
+ destinationParentKey?: string,
+ origin?: KanbanAnimationOrigin
+ ) {
+ const viewport = options.viewport();
+
+ if (!viewport || reducedMotion()) {
+ return () => {};
+ }
+
+ if (moves === 0 && !observer) {
+ movingIdentities.clear();
+ destinations.clear();
+ movingIdentities.add(identity);
+ snapshots = capture();
+ observe(viewport);
+ }
+
+ if (!movingIdentities.has(identity)) {
+ movingIdentities.add(identity);
+
+ // Retain the current first frame for other pending moves.
+ for (const item of capture().values()) {
+ if (item.identity === identity) {
+ snapshots.set(item.key, item);
+ }
+ }
+ }
+
+ if (origin && origin.rect.width > 0 && origin.rect.height > 0) {
+ const { key, element, rect, parentKey } = origin;
+ snapshots.set(key, {
+ key,
+ identity,
+ parentKey,
+ element,
+ layout: element,
+ rect: new DOMRect(rect.left, rect.top, rect.width, rect.height),
+ clone: element.cloneNode(true) as HTMLElement,
+ dragOrigin: true,
+ });
+ }
+ if (destinationParentKey) {
+ destinations.set(identity, destinationParentKey);
+ }
+ moves += 1;
+ const started = generation;
+ let finished = false;
+
+ return () => {
+ if (finished || generation !== started) {
+ return;
+ }
+
+ finished = true;
+ moves -= 1;
+ schedule();
+
+ if (moves === 0 && !hovering) {
+ disconnect();
+ }
+ };
+ }
+
+ return { begin, beginHover, cancel };
+}
diff --git a/apps/web/src/components/kanban/kanban-collision.test.ts b/apps/web/src/components/kanban/kanban-collision.test.ts
new file mode 100644
index 0000000000..a74c9bc795
--- /dev/null
+++ b/apps/web/src/components/kanban/kanban-collision.test.ts
@@ -0,0 +1,106 @@
+import type { Droppable } from '@thisbeyond/solid-dnd';
+import { describe, expect, it } from 'vitest';
+import { findKanbanCollision } from './kanban-collision';
+
+const viewport = new DOMRect(0, 0, 600, 400);
+const source = { data: { kind: 'card', itemId: 'moving', laneId: 'source' } };
+
+function lane(id: string, left: number): Droppable {
+ const node = document.createElement('div');
+ node.getBoundingClientRect = () => new DOMRect(left, 0, 200, 400);
+ const rect = node.getBoundingClientRect();
+ const layout = {
+ x: rect.x,
+ y: rect.y,
+ width: rect.width,
+ height: rect.height,
+ left: rect.left,
+ right: rect.right,
+ top: rect.top,
+ bottom: rect.bottom,
+ rect,
+ center: { x: left + 100, y: 200 },
+ corners: {
+ topLeft: { x: left, y: 0 },
+ topRight: { x: left + 200, y: 0 },
+ bottomLeft: { x: left, y: 400 },
+ bottomRight: { x: left + 200, y: 400 },
+ },
+ };
+ return {
+ id,
+ node,
+ data: { laneId: id },
+ layout,
+ transformed: layout,
+ transform: { x: 0, y: 0 },
+ transformers: {},
+ };
+}
+
+function card(destination: Droppable, id: string, top: number, nextId = '') {
+ const layout = document.createElement('div');
+ layout.dataset.kanbanCardLayout = '';
+ layout.dataset.kanbanNextId = nextId;
+ layout.getBoundingClientRect = () => new DOMRect(220, top, 200, 100);
+ const node = document.createElement('div');
+ node.dataset.kanbanCard = id;
+ layout.append(node);
+ destination.node.append(layout);
+ return layout;
+}
+
+const options = {
+ mode: 'cross-column',
+ pointerPlacement: true,
+ viewport,
+} as const;
+
+describe('Kanban collision geometry', () => {
+ it('uses layout midpoints and retains the next unmounted card as the insertion anchor', () => {
+ const destination = lane('destination', 220);
+ card(destination, 'first', 0);
+ card(destination, 'second', 100, 'offscreen');
+
+ expect(
+ findKanbanCollision(source, [destination], { x: 240, y: 120 }, options)
+ ?.drop
+ ).toMatchObject({ toLane: 'destination', beforeId: 'second' });
+ expect(
+ findKanbanCollision(source, [destination], { x: 240, y: 190 }, options)
+ ?.drop
+ ).toMatchObject({ toLane: 'destination', beforeId: 'offscreen' });
+ });
+
+ it('keeps the insertion anchor while hovering the space opened by its placeholder', () => {
+ const destination = lane('destination', 220);
+ const layout = card(destination, 'first', 100);
+ const placeholder = document.createElement('div');
+ placeholder.dataset.kanbanPlaceholder = '';
+ placeholder.dataset.kanbanBeforeId = 'first';
+ layout.replaceChildren(placeholder);
+
+ expect(
+ findKanbanCollision(source, [destination], { x: 240, y: 190 }, options)
+ ?.drop
+ ).toMatchObject({ beforeId: 'first' });
+ });
+
+ it('rejects gaps and off-viewport drops without changing ordered-mode gap selection', () => {
+ const lanes = [lane('source', 0), lane('destination', 220)];
+ expect(
+ findKanbanCollision(source, lanes, { x: 210, y: 120 }, options)
+ ).toBeNull();
+ expect(
+ findKanbanCollision(source, lanes, { x: 240, y: 410 }, options)
+ ).toBeNull();
+ expect(
+ findKanbanCollision(
+ source,
+ lanes,
+ { x: 215, y: 120 },
+ { mode: 'ordered', viewport }
+ )?.drop
+ ).toMatchObject({ toLane: 'destination' });
+ });
+});
diff --git a/apps/web/src/components/kanban/kanban-collision.ts b/apps/web/src/components/kanban/kanban-collision.ts
new file mode 100644
index 0000000000..3098f071c4
--- /dev/null
+++ b/apps/web/src/components/kanban/kanban-collision.ts
@@ -0,0 +1,251 @@
+import type { Draggable, Droppable } from '@thisbeyond/solid-dnd';
+import type { KanbanDrop } from './kanban-types';
+
+export const LANE_INSERTION_INSET = 10;
+
+type Point = { x: number; y: number };
+
+type MeasuredLane = {
+ droppable: Droppable;
+ rect: DOMRect;
+};
+
+type DropLocation = {
+ id: string;
+ fromLane: string;
+ toLane: string;
+};
+
+type CollisionOptions = {
+ mode: 'ordered' | 'cross-column';
+ viewport?: DOMRect;
+ pointerPlacement?: boolean;
+};
+
+type KanbanCollision = {
+ drop: KanbanDrop;
+ droppable: Droppable;
+};
+
+function isOutside(value: number, start: number, end: number) {
+ return value < start || value > end;
+}
+
+function findClosestLane(
+ lanes: MeasuredLane[],
+ pointer: Point,
+ viewport?: DOMRect
+) {
+ if (lanes.length === 0) {
+ return undefined;
+ }
+
+ const left = lanes[0].rect.left;
+ const right = lanes[lanes.length - 1].rect.right;
+
+ if (isOutside(pointer.x, left, right)) {
+ return undefined;
+ }
+
+ if (!viewport) {
+ const top = Math.min(...lanes.map((lane) => lane.rect.top));
+ const bottom = Math.max(...lanes.map((lane) => lane.rect.bottom));
+
+ if (isOutside(pointer.y, top, bottom)) {
+ return undefined;
+ }
+ }
+
+ return lanes.reduce((closest, lane) => {
+ const center = lane.rect.left + lane.rect.width / 2;
+ const closestCenter = closest.rect.left + closest.rect.width / 2;
+ const distance = Math.abs(pointer.x - center);
+ const closestDistance = Math.abs(pointer.x - closestCenter);
+
+ if (distance < closestDistance) {
+ return lane;
+ }
+
+ return closest;
+ });
+}
+
+function getLaneDrop(
+ location: DropLocation,
+ lane: MeasuredLane,
+ lanes: MeasuredLane[],
+ pointerX: number,
+ viewport?: DOMRect
+): KanbanDrop | undefined {
+ const { fromLane, toLane } = location;
+
+ if (fromLane === toLane) {
+ return undefined;
+ }
+
+ const center = lane.rect.left + lane.rect.width / 2;
+ const edge = pointerX < center ? 'before' : 'after';
+ const boundary =
+ edge === 'before'
+ ? lane.rect.left - LANE_INSERTION_INSET
+ : lane.rect.right + LANE_INSERTION_INSET;
+
+ if (viewport && isOutside(boundary, viewport.left, viewport.right)) {
+ return undefined;
+ }
+
+ const originalIndex = lanes.findIndex(
+ (lane) => lane.droppable.data.laneId === fromLane
+ );
+
+ if (originalIndex < 0) {
+ return undefined;
+ }
+
+ const remaining = lanes.filter(
+ (lane) => lane.droppable.data.laneId !== fromLane
+ );
+ const destinationIndex = remaining.findIndex(
+ (lane) => lane.droppable.data.laneId === toLane
+ );
+ const insertionIndex = destinationIndex + (edge === 'after' ? 1 : 0);
+
+ if (insertionIndex === originalIndex) {
+ return undefined;
+ }
+
+ return { kind: 'lane', ...location, edge };
+}
+
+function getCardDrop(
+ location: DropLocation,
+ lane: MeasuredLane,
+ pointerY: number,
+ pointerPlacement = false
+): KanbanDrop | undefined {
+ const { id, fromLane, toLane } = location;
+ if (pointerPlacement) {
+ const placeholder = lane.droppable.node.querySelector<HTMLElement>(
+ '[data-kanban-placeholder]'
+ );
+ const bounds = placeholder?.parentElement?.getBoundingClientRect();
+
+ if (
+ placeholder &&
+ bounds &&
+ pointerY >= bounds.top &&
+ pointerY <= bounds.bottom
+ ) {
+ return {
+ kind: 'card',
+ ...location,
+ beforeId: placeholder.dataset.kanbanBeforeId || undefined,
+ };
+ }
+ }
+ const cards = Array.from(
+ lane.droppable.node.querySelectorAll<HTMLElement>('[data-kanban-card]')
+ );
+ const remaining = cards.filter((card) => card.dataset.kanbanCard !== id);
+ const next = remaining.find((card) => {
+ const layout = pointerPlacement
+ ? card.closest<HTMLElement>('[data-kanban-card-layout]')
+ : undefined;
+ const bounds = (layout ?? card).getBoundingClientRect();
+
+ return pointerY < bounds.top + bounds.height / 2;
+ });
+
+ if (fromLane === toLane) {
+ const insertionIndex = next ? remaining.indexOf(next) : remaining.length;
+ const originalIndex = cards.findIndex(
+ (card) => card.dataset.kanbanCard === id
+ );
+
+ if (insertionIndex === originalIndex) {
+ return undefined;
+ }
+ }
+
+ const last = remaining.at(-1);
+ const nextId = pointerPlacement
+ ? last?.closest<HTMLElement>('[data-kanban-card-layout]')?.dataset
+ .kanbanNextId
+ : undefined;
+ return {
+ kind: 'card',
+ ...location,
+ beforeId: next?.dataset.kanbanCard ?? (nextId || undefined),
+ };
+}
+
+/** Measures the current DOM so scrolling never leaves stale collision targets. */
+export function findKanbanCollision(
+ draggable: Pick<Draggable, 'data'>,
+ droppables: Droppable[],
+ pointer: Point,
+ options: CollisionOptions
+): KanbanCollision | null {
+ const { mode, viewport } = options;
+
+ if (viewport) {
+ const outsideX = isOutside(pointer.x, viewport.left, viewport.right);
+ const outsideY = isOutside(pointer.y, viewport.top, viewport.bottom);
+
+ if (outsideX || outsideY) {
+ return null;
+ }
+ }
+
+ const lanes = droppables
+ .map((droppable) => ({
+ droppable,
+ rect: droppable.node.getBoundingClientRect(),
+ }))
+ .sort((a, b) => a.rect.left - b.rect.left);
+ const lane = findClosestLane(lanes, pointer, viewport);
+
+ if (!lane) {
+ return null;
+ }
+
+ if (mode === 'cross-column') {
+ const outsideX = isOutside(pointer.x, lane.rect.left, lane.rect.right);
+ const outsideY = isOutside(pointer.y, lane.rect.top, lane.rect.bottom);
+
+ if (outsideX || outsideY) {
+ return null;
+ }
+ }
+
+ const { kind, itemId: id, laneId: fromLane } = draggable.data;
+ const toLane: unknown = lane.droppable.data.laneId;
+ const validSource = typeof id === 'string' && typeof fromLane === 'string';
+
+ if (!validSource || typeof toLane !== 'string') {
+ return null;
+ }
+
+ const location = { id, fromLane, toLane };
+
+ if (kind === 'lane') {
+ if (mode === 'cross-column') {
+ return null;
+ }
+
+ const drop = getLaneDrop(location, lane, lanes, pointer.x, viewport);
+
+ return drop ? { drop, droppable: lane.droppable } : null;
+ }
+
+ if (kind !== 'card') {
+ return null;
+ }
+
+ const drop: KanbanDrop | undefined =
+ mode === 'cross-column' && !options.pointerPlacement
+ ? { kind: 'card', ...location }
+ : getCardDrop(location, lane, pointer.y, options.pointerPlacement);
+
+ return drop ? { drop, droppable: lane.droppable } : null;
+}
diff --git a/apps/web/src/components/kanban/kanban-pointer-intent.test.ts b/apps/web/src/components/kanban/kanban-pointer-intent.test.ts
new file mode 100644
index 0000000000..0945e3f3ba
--- /dev/null
+++ b/apps/web/src/components/kanban/kanban-pointer-intent.test.ts
@@ -0,0 +1,43 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { createKanbanPointerIntent } from './kanban-pointer-intent';
+
+afterEach(() => vi.useRealTimers());
+
+it('suppresses fast travel, then activates a stationary pointer', () => {
+ vi.useFakeTimers();
+ const settled = vi.fn();
+ const intent = createKanbanPointerIntent({ speed: () => 600, settled });
+ intent.reset({ x: 0, y: 0 });
+ vi.advanceTimersByTime(16);
+ expect(intent.update({ x: 300, y: 0 })).toBe(false);
+ expect(intent.update({ x: 300, y: 0 })).toBe(false);
+ vi.advanceTimersByTime(99);
+ expect(settled).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(settled).toHaveBeenCalledOnce();
+ expect(intent.update({ x: 300, y: 0 })).toBe(true);
+});
+
+it('accepts slow movement and cancels stale activation after release', () => {
+ vi.useFakeTimers();
+ const settled = vi.fn();
+ const intent = createKanbanPointerIntent({ speed: () => 600, settled });
+ intent.reset({ x: 0, y: 0 });
+ vi.advanceTimersByTime(16);
+ expect(intent.update({ x: 300, y: 0 })).toBe(false);
+ vi.advanceTimersByTime(50);
+ expect(intent.update({ x: 305, y: 0 })).toBe(true);
+ vi.advanceTimersByTime(100);
+ expect(settled).not.toHaveBeenCalled();
+ expect(intent.update({ x: 700, y: 0 })).toBe(false);
+ intent.reset();
+ vi.advanceTimersByTime(200);
+ expect(settled).not.toHaveBeenCalled();
+});
+
+it('leaves default consumers ungated', () => {
+ const settled = vi.fn();
+ const intent = createKanbanPointerIntent({ speed: () => undefined, settled });
+ intent.reset({ x: 0, y: 0 });
+ expect(intent.update({ x: 1000, y: 0 })).toBe(true);
+});
diff --git a/apps/web/src/components/kanban/kanban-pointer-intent.ts b/apps/web/src/components/kanban/kanban-pointer-intent.ts
new file mode 100644
index 0000000000..4b620ddebc
--- /dev/null
+++ b/apps/web/src/components/kanban/kanban-pointer-intent.ts
@@ -0,0 +1,49 @@
+type Point = { x: number; y: number };
+
+/** Gate previews during fast travel; a stationary pointer settles after 100 ms. */
+export function createKanbanPointerIntent(options: {
+ speed(): number | undefined;
+ settled(): void;
+}) {
+ let previous: (Point & { time: number }) | undefined;
+ let blocked = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ function reset(point?: Point) {
+ clearTimeout(timer);
+ previous = point ? { ...point, time: performance.now() } : undefined;
+ blocked = false;
+ }
+
+ function update(point: Point) {
+ const threshold = options.speed();
+
+ if (!threshold || !previous) {
+ previous = { ...point, time: performance.now() };
+ return true;
+ }
+
+ const distance = Math.hypot(point.x - previous.x, point.y - previous.y);
+
+ if (distance === 0) {
+ return !blocked;
+ }
+
+ const time = performance.now();
+ const speed = (distance * 1000) / Math.max(16, time - previous.time);
+ previous = { ...point, time };
+ blocked = speed > threshold * (blocked ? 0.6 : 1);
+ clearTimeout(timer);
+
+ if (blocked) {
+ timer = setTimeout(() => {
+ blocked = false;
+ options.settled();
+ }, 100);
+ }
+
+ return !blocked;
+ }
+
+ return { update, reset };
+}
diff --git a/apps/web/src/components/kanban/kanban-types.ts b/apps/web/src/components/kanban/kanban-types.ts
new file mode 100644
index 0000000000..8fde666a35
--- /dev/null
+++ b/apps/web/src/components/kanban/kanban-types.ts
@@ -0,0 +1,17 @@
+export type KanbanDrop = {
+ id: string;
+ fromLane: string;
+ toLane: string;
+} & (
+ | { kind: 'lane'; edge: 'before' | 'after' }
+ | { kind: 'card'; beforeId?: string }
+);
+
+/** A column change leaves card order to the caller (for example, a sorted view). */
+export type KanbanCrossColumnDrop = {
+ kind: 'card';
+ id: string;
+ fromLane: string;
+ toLane: string;
+ beforeId?: string;
+};
diff --git a/apps/web/src/components/kanban/kanban-virtualizer.ts b/apps/web/src/components/kanban/kanban-virtualizer.ts
new file mode 100644
index 0000000000..6ae2816e32
--- /dev/null
+++ b/apps/web/src/components/kanban/kanban-virtualizer.ts
@@ -0,0 +1,138 @@
+import {
+ createVirtualizer,
+ defaultRangeExtractor,
+ type Range,
+ type VirtualItem,
+} from '@tanstack/solid-virtual';
+import { useDragDropContext } from '@thisbeyond/solid-dnd';
+import {
+ type Accessor,
+ createEffect,
+ createSignal,
+ on,
+ onCleanup,
+ onMount,
+} from 'solid-js';
+
+export type KanbanScrollSnapshot = {
+ offset: number;
+ measurements: VirtualItem[];
+};
+
+type KanbanVirtualizerOptions = {
+ keys: Accessor<readonly (string | number)[]>;
+ getScrollElement: () => HTMLDivElement | undefined;
+ estimateSize: number;
+ gap: number;
+ overscan: number;
+ paddingStart?: number;
+ paddingEnd?: number;
+ snapshot?: KanbanScrollSnapshot;
+} & (
+ | { direction: 'horizontal' }
+ | { direction: 'vertical'; laneId: Accessor<string> }
+);
+
+/** Keep the drag source mounted even when its column or card leaves the viewport. */
+export function createKanbanVirtualizer(options: KanbanVirtualizerOptions) {
+ const context = useDragDropContext();
+
+ if (!context) {
+ throw new Error('Kanban virtualizers require a Kanban provider');
+ }
+
+ const [state, actions] = context;
+ const [scrollElement, setScrollElement] = createSignal<HTMLDivElement>();
+
+ onMount(() => {
+ // Suspense can create the viewport in an inert document before attaching it.
+ // Binding there leaves the virtualizer without a window or resize observer.
+ const observer = new MutationObserver(connect);
+
+ function connect() {
+ const element = options.getScrollElement();
+
+ if (!element?.isConnected) {
+ return;
+ }
+
+ observer.disconnect();
+ setScrollElement(element);
+ }
+
+ observer.observe(document, { childList: true, subtree: true });
+ connect();
+ onCleanup(() => observer.disconnect());
+ });
+
+ const pinnedIndex = () => {
+ const source = state.active.draggable?.data;
+
+ if (source?.kind !== 'card') {
+ return -1;
+ }
+
+ if (options.direction === 'horizontal') {
+ return options.keys().indexOf(source.laneId);
+ }
+
+ if (source.laneId !== options.laneId()) {
+ return -1;
+ }
+
+ return options.keys().indexOf(source.itemId);
+ };
+
+ const virtualizer = createVirtualizer<HTMLDivElement, HTMLDivElement>({
+ get count() {
+ return options.keys().length;
+ },
+ get getItemKey() {
+ const keys = options.keys();
+
+ return (index: number) => keys[index];
+ },
+ getScrollElement: () => scrollElement() ?? null,
+ horizontal: options.direction === 'horizontal',
+ estimateSize: () => options.estimateSize,
+ gap: options.gap,
+ overscan: options.overscan,
+ paddingStart: options.paddingStart,
+ paddingEnd: options.paddingEnd,
+ initialOffset: options.snapshot?.offset,
+ initialMeasurementsCache: options.snapshot?.measurements,
+ get rangeExtractor() {
+ const index = pinnedIndex();
+
+ return (range: Range) => {
+ const indexes = defaultRangeExtractor(range);
+
+ if (index < 0 || index >= range.count || indexes.includes(index)) {
+ return indexes;
+ }
+
+ return [...indexes, index].sort((a, b) => a - b);
+ };
+ },
+ });
+
+ createEffect(
+ on(
+ () => virtualizer.getVirtualItems(),
+ () => {
+ if (!state.active.draggable) {
+ return;
+ }
+
+ // New virtual columns mount after the scroll event's collision pass.
+ queueMicrotask(() => {
+ if (state.active.draggable) {
+ actions.detectCollisions();
+ }
+ });
+ }
+ )
+ );
+
+ return virtualizer;
+}
diff --git a/apps/web/src/components/kanban/kanban-wheel-scroll.test.ts b/apps/web/src/components/kanban/kanban-wheel-scroll.test.ts
new file mode 100644
index 0000000000..a93b946b75
--- /dev/null
+++ b/apps/web/src/components/kanban/kanban-wheel-scroll.test.ts
@@ -0,0 +1,90 @@
+import { afterEach, expect, it } from 'vitest';
+import { createKanbanWheelScroll } from './kanban-wheel-scroll';
+
+afterEach(() => document.body.replaceChildren());
+
+function fixture() {
+ const viewport = document.createElement('div');
+ const first = document.createElement('div');
+ const second = document.createElement('div');
+ first.dataset.lane = '';
+ second.dataset.lane = '';
+ viewport.append(first, second);
+ document.body.append(viewport);
+ for (const element of [viewport, first, second]) {
+ Object.defineProperties(element, {
+ clientWidth: { value: 100 },
+ scrollWidth: { value: 1000 },
+ clientHeight: { value: 100 },
+ scrollHeight: { value: 1000 },
+ });
+ }
+ let now = 0;
+ const scroll = createKanbanWheelScroll({
+ viewport: () => viewport,
+ verticalViewport: (target) => target.closest('[data-lane]'),
+ now: () => now,
+ });
+ viewport.addEventListener('wheel', scroll.onWheel);
+ const wheel = (
+ target: HTMLElement,
+ deltaY = 80,
+ extra: WheelEventInit = {}
+ ) => {
+ const event = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ deltaY,
+ ...extra,
+ });
+ target.dispatchEvent(event);
+ now += 16;
+ return event;
+ };
+ return {
+ viewport,
+ first,
+ second,
+ wheel,
+ idle: () => {
+ now += 181;
+ },
+ };
+}
+
+it('keeps horizontal momentum when a column moves underneath the pointer', () => {
+ const board = fixture();
+ board.wheel(board.viewport);
+ board.wheel(board.first);
+ board.wheel(board.second);
+ expect(board.viewport.scrollLeft).toBe(240);
+ expect(board.first.scrollTop).toBe(0);
+ expect(board.second.scrollTop).toBe(0);
+ board.idle();
+ board.wheel(board.second);
+ expect(board.viewport.scrollLeft).toBe(240);
+ expect(board.second.scrollTop).toBe(80);
+});
+
+it('keeps vertical momentum with its original column and consumes boundary events', () => {
+ const board = fixture();
+ board.wheel(board.first);
+ board.wheel(board.second);
+ board.wheel(board.viewport, 1000);
+ expect(board.first.scrollTop).toBe(900);
+ const boundary = board.wheel(board.second);
+ expect(boundary.defaultPrevented).toBe(true);
+ expect(board.second.scrollTop).toBe(0);
+ expect(board.viewport.scrollLeft).toBe(0);
+});
+
+it('supports native horizontal deltas, line units, and releases ownership for zoom', () => {
+ const board = fixture();
+ board.wheel(board.first, 0, { deltaX: 4, deltaMode: 1 });
+ expect(board.viewport.scrollLeft).toBe(64);
+ const zoom = board.wheel(board.first, 80, { ctrlKey: true });
+ expect(zoom.defaultPrevented).toBe(false);
+ expect(board.viewport.scrollLeft).toBe(64);
+ board.wheel(board.first);
+ expect(board.first.scrollTop).toBe(80);
+});
diff --git a/apps/web/src/components/kanban/kanban-wheel-scroll.ts b/apps/web/src/components/kanban/kanban-wheel-scroll.ts
new file mode 100644
index 0000000000..19d503b8db
--- /dev/null
+++ b/apps/web/src/components/kanban/kanban-wheel-scroll.ts
@@ -0,0 +1,80 @@
+const GESTURE_IDLE_MS = 180;
+
+/** Keep wheel momentum with its original scroll viewport while columns move under the pointer. */
+export function createKanbanWheelScroll(options: {
+ viewport(): HTMLElement | undefined;
+ verticalViewport(target: Element): HTMLElement | null;
+ now?: () => number;
+}) {
+ let owner: { element: HTMLElement; horizontal: boolean } | undefined;
+ let lastEvent = -Infinity;
+
+ function reset() {
+ owner = undefined;
+ lastEvent = -Infinity;
+ }
+
+ function onWheel(event: WheelEvent) {
+ if (event.ctrlKey) {
+ reset();
+ return;
+ }
+
+ if (event.defaultPrevented || (!event.deltaX && !event.deltaY)) {
+ return;
+ }
+
+ const viewport = options.viewport();
+
+ if (!viewport || !event.cancelable) {
+ return;
+ }
+
+ const now = options.now?.() ?? performance.now();
+
+ if (now - lastEvent > GESTURE_IDLE_MS || !owner?.element.isConnected) {
+ const vertical =
+ event.target instanceof Element
+ ? options.verticalViewport(event.target)
+ : null;
+ const useVertical =
+ vertical &&
+ viewport.contains(vertical) &&
+ vertical.scrollHeight > vertical.clientHeight &&
+ !event.shiftKey &&
+ Math.abs(event.deltaY) > Math.abs(event.deltaX);
+ owner = useVertical
+ ? { element: vertical, horizontal: false }
+ : { element: viewport, horizontal: true };
+ }
+
+ lastEvent = now;
+ const { element, horizontal } = owner;
+ const length = horizontal ? element.clientWidth : element.clientHeight;
+ const unit =
+ event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? length : 1;
+ const delta =
+ horizontal && Math.abs(event.deltaX) > Math.abs(event.deltaY)
+ ? event.deltaX
+ : event.deltaY;
+ const maximum = horizontal
+ ? element.scrollWidth - element.clientWidth
+ : element.scrollHeight - element.clientHeight;
+ const previous = horizontal ? element.scrollLeft : element.scrollTop;
+ const next = Math.max(
+ 0,
+ Math.min(Math.max(0, maximum), previous + delta * unit)
+ );
+
+ if (horizontal) {
+ element.scrollLeft = next;
+ } else {
+ element.scrollTop = next;
+ }
+
+ // Consume boundary events too: momentum must not leak into the element now under the pointer.
+ event.preventDefault();
+ }
+
+ return { onWheel, reset };
+}
diff --git a/apps/web/src/components/kanban/kanban.docs.tsx b/apps/web/src/components/kanban/kanban.docs.tsx
index 818daef889..f7a8eeaa90 100644
--- a/apps/web/src/components/kanban/kanban.docs.tsx
+++ b/apps/web/src/components/kanban/kanban.docs.tsx
@@ -9,40 +9,65 @@ import {
/** Query-free card and lane drag primitives, reusable by task or database boards. */
export default function KanbanExample() {
+ return (
+ <div class="flex flex-col gap-6">
+ <section>
+ <h2 class="text-sm font-semibold">Ordered cards and columns</h2>
+ <OrderedExample />
+ </section>
+ <section>
+ <h2 class="text-sm font-semibold">
+ Sorted cards, cross-column moves only
+ </h2>
+ <SortedCrossColumnExample />
+ </section>
+ </div>
+ );
+}
+
+function OrderedExample() {
const [lanes, setLanes] = createSignal(['Ideas', 'In progress', 'Done']);
const [cards, setCards] = createSignal([
{ id: 'one', title: 'Plan the next release', lane: 'Ideas' },
{ id: 'two', title: 'Review the design', lane: 'Ideas' },
{ id: 'three', title: 'Share the prototype', lane: 'In progress' },
]);
+
let viewport: HTMLDivElement | undefined;
+
return (
<Kanban
getViewport={() => viewport}
onDrop={(drop) => {
- if (drop.kind === 'card')
+ if (drop.kind === 'card') {
setCards((items) => {
const card = items.find((item) => item.id === drop.id);
- if (!card) return items;
+
+ if (!card) {
+ return items;
+ }
+
const next = items.filter((item) => item.id !== drop.id);
const before = next.findIndex((item) => item.id === drop.beforeId);
- next.splice(before < 0 ? next.length : before, 0, {
- ...card,
- lane: drop.toLane,
- });
- return next;
- });
- else
- setLanes((items) => {
- const next = [...items];
- next.splice(next.indexOf(drop.fromLane), 1);
- next.splice(
- next.indexOf(drop.toLane) + (drop.edge === 'after' ? 1 : 0),
- 0,
- drop.fromLane
- );
+ const insertionIndex = before < 0 ? next.length : before;
+
+ next.splice(insertionIndex, 0, { ...card, lane: drop.toLane });
return next;
});
+ return;
+ }
+
+ setLanes((items) => {
+ const next = [...items];
+ next.splice(next.indexOf(drop.fromLane), 1);
+
+ const destinationIndex = next.indexOf(drop.toLane);
+ const insertionIndex =
+ destinationIndex + (drop.edge === 'after' ? 1 : 0);
+
+ next.splice(insertionIndex, 0, drop.fromLane);
+ return next;
+ });
}}
>
<div ref={viewport} class="flex items-start gap-4 overflow-auto p-4">
@@ -72,3 +97,60 @@ export default function KanbanExample() {
</Kanban>
);
}
+
+/** A sorted board owns order and changes only the card's column on drop. */
+export function SortedCrossColumnExample() {
+ const columns = ['To do', 'In progress', 'Done'];
+ const [cards, setCards] = createSignal([
+ { id: 'one', title: 'Write tests', column: 'To do', priority: 2 },
+ { id: 'two', title: 'Review changes', column: 'To do', priority: 1 },
+ { id: 'three', title: 'Ship', column: 'In progress', priority: 3 },
+ ]);
+
+ let viewport: HTMLDivElement | undefined;
+
+ const cardsInColumn = (column: string) => {
+ return cards()
+ .filter((card) => card.column === column)
+ .sort((a, b) => a.priority - b.priority);
+ };
+
+ return (
+ <Kanban
+ mode="cross-column"
+ getViewport={() => viewport}
+ onDrop={(drop) => {
+ setCards((items) => {
+ return items.map((card) => {
+ if (card.id !== drop.id) {
+ return card;
+ }
+
+ return { ...card, column: drop.toLane };
+ });
+ });
+ }}
+ >
+ <div ref={viewport} class="flex items-start gap-4 overflow-auto p-4">
+ <For each={columns}>
+ {(column) => (
+ <KanbanLane id={column} label={`${column} column`}>
+ <h3 class="px-2 py-3 text-sm font-medium">{column}</h3>
+ <div class="flex flex-col gap-2">
+ <For each={cardsInColumn(column)}>
+ {(card) => (
+ <KanbanCard id={card.id} laneId={column} canDrag>
+ <div class="p-3 text-sm">
+ {card.title} · Priority {card.priority}
+ </div>
+ </KanbanCard>
+ )}
+ </For>
+ </div>
+ </KanbanLane>
+ )}
+ </For>
+ </div>
+ </Kanban>
+ );
+}
diff --git a/apps/web/src/components/kanban/kanban.tsx b/apps/web/src/components/kanban/kanban.tsx
index 50acfb1c0c..b58fe38d4a 100644
--- a/apps/web/src/components/kanban/kanban.tsx
+++ b/apps/web/src/components/kanban/kanban.tsx
@@ -5,6 +5,7 @@ import {
DragDropProvider,
DragOverlay,
} from '@thisbeyond/solid-dnd';
+import { cn } from '@ui';
import {
createContext,
createSignal,
@@ -15,20 +16,41 @@ import {
} from 'solid-js';
import { cloneDragPreview } from '../drag-drop/drag-preview';
import { DragSessionSensors } from '../drag-drop/drag-session-sensors';
+import { findKanbanCollision, LANE_INSERTION_INSET } from './kanban-collision';
+import { createKanbanPointerIntent } from './kanban-pointer-intent';
+import type { KanbanCrossColumnDrop, KanbanDrop } from './kanban-types';
-export type KanbanDrop = {
- id: string;
- fromLane: string;
- toLane: string;
+export type { KanbanCrossColumnDrop, KanbanDrop } from './kanban-types';
+
+export type KanbanDropVisual = {
+ element: HTMLElement;
+ rect: DOMRectReadOnly;
+};
+type KanbanProps = {
+ children: JSX.Element;
+ getViewport?: () => HTMLElement | undefined;
+ /** In cross-column mode, report pointer placement instead of host sorting. */
+ pointerPlacement?: boolean;
+ /** Gate entry to new columns above this pointer speed (pixels/second). */
+ targetActivationSpeed?: number;
} & (
- | { kind: 'lane'; edge: 'before' | 'after' }
- | { kind: 'card'; beforeId?: string }
+ | {
+ mode?: 'ordered';
+ onDrop: (drop: KanbanDrop) => void;
+ canDropCard?: (drop: Extract<KanbanDrop, { kind: 'card' }>) => boolean;
+ }
+ | {
+ mode: 'cross-column';
+ onDrop: (drop: KanbanCrossColumnDrop, visual?: KanbanDropVisual) => void;
+ canDropCard?: (drop: KanbanCrossColumnDrop) => boolean;
+ }
);
const DragContext = createContext<{
suppressClick: () => boolean;
start: (event: MouseEvent) => void;
target: () => KanbanDrop | undefined;
+ crossColumn: () => boolean;
}>();
const HandleContext = createContext<{
@@ -36,142 +58,183 @@ const HandleContext = createContext<{
disabled: boolean;
}>();
-const LANE_INSERTION_INSET = 10;
-
/** Query-free drag surface. Its preview is a snapshot of the original at its exact size. */
-export function Kanban(props: {
- children: JSX.Element;
- onDrop: (drop: KanbanDrop) => void;
- getViewport?: () => HTMLElement | undefined;
- canDropCard?: (drop: Extract<KanbanDrop, { kind: 'card' }>) => boolean;
-}) {
+export function Kanban(props: KanbanProps) {
const [preview, setPreview] = createSignal<HTMLElement>();
const [target, setTarget] = createSignal<KanbanDrop>();
+
let origin: { x: number; y: number } | undefined;
let suppressClick = false;
let cancelled = false;
- const releaseClick = () =>
+ let reevaluate: (() => void) | undefined;
+ let dropVisual: KanbanDropVisual | undefined;
+ const intent = createKanbanPointerIntent({
+ speed: () => props.targetActivationSpeed,
+ settled: () => reevaluate?.(),
+ });
+ const clearIntent = () => {
+ intent.reset();
+ reevaluate = undefined;
+ };
+ onCleanup(clearIntent);
+
+ const canDropCard = (drop: Extract<KanbanDrop, { kind: 'card' }>) => {
+ if (props.mode !== 'cross-column') {
+ return props.canDropCard?.(drop) ?? true;
+ }
+
+ if (drop.fromLane === drop.toLane) {
+ return false;
+ }
+
+ return (
+ props.canDropCard?.({
+ kind: 'card',
+ id: drop.id,
+ fromLane: drop.fromLane,
+ toLane: drop.toLane,
+ ...(props.pointerPlacement ? { beforeId: drop.beforeId } : {}),
+ }) ?? true
+ );
+ };
+
+ const releaseClick = () => {
setTimeout(() => {
suppressClick = false;
}, 0);
- onCleanup(() => document.removeEventListener('mouseup', releaseClick));
+ };
+
+ const rejectCollision = () => {
+ setTarget(undefined);
+ return null;
+ };
+
const collisionDetector: CollisionDetector = (draggable, droppables) => {
- const reject = () => {
- setTarget(undefined);
- return null;
- };
- if (!origin || cancelled) return reject();
+ if (!origin || cancelled) {
+ return rejectCollision();
+ }
+
+ const element = preview();
+ if (element && props.mode === 'cross-column') {
+ // The overlay detaches and its transform resets before onDragEnd runs.
+ const rect = draggable.transformed;
+ dropVisual = {
+ element,
+ rect: new DOMRect(rect.left, rect.top, rect.width, rect.height),
+ };
+ }
+
const pointer = {
x: origin.x + draggable.transform.x,
y: origin.y + draggable.transform.y,
};
- const viewport = props.getViewport?.()?.getBoundingClientRect();
- if (
- viewport &&
- (pointer.x < viewport.left ||
- pointer.x > viewport.right ||
- pointer.y < viewport.top ||
- pointer.y > viewport.bottom)
- )
- return reject();
- const lanes = droppables
- .map((droppable) => ({
- droppable,
- rect: droppable.node.getBoundingClientRect(),
- }))
- .sort((a, b) => a.rect.left - b.rect.left);
- if (
- !lanes.length ||
- pointer.x < lanes[0].rect.left ||
- pointer.x > lanes[lanes.length - 1].rect.right ||
- (!viewport &&
- (pointer.y < Math.min(...lanes.map((lane) => lane.rect.top)) ||
- pointer.y > Math.max(...lanes.map((lane) => lane.rect.bottom))))
- )
- return reject();
- const lane = lanes.reduce((closest, lane) =>
- Math.abs(pointer.x - (lane.rect.left + lane.rect.width / 2)) <
- Math.abs(pointer.x - (closest.rect.left + closest.rect.width / 2))
- ? lane
- : closest
- );
- const { kind, itemId: id, laneId: fromLane } = draggable.data;
- const toLane: unknown = lane.droppable.data.laneId;
- if (
- typeof id !== 'string' ||
- typeof fromLane !== 'string' ||
- typeof toLane !== 'string'
- )
- return reject();
- if (kind === 'lane') {
- if (fromLane === toLane) return reject();
- const edge =
- pointer.x < lane.rect.left + lane.rect.width / 2 ? 'before' : 'after';
- const boundary =
- edge === 'before'
- ? lane.rect.left - LANE_INSERTION_INSET
- : lane.rect.right + LANE_INSERTION_INSET;
- if (viewport && (boundary < viewport.left || boundary > viewport.right))
- return reject();
- const originalIndex = lanes.findIndex(
- (lane) => lane.droppable.data.laneId === fromLane
- );
- const remaining = lanes.filter(
- (lane) => lane.droppable.data.laneId !== fromLane
- );
- const insertionIndex =
- remaining.findIndex((lane) => lane.droppable.data.laneId === toLane) +
- (edge === 'after' ? 1 : 0);
- if (originalIndex < 0 || insertionIndex === originalIndex)
- return reject();
- setTarget({ kind, id, fromLane, toLane, edge });
- } else if (kind === 'card') {
- const cards = Array.from(
- lane.droppable.node.querySelectorAll<HTMLElement>('[data-kanban-card]')
- );
- const remaining = cards.filter((card) => card.dataset.kanbanCard !== id);
- const next = remaining.find((card) => {
- const bounds = card.getBoundingClientRect();
- return pointer.y < bounds.top + bounds.height / 2;
+ const resolve = () => {
+ const settled = intent.update(pointer);
+ const collision = findKanbanCollision(draggable, droppables, pointer, {
+ mode: props.mode ?? 'ordered',
+ viewport: props.getViewport?.()?.getBoundingClientRect(),
+ pointerPlacement: props.pointerPlacement,
});
- const insertion = next ? remaining.indexOf(next) : remaining.length;
- if (
- fromLane === toLane &&
- insertion === cards.findIndex((card) => card.dataset.kanbanCard === id)
- )
- return reject();
- const drop = {
- kind,
- id,
- fromLane,
- toLane,
- beforeId: next?.dataset.kanbanCard,
- };
- if (props.canDropCard && !props.canDropCard(drop)) return reject();
+
+ if (!collision) {
+ return rejectCollision();
+ }
+
+ const { drop, droppable } = collision;
+
+ if (drop.kind === 'card' && !canDropCard(drop)) {
+ return rejectCollision();
+ }
+
+ const active = target();
+ const sameColumn =
+ active?.id === drop.id && active.toLane === drop.toLane;
+
+ if (!settled && !sameColumn) {
+ return rejectCollision();
+ }
setTarget(drop);
- } else return reject();
- return lane.droppable;
+ return droppable;
+ };
+ reevaluate = resolve;
+
+ return resolve();
};
+
+ const handleDragEnd = () => {
+ const drop = target();
+ clearIntent();
+
+ try {
+ if (cancelled) {
+ return;
+ }
+
+ releaseClick();
+
+ if (!drop) {
+ return;
+ }
+
+ if (drop.kind === 'card' && !canDropCard(drop)) {
+ return;
+ }
+
+ if (props.mode !== 'cross-column') {
+ props.onDrop(drop);
+ return;
+ }
+
+ if (drop.kind !== 'card') {
+ return;
+ }
+
+ // Let the host capture the placeholder layout before removing it.
+ props.onDrop(
+ {
+ kind: 'card',
+ id: drop.id,
+ fromLane: drop.fromLane,
+ toLane: drop.toLane,
+ ...(props.pointerPlacement ? { beforeId: drop.beforeId } : {}),
+ },
+ dropVisual
+ );
+ } finally {
+ origin = undefined;
+ setTarget(undefined);
+ setPreview(undefined);
+ dropVisual = undefined;
+ }
+ };
+
+ onCleanup(() => document.removeEventListener('mouseup', releaseClick));
+
return (
<DragDropProvider
collisionDetector={collisionDetector}
onDragStart={({ draggable }) => {
suppressClick = true;
setPreview(cloneDragPreview(draggable.node, 'data-kanban-preview'));
+ dropVisual = undefined;
}}
- onDragEnd={() => {
- const drop = target();
- setTarget(undefined);
- setPreview(undefined);
- if (!cancelled) releaseClick();
- if (drop && !cancelled) props.onDrop(drop);
- }}
+ onDragEnd={handleDragEnd}
>
<DragSessionSensors
getViewport={() => props.getViewport?.()}
axis="both"
+ activationDistance={props.mode === 'cross-column' ? 10 : undefined}
+ nestedScroll={
+ props.mode === 'cross-column'
+ ? {
+ viewportSelector: '[data-kanban-scroll]',
+ horizontalOutside: true,
+ }
+ : undefined
+ }
onCancel={() => {
cancelled = true;
+ clearIntent();
setTarget(undefined);
document.addEventListener('mouseup', releaseClick, { once: true });
}}
@@ -180,9 +243,13 @@ export function Kanban(props: {
value={{
suppressClick: () => suppressClick,
target,
+ crossColumn: () => props.mode === 'cross-column',
start: (event) => {
origin = { x: event.clientX, y: event.clientY };
+ clearIntent();
+ intent.reset(origin);
cancelled = false;
+ dropVisual = undefined;
setTarget(undefined);
},
}}
@@ -199,20 +266,32 @@ export function Kanban(props: {
);
}
+/** Read the validated destination without coupling consumers to drag sensor state. */
+export function useKanbanDropTarget() {
+ const drag = useContext(DragContext);
+ return () => drag?.target();
+}
/** Place at the end of a relatively positioned card list; cards provide their own leading marker. */
export function KanbanCardInsertion(props: {
laneId: string;
beforeId?: string;
}) {
const drag = useContext(DragContext);
+
const active = () => {
+ if (drag?.crossColumn()) {
+ return false;
+ }
+
const target = drag?.target();
- return (
- target?.kind === 'card' &&
- target.toLane === props.laneId &&
- target.beforeId === props.beforeId
- );
+
+ if (target?.kind !== 'card' || target.toLane !== props.laneId) {
+ return false;
+ }
+
+ return target.beforeId === props.beforeId;
};
+
return (
<Show when={active()}>
<span
@@ -220,11 +299,10 @@ export function KanbanCardInsertion(props: {
data-kanban-insertion="card"
data-lane-id={props.laneId}
data-before-row-id={props.beforeId}
- class="pointer-events-none absolute -inset-x-2 z-10 h-0.5 rounded-full bg-accent"
- classList={{
- '-top-1.5': !!props.beforeId,
- '-bottom-1.5': !props.beforeId,
- }}
+ class={cn(
+ 'pointer-events-none absolute -inset-x-2 z-10 h-0.5 rounded-full bg-accent',
+ props.beforeId ? '-top-1.5' : '-bottom-1.5'
+ )}
>
<span class="absolute top-1/2 left-0 size-1 -translate-y-1/2 rounded-full bg-accent" />
<span class="absolute top-1/2 right-0 size-1 -translate-y-1/2 rounded-full bg-accent" />
@@ -236,23 +314,45 @@ export function KanbanCardInsertion(props: {
export function KanbanLane(props: {
id: string;
label: string;
+ 'aria-labelledby'?: string;
canReorder?: boolean;
+ class?: string;
onKeyDown?: JSX.EventHandlerUnion<HTMLElement, KeyboardEvent>;
+ onPointerEnter?: JSX.EventHandlerUnion<HTMLElement, PointerEvent>;
+ onPointerLeave?: JSX.EventHandlerUnion<HTMLElement, PointerEvent>;
children: JSX.Element;
}) {
const drag = useContext(DragContext);
+
const edge = () => {
const target = drag?.target();
- return target?.kind === 'lane' && target.toLane === props.id
- ? target.edge
- : undefined;
+
+ if (target?.kind !== 'lane' || target.toLane !== props.id) {
+ return undefined;
+ }
+
+ return target.edge;
};
+
+ const highlighted = () => {
+ if (!drag?.crossColumn()) {
+ return false;
+ }
+
+ const target = drag.target();
+
+ return target?.kind === 'card' && target.toLane === props.id;
+ };
+
+ const canReorder = () => props.canReorder && !drag?.crossColumn();
+
const draggable = createDraggable(`lane:${props.id}`, {
kind: 'lane',
itemId: props.id,
laneId: props.id,
});
const droppable = createDroppable(`lane:${props.id}`, { laneId: props.id });
+
return (
<HandleContext.Provider
value={{
@@ -260,7 +360,7 @@ export function KanbanLane(props: {
return draggable.dragActivators;
},
get disabled() {
- return !props.canReorder;
+ return !canReorder();
},
}}
>
@@ -269,18 +369,26 @@ export function KanbanLane(props: {
draggable.ref(node);
droppable.ref(node);
}}
- class="relative flex w-72 shrink-0 flex-col rounded-xl border border-transparent bg-surface-1 p-2 transition-colors"
- classList={{
- 'opacity-35': draggable.isActiveDraggable,
- }}
+ class={cn(
+ 'relative flex w-72 shrink-0 flex-col rounded-xl border border-transparent bg-surface-1 p-2 transition-colors',
+ draggable.isActiveDraggable && 'opacity-35',
+ highlighted() && 'ring-2 ring-accent',
+ props.class
+ )}
+ data-kanban-drop-target={highlighted() ? 'column' : undefined}
aria-label={props.label}
+ aria-labelledby={props['aria-labelledby']}
data-kanban-lane={props.id}
onKeyDown={props.onKeyDown}
+ onPointerEnter={props.onPointerEnter}
+ onPointerLeave={props.onPointerLeave}
onMouseDown={(event) => {
- if (props.canReorder && event.target === event.currentTarget) {
- drag?.start(event);
- draggable.dragActivators.onmousedown?.(event);
+ if (!canReorder() || event.target !== event.currentTarget) {
+ return;
}
+
+ drag?.start(event);
+ draggable.dragActivators.onmousedown?.(event);
}}
>
<Show when={edge()}>
@@ -308,6 +416,7 @@ export function KanbanCard(props: {
laneId: string;
canDrag: boolean;
pending?: boolean;
+ onClick?: JSX.EventHandler<HTMLElement, MouseEvent>;
children: JSX.Element;
}) {
const drag = useContext(DragContext);
@@ -316,6 +425,7 @@ export function KanbanCard(props: {
itemId: props.id,
laneId: props.laneId,
});
+
return (
<HandleContext.Provider
value={{
@@ -329,26 +439,47 @@ export function KanbanCard(props: {
>
<article
ref={draggable.ref}
- class="group relative rounded-lg border border-edge-muted bg-surface-3 shadow-sm transition-shadow hover:border-edge hover:shadow-md"
- classList={{
- 'opacity-35': draggable.isActiveDraggable,
- 'ring-1 ring-ink/20': !!props.pending,
- }}
+ class={cn(
+ 'group relative rounded-lg border border-edge-muted bg-surface-3 shadow-sm transition-shadow hover:border-edge hover:shadow-md',
+ draggable.isActiveDraggable && 'opacity-35',
+ props.pending && 'ring-1 ring-ink/20'
+ )}
onMouseDown={(event) => {
- if (props.canDrag && !event.target.closest('[data-kanban-no-drag]')) {
- drag?.start(event);
- draggable.dragActivators.onmousedown?.(event);
+ if (!event.currentTarget.contains(event.target)) {
+ return;
+ }
+
+ if (!props.canDrag || event.target.closest('[data-kanban-no-drag]')) {
+ return;
}
+
+ drag?.start(event);
+ draggable.dragActivators.onmousedown?.(event);
}}
onDragStart={(event) => {
- if (props.canDrag) event.preventDefault();
+ if (props.canDrag) {
+ event.preventDefault();
+ }
+ }}
+ onClick={(event) => {
+ if (!event.currentTarget.contains(event.target)) {
+ return;
+ }
+
+ if (drag?.suppressClick()) {
+ return;
+ }
+
+ props.onClick?.(event);
}}
on:click={{
handleEvent(event: MouseEvent) {
- if (drag?.suppressClick()) {
- event.preventDefault();
- event.stopPropagation();
+ if (!drag?.suppressClick()) {
+ return;
}
+
+ event.preventDefault();
+ event.stopPropagation();
},
capture: true,
}}
@@ -372,17 +503,22 @@ export function KanbanHandle(props: {
}) {
const drag = useContext(HandleContext);
const board = useContext(DragContext);
- if (!drag)
+
+ if (!drag) {
throw new Error('KanbanHandle requires a KanbanLane or KanbanCard');
+ }
+
return (
<div
class={props.class}
onMouseDown={(event) => {
- if (!drag.disabled && !event.target.closest('[data-kanban-no-drag]')) {
- event.stopPropagation();
- board?.start(event);
- drag.activators.onmousedown?.(event);
+ if (drag.disabled || event.target.closest('[data-kanban-no-drag]')) {
+ return;
}
+
+ event.stopPropagation();
+ board?.start(event);
+ drag.activators.onmousedown?.(event);
}}
aria-label={props.label}
onKeyDown={props.onKeyDown}
diff --git a/apps/web/src/components/ui/components/Scroll.tsx b/apps/web/src/components/ui/components/Scroll.tsx
index 8e0b55e968..ed01ae1730 100644
--- a/apps/web/src/components/ui/components/Scroll.tsx
+++ b/apps/web/src/components/ui/components/Scroll.tsx
@@ -1,157 +1,429 @@
-import type { JSX } from 'solid-js';
-import { createSignal, onCleanup, onMount, splitProps } from 'solid-js';
+import {
+ createEffect,
+ createSignal,
+ For,
+ type JSX,
+ onCleanup,
+ onMount,
+ Show,
+ splitProps,
+} from 'solid-js';
-const THUMB_WIDTH = 2;
-const HIDE_DELAY = 500;
-const GUTTER_WIDTH = 8;
-const MIN_THUMB_HEIGHT = 24;
-const THUMB_INSET = (GUTTER_WIDTH - THUMB_WIDTH) * 0.5;
+const GUTTER = 10;
+const THUMB = 4;
+const INSET = (GUTTER - THUMB) / 2;
+const MIN_THUMB = 24;
+type Axis = 'horizontal' | 'vertical';
+type Metrics = {
+ overflow: number;
+ size: number;
+ travel: number;
+ offset: number;
+};
+const emptyMetrics = (): Metrics => ({
+ overflow: 0,
+ size: 0,
+ travel: 0,
+ offset: 0,
+});
type ScrollProps = JSX.HTMLAttributes<HTMLDivElement> & {
scrollRef?: (element: HTMLDivElement) => void;
+ /** Controls scrolling, independently of scrollbar visibility. */
+ orientation?: Axis | 'both';
+ /** Which custom scrollbars to show when their content overflows. */
+ scrollbars?: Axis | 'both' | 'none';
+ autoHide?: boolean;
+ autoHideDelay?: number;
+ /** Opt in to hover-only reveal instead of revealing on scrolling and mount. */
+ revealOn?: 'scroll' | 'hover';
+ /** Include an enclosing surface, such as a lane header, in the hover area. */
+ hovered?: boolean;
+ /** Disable for content-height flex layouts, such as Kanban lanes. */
+ fill?: boolean;
+ viewportProps?: Omit<
+ JSX.HTMLAttributes<HTMLDivElement>,
+ 'ref' | 'children'
+ > & {
+ [key: `data-${string}`]: string | undefined;
+ };
+ contentProps?: Omit<JSX.HTMLAttributes<HTMLDivElement>, 'ref' | 'children'>;
};
+function styles(
+ base: JSX.CSSProperties,
+ overrides: JSX.CSSProperties | string | undefined
+) {
+ if (typeof overrides === 'string') {
+ return (
+ Object.entries(base)
+ .map(([key, value]) => `${key}:${value ?? ''}`)
+ .join(';') +
+ ';' +
+ overrides
+ );
+ }
+
+ return { ...base, ...overrides };
+}
+
+/** Defaults retain the original vertical, auto-hiding scrollbar and full-height layout. */
export function Scroll(props: ScrollProps) {
- const [local, rest] = splitProps(props, ['children', 'scrollRef']);
- const [translateY, setTranslateY] = createSignal(THUMB_INSET);
- const [thumbHeight, setThumbHeight] = createSignal(MIN_THUMB_HEIGHT);
+ const [local, rest] = splitProps(props, [
+ 'children',
+ 'scrollRef',
+ 'orientation',
+ 'scrollbars',
+ 'autoHide',
+ 'autoHideDelay',
+ 'revealOn',
+ 'hovered',
+ 'fill',
+ 'viewportProps',
+ 'contentProps',
+ 'style',
+ ]);
+ const [metrics, setMetrics] = createSignal<Record<Axis, Metrics>>({
+ horizontal: emptyMetrics(),
+ vertical: emptyMetrics(),
+ });
const [visible, setVisible] = createSignal(false);
+ const [rootHovered, setRootHovered] = createSignal(false);
+ const [trackHovered, setTrackHovered] = createSignal(false);
+ const isHovered = () =>
+ rootHovered() || trackHovered() || local.hovered === true;
+ let viewport!: HTMLDivElement;
+ let content!: HTMLDivElement;
+ let timer: ReturnType<typeof setTimeout> | undefined;
- let hideTimer: ReturnType<typeof setTimeout> | undefined;
- let contentRef!: HTMLDivElement;
- let gutterRef!: HTMLDivElement;
- let scrollRef!: HTMLDivElement;
- let maxScroll = 0;
- let maxTop = 0;
-
- function update() {
- setTranslateY(
- THUMB_INSET +
- (maxScroll > 0 ? (scrollRef.scrollTop / maxScroll) * maxTop : 0)
- );
+ const enabled = (axis: Axis) =>
+ !local.orientation ||
+ local.orientation === 'both' ||
+ local.orientation === axis;
+ const shown = (axis: Axis) => {
+ const visibility = local.scrollbars ?? 'vertical';
+ return enabled(axis) && (visibility === 'both' || visibility === axis);
+ };
+
+ function configure() {
+ if (!viewport) {
+ return;
+ }
+
+ const x = Math.max(0, viewport.scrollWidth - viewport.clientWidth);
+ const y = Math.max(0, viewport.scrollHeight - viewport.clientHeight);
+ const measure = (axis: Axis): Metrics => {
+ const horizontal = axis === 'horizontal';
+ const other = horizontal ? 'vertical' : 'horizontal';
+ const length = horizontal ? viewport.clientWidth : viewport.clientHeight;
+ const total = horizontal ? viewport.scrollWidth : viewport.scrollHeight;
+ 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 size = Math.min(
+ track,
+ Math.max(MIN_THUMB, total ? (track * length) / total : track)
+ );
+ const travel = Math.max(0, track - size);
+ const scroll = horizontal ? viewport.scrollLeft : viewport.scrollTop;
+ return {
+ overflow,
+ size,
+ travel,
+ offset: overflow ? (Math.max(0, scroll) / overflow) * travel : 0,
+ };
+ };
+ setMetrics({
+ horizontal: measure('horizontal'),
+ vertical: measure('vertical'),
+ });
}
function reveal() {
- if (scrollRef.scrollHeight <= scrollRef.clientHeight) {
+ if (local.revealOn === 'hover' && !isHovered()) {
return;
}
+ clearTimeout(timer);
setVisible(true);
- clearTimeout(hideTimer);
- hideTimer = setTimeout(() => setVisible(false), HIDE_DELAY);
- }
- function config() {
- const ch = scrollRef.clientHeight;
- const sh = scrollRef.scrollHeight;
- const trackHeight = Math.max(0, ch - THUMB_INSET * 2);
- const ratio = sh > 0 ? ch / sh : 1;
- const th = Math.max(
- MIN_THUMB_HEIGHT,
- Math.min(trackHeight, trackHeight * ratio)
- );
- setThumbHeight(th);
- maxScroll = Math.max(0, sh - ch);
- maxTop = Math.max(0, trackHeight - th);
- update();
+ if (
+ local.autoHide !== false &&
+ !(local.revealOn === 'hover' && isHovered())
+ ) {
+ timer = setTimeout(
+ () => setVisible(false),
+ Math.max(0, local.autoHideDelay ?? 500)
+ );
+ }
}
function handleScroll() {
- update();
+ configure();
reveal();
}
- function seek(localY: number) {
- if (maxScroll <= 0 || maxTop <= 0) {
- return;
- }
- scrollRef.scrollTop =
- (Math.max(0, Math.min(maxTop, localY - thumbHeight() / 2 - THUMB_INSET)) /
- maxTop) *
- maxScroll;
+ onMount(() => {
+ const root = viewport.parentElement;
+ const enter = () => setRootHovered(true);
+ const leave = () => setRootHovered(false);
+ root?.addEventListener('pointerenter', enter);
+ root?.addEventListener('pointerleave', leave);
+ const observer = new ResizeObserver(configure);
+ observer.observe(viewport);
+ observer.observe(content);
+ viewport.addEventListener('scroll', handleScroll);
+ configure();
+
+ onCleanup(() => {
+ root?.removeEventListener('pointerenter', enter);
+ root?.removeEventListener('pointerleave', leave);
+ observer.disconnect();
+ viewport.removeEventListener('scroll', handleScroll);
+ clearTimeout(timer);
+ });
+ });
+
+ createEffect(() => {
+ local.orientation;
+ local.scrollbars;
+ local.autoHide;
+ local.autoHideDelay;
+ configure();
reveal();
- }
+ });
- function handlePointerDown(e: PointerEvent) {
- if (e.button !== 0) {
+ createEffect(() => {
+ if (local.revealOn !== 'hover') {
return;
}
- e.preventDefault();
- gutterRef.setPointerCapture(e.pointerId);
- seek(e.offsetY);
- }
- function handlePointerMove(e: PointerEvent) {
- if (!gutterRef.hasPointerCapture(e.pointerId)) {
+ clearTimeout(timer);
+
+ if (isHovered()) {
+ setVisible(true);
return;
}
- seek(e.offsetY);
- }
- onMount(() => {
- const ro = new ResizeObserver(config);
- ro.observe(scrollRef);
- ro.observe(contentRef);
-
- onCleanup(() => {
- ro.disconnect();
- clearTimeout(hideTimer);
- });
+ timer = setTimeout(
+ () => setVisible(false),
+ Math.max(0, local.autoHideDelay ?? 500)
+ );
});
return (
<div
{...rest}
- style={{
- position: 'relative',
- 'min-height': '0',
- 'min-width': '0',
- height: '100%',
- width: '100%',
- }}
+ style={styles(
+ {
+ position: 'relative',
+ display: 'flex',
+ 'flex-direction': 'column',
+ 'min-height': '0',
+ 'min-width': '0',
+ height: local.fill === false ? undefined : '100%',
+ width: '100%',
+ },
+ local.style
+ )}
>
<div
+ {...local.viewportProps}
ref={(element) => {
- scrollRef = element;
+ viewport = element;
local.scrollRef?.(element);
}}
- onScroll={handleScroll}
- style={{
- 'scrollbar-width': 'none',
- 'overflow-y': 'auto',
- height: '100%',
- }}
+ style={styles(
+ {
+ 'scrollbar-width': 'none',
+ 'min-height': '0',
+ 'min-width': '0',
+ flex: '1 1 auto',
+ 'overflow-x': enabled('horizontal') ? 'auto' : 'hidden',
+ 'overflow-y': enabled('vertical') ? 'auto' : 'hidden',
+ height: local.fill === false ? undefined : '100%',
+ },
+ local.viewportProps?.style
+ )}
>
- <div ref={contentRef}>{local.children}</div>
+ <div {...local.contentProps} ref={content}>
+ {local.children}
+ </div>
</div>
- <div
- ref={gutterRef}
- onPointerDown={handlePointerDown}
- onPointerMove={handlePointerMove}
- aria-hidden="true"
- style={{
- width: `${GUTTER_WIDTH}px`,
- 'touch-action': 'none',
- position: 'absolute',
- height: '100%',
- right: '0',
- top: '0',
+ <For each={['horizontal', 'vertical'] as const}>
+ {(axis) => {
+ const horizontal = axis === 'horizontal';
+ let gutter!: HTMLDivElement;
+ let grab = 0;
+ const [dragging, setDragging] = createSignal(false);
+ const [focused, setFocused] = createSignal(false);
+ const current = () => metrics()[axis];
+ const other = () => metrics()[horizontal ? 'vertical' : 'horizontal'];
+ const corner = () =>
+ shown(horizontal ? 'vertical' : 'horizontal') &&
+ other().overflow > 0
+ ? GUTTER
+ : 0;
+ const coordinate = (event: PointerEvent) => {
+ const bounds = gutter.getBoundingClientRect();
+ return horizontal
+ ? event.clientX - bounds.left
+ : event.clientY - bounds.top;
+ };
+ const seek = (position: number) => {
+ const value = current();
+ if (!value.travel) {
+ return;
+ }
+ const scroll =
+ (Math.max(0, Math.min(value.travel, position - grab - INSET)) /
+ value.travel) *
+ value.overflow;
+ if (horizontal) {
+ viewport.scrollLeft = scroll;
+ } else {
+ viewport.scrollTop = scroll;
+ }
+ handleScroll();
+ };
+
+ return (
+ <Show when={shown(axis) && current().overflow > 0}>
+ <div
+ ref={gutter}
+ role="scrollbar"
+ aria-label={
+ horizontal ? 'Scroll horizontally' : 'Scroll vertically'
+ }
+ aria-orientation={axis}
+ aria-valuemin={0}
+ aria-valuemax={current().overflow}
+ aria-valuenow={
+ current().travel
+ ? Math.round(
+ (current().offset / current().travel) *
+ current().overflow
+ )
+ : 0
+ }
+ tabindex={0}
+ data-scrollbar={axis}
+ onFocus={() => {
+ setFocused(true);
+ reveal();
+ }}
+ onBlur={() => {
+ setFocused(false);
+ reveal();
+ }}
+ onPointerEnter={() => {
+ setTrackHovered(true);
+ reveal();
+ }}
+ onPointerLeave={() => setTrackHovered(false)}
+ onPointerDown={(event) => {
+ if (event.button !== 0) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ gutter.setPointerCapture(event.pointerId);
+ setDragging(true);
+ const point = coordinate(event);
+ const start = current().offset + INSET;
+ grab =
+ point >= start && point <= start + current().size
+ ? point - start
+ : current().size / 2;
+ seek(point);
+ }}
+ onLostPointerCapture={() => {
+ setDragging(false);
+ reveal();
+ }}
+ onPointerMove={(event) => {
+ if (gutter.hasPointerCapture(event.pointerId)) {
+ seek(coordinate(event));
+ }
+ }}
+ onPointerUp={(event) => {
+ if (gutter.hasPointerCapture(event.pointerId)) {
+ gutter.releasePointerCapture(event.pointerId);
+ }
+ reveal();
+ }}
+ onKeyDown={(event) => {
+ const negative = horizontal ? 'ArrowLeft' : 'ArrowUp';
+ const positive = horizontal ? 'ArrowRight' : 'ArrowDown';
+ const position = horizontal
+ ? viewport.scrollLeft
+ : viewport.scrollTop;
+ let next: number;
+
+ if (event.key === negative) {
+ next = position - 40;
+ } else if (event.key === positive) {
+ next = position + 40;
+ } else if (event.key === 'Home') {
+ next = 0;
+ } else if (event.key === 'End') {
+ next = current().overflow;
+ } else {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ const bounded = Math.max(
+ 0,
+ Math.min(current().overflow, next)
+ );
+
+ if (horizontal) {
+ viewport.scrollLeft = bounded;
+ } else {
+ viewport.scrollTop = bounded;
+ }
+ handleScroll();
+ }}
+ style={{
+ position: 'absolute',
+ right: horizontal ? `${corner()}px` : '0',
+ bottom: horizontal ? '0' : `${corner()}px`,
+ left: horizontal ? '0' : undefined,
+ top: horizontal ? undefined : '0',
+ width: horizontal ? undefined : `${GUTTER}px`,
+ height: horizontal ? `${GUTTER}px` : undefined,
+ 'touch-action': 'none',
+ 'z-index': 1,
+ }}
+ >
+ <div
+ style={{
+ position: 'absolute',
+ 'pointer-events': 'none',
+ left: horizontal ? '0' : `${INSET}px`,
+ top: horizontal ? `${INSET}px` : '0',
+ width: `${horizontal ? current().size : THUMB}px`,
+ height: `${horizontal ? THUMB : current().size}px`,
+ transform: `translate${horizontal ? 'X' : 'Y'}(${current().offset + INSET}px)`,
+ 'border-radius': `${THUMB / 2}px`,
+ 'background-color': 'var(--color-content-4)',
+ opacity:
+ local.autoHide === false ||
+ visible() ||
+ dragging() ||
+ focused()
+ ? 1
+ : 0,
+ transition: 'opacity 150ms ease-in-out',
+ }}
+ />
+ </div>
+ </Show>
+ );
}}
- >
- <div
- style={{
- transform: `translateY(${translateY()}px)`,
- transition: 'opacity 150ms ease-in-out',
- 'border-radius': `${THUMB_WIDTH * 0.5}px`,
- 'background-color': 'var(--color-content-4)',
- height: `${thumbHeight()}px`,
- opacity: visible() ? 1 : 0,
- right: `${THUMB_INSET}px`,
- width: `${THUMB_WIDTH}px`,
- 'pointer-events': 'none',
- position: 'absolute',
- }}
- />
- </div>
+ </For>
</div>
);
}
diff --git a/apps/web/src/components/view-shell/ListDropdowns.tsx b/apps/web/src/components/view-shell/ListDropdowns.tsx
index dc18e104b2..c9a6bda34d 100644
--- a/apps/web/src/components/view-shell/ListDropdowns.tsx
+++ b/apps/web/src/components/view-shell/ListDropdowns.tsx
@@ -4,6 +4,8 @@ import {
} from '@app/features/next-soup/soup-view/filters-bar/filter-menu';
import CheckIcon from '@phosphor/check.svg';
import FilterIcon from '@phosphor/funnel-simple.svg';
+import BoardIcon from '@phosphor/kanban.svg';
+import ListIcon from '@phosphor/list-bullets.svg';
import SortIcon from '@phosphor/sort-ascending.svg';
import GroupIcon from '@phosphor/stack.svg';
import { cn, Dropdown } from '@ui';
@@ -91,6 +93,35 @@ function SingleSelectDropdown<TId extends string>(
);
}
+export type ViewLayout = 'list' | 'board';
+
+export type ViewLayoutDropdownProps = Omit<
+ SingleSelectDropdownProps<ViewLayout>,
+ 'icon' | 'label' | 'options'
+> & {
+ label?: string;
+};
+
+const VIEW_LAYOUT_OPTIONS: ListControlOption<ViewLayout>[] = [
+ { id: 'list', label: 'List', icon: () => <ListIcon /> },
+ { id: 'board', label: 'Board', icon: () => <BoardIcon /> },
+];
+
+export function ViewLayoutDropdown(props: ViewLayoutDropdownProps) {
+ return (
+ <SingleSelectDropdown
+ {...props}
+ label={props.label ?? 'Layout'}
+ options={VIEW_LAYOUT_OPTIONS}
+ icon={
+ <Show when={props.value === 'board'} fallback={<ListIcon />}>
+ <BoardIcon />
+ </Show>
+ }
+ />
+ );
+}
+
export type ListSortDropdownProps<TId extends string> = Omit<
SingleSelectDropdownProps<TId>,
'icon' | 'label'
diff --git a/apps/web/src/components/view-shell/index.ts b/apps/web/src/components/view-shell/index.ts
index 121f8e955a..a98c8bb59a 100644
--- a/apps/web/src/components/view-shell/index.ts
+++ b/apps/web/src/components/view-shell/index.ts
@@ -16,6 +16,9 @@ export {
type ListGroupDropdownProps,
ListSortDropdown,
type ListSortDropdownProps,
+ type ViewLayout,
+ ViewLayoutDropdown,
+ type ViewLayoutDropdownProps,
} from './ListDropdowns';
export { MobileFilterDrawer } from './MobileFilterDrawer';
export { SearchBar, type SearchBarProps } from './SearchBar';
diff --git a/apps/web/src/features/entity/utils/task-properties.ts b/apps/web/src/features/entity/utils/task-properties.ts
index 4383e0ac35..7cd76d7e4e 100644
--- a/apps/web/src/features/entity/utils/task-properties.ts
+++ b/apps/web/src/features/entity/utils/task-properties.ts
@@ -9,7 +9,7 @@ export const TASK_STATUS_OPTIONS = [
{ value: PROPERTY_OPTION_IDS.STATUS.CANCELED, label: 'Canceled' },
] as const;
-const TASK_PRIORITY_OPTIONS = [
+export const TASK_PRIORITY_OPTIONS = [
{ value: PROPERTY_OPTION_IDS.PRIORITY.URGENT, label: 'Urgent' },
{ value: PROPERTY_OPTION_IDS.PRIORITY.HIGH, label: 'High' },
{ value: PROPERTY_OPTION_IDS.PRIORITY.MEDIUM, label: 'Medium' },
diff --git a/apps/web/src/features/projects/queries/project-tasks.test.ts b/apps/web/src/features/projects/queries/project-tasks.test.ts
index 1397cda569..4d4b240e7f 100644
--- a/apps/web/src/features/projects/queries/project-tasks.test.ts
+++ b/apps/web/src/features/projects/queries/project-tasks.test.ts
@@ -40,6 +40,7 @@ it('scopes tasks to the Project property and disables the shared source immediat
updatedAt: '',
});
const refresh = vi.fn(async () => {});
+ const [board, setBoard] = createSignal(false);
const source = createProjectTasksDataSource(
'project',
{
@@ -61,6 +62,7 @@ it('scopes tasks to the Project property and disables the shared source immediat
tagSets: () => [],
tagSetsReady: () => true,
isGroupExpanded: () => true,
+ board,
}
);
expect(mock.options?.reference?.()).toEqual({
@@ -69,6 +71,13 @@ it('scopes tasks to the Project property and disables the shared source immediat
});
expect(mock.options?.enabled?.()).toBe(true);
expect(mock.options?.loadAll).toBe(true);
+ expect(mock.options?.board?.()).toBe(false);
+ setBoard(true);
+ expect(mock.options?.board?.()).toBe(true);
+ expect(mock.options?.reference?.()).toEqual({
+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.PROJECT,
+ entityId: 'project',
+ });
setProject(undefined);
expect(mock.options?.enabled?.()).toBe(false);
source
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 ae5ea269ce..4cd8345d71 100644
--- a/apps/web/src/features/projects/views/project-tasks-list.tsx
+++ b/apps/web/src/features/projects/views/project-tasks-list.tsx
@@ -1,5 +1,5 @@
import { TasksControls } from '@app/features/tasks-view/components/TasksControls';
-import { TaskList } from '@app/features/tasks-view/components/task-list/TaskList';
+import { TasksContent } from '@app/features/tasks-view/tasks-content';
import {
TasksViewProvider,
type TasksViewProviderProps,
@@ -26,7 +26,7 @@ export type ProjectTasksListProps = Omit<
addTasksAction?: JSX.Element;
};
-/** Embeds the actual Tasks list, including its controllers, menus and row editors. */
+/** Embeds Tasks layouts with project-scoped data, controllers, menus and editors. */
export function ProjectTasksProvider(props: ProjectTasksProviderProps) {
const context = useProjectsContext();
return (
@@ -36,6 +36,7 @@ export function ProjectTasksProvider(props: ProjectTasksProviderProps) {
initialState={{ tab: 'team-tasks', groupBy: 'status', facets: {} }}
restoreEntryState
scopeKey={`initiative:${projectId}:tasks`}
+ searchNamespace="projectTasks"
onOpenTask={props.onOpenTask}
onCloseTask={() => {}}
sourceFactory={(state, options) =>
@@ -97,7 +98,7 @@ function ProjectTasksListBody(props: ProjectTasksListProps) {
</Button>
</div>
</Show>
- <TaskList />
+ <TasksContent />
</div>
);
}
diff --git a/apps/web/src/features/tasks-view/components/TasksControls.tsx b/apps/web/src/features/tasks-view/components/TasksControls.tsx
index 5df5452996..475993c592 100644
--- a/apps/web/src/features/tasks-view/components/TasksControls.tsx
+++ b/apps/web/src/features/tasks-view/components/TasksControls.tsx
@@ -3,16 +3,18 @@ import {
ListGroupDropdown,
ListSortDropdown,
useViewControlHotkeys,
+ ViewLayoutDropdown,
} from '@app/components/view-shell';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { createSignal, Show } from 'solid-js';
import { TASK_GROUP_OPTIONS, TASK_SORT_OPTIONS } from '../constants';
+import { TASK_BOARD_GROUP_OPTIONS } from '../core/task-board';
import { useTaskFilters } from '../filters/use-task-filters';
import { useTasksView } from '../tasks-view-context';
export function TasksControls() {
const panel = useSplitPanelOrThrow();
- const { state, setPrimarySort, setState } = useTasksView();
+ const { state, setPrimarySort, setState, projectsEnabled } = useTasksView();
const filters = useTaskFilters();
const [openMenu, setOpenMenu] = createSignal<'filters' | 'sort'>();
let filterTrigger: HTMLButtonElement | undefined;
@@ -50,22 +52,50 @@ export function TasksControls() {
});
const primarySort = () => state.sort[0]?.id ?? 'updated_at';
+ const isBoardSearch = () => state.layout === 'board' && !!state.search.trim();
+
+ const groupOptions = () => {
+ if (state.layout !== 'board') {
+ return TASK_GROUP_OPTIONS;
+ }
+
+ return TASK_BOARD_GROUP_OPTIONS.filter((option) => {
+ return option.id !== 'project' || projectsEnabled();
+ });
+ };
return (
- <div class="flex min-w-0 shrink-0 items-center justify-end gap-2 @max-[720px]/view-shell:gap-1">
- <ListSortDropdown
- label="Sort tasks"
- value={primarySort()}
- options={TASK_SORT_OPTIONS}
- open={openMenu() === 'sort'}
- onChange={setPrimarySort}
- onOpenChange={handleMenuOpenChange('sort')}
- triggerRef={(element) => (sortTrigger = element)}
+ <div class="flex min-w-0 shrink-0 flex-wrap items-center justify-end gap-2 @max-[720px]/view-shell:gap-1">
+ <ViewLayoutDropdown
+ label="Task layout"
+ value={state.layout}
+ onChange={(layout) => setState('layout', layout)}
/>
+ <Show
+ when={!isBoardSearch()}
+ fallback={
+ <span
+ class="text-xs text-ink-muted"
+ title="Search results are ranked by relevance. Clear search to sort the board."
+ >
+ Relevance
+ </span>
+ }
+ >
+ <ListSortDropdown
+ label="Sort tasks"
+ value={primarySort()}
+ options={TASK_SORT_OPTIONS}
+ open={openMenu() === 'sort'}
+ onChange={setPrimarySort}
+ onOpenChange={handleMenuOpenChange('sort')}
+ triggerRef={(element) => (sortTrigger = element)}
+ />
+ </Show>
<ListGroupDropdown
- label="Group tasks"
+ label="Group by"
value={state.groupBy}
- options={TASK_GROUP_OPTIONS}
+ options={groupOptions()}
onChange={(groupBy) => setState('groupBy', groupBy)}
/>
<div class="relative shrink-0">
diff --git a/apps/web/src/features/tasks-view/components/TasksHeader.tsx b/apps/web/src/features/tasks-view/components/TasksHeader.tsx
index 987fd38ccf..3db75379d4 100644
--- a/apps/web/src/features/tasks-view/components/TasksHeader.tsx
+++ b/apps/web/src/features/tasks-view/components/TasksHeader.tsx
@@ -114,6 +114,7 @@ export function TasksHeader(props: TasksHeaderProps) {
}
>
<TasksMobileTabs />
+ <TasksControls />
</Show>
</div>
);
diff --git a/apps/web/src/features/tasks-view/components/task-board-composition.test.ts b/apps/web/src/features/tasks-view/components/task-board-composition.test.ts
new file mode 100644
index 0000000000..0ae2dad44f
--- /dev/null
+++ b/apps/web/src/features/tasks-view/components/task-board-composition.test.ts
@@ -0,0 +1,251 @@
+import type {
+ Kanban,
+ KanbanCrossColumnDrop,
+} from '@app/components/kanban/kanban';
+import { cleanup, render } from '@solidjs/testing-library';
+import {
+ type Accessor,
+ type ComponentProps,
+ createComponent,
+ createEffect,
+ createSignal,
+ type JSX,
+ onCleanup,
+} from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { TaskBoardColumn, TaskBoardTask } from '../core/task-board';
+import { TaskBoard } from './task-board';
+
+const drag = vi.hoisted(() => ({
+ drop: undefined as ((drop: KanbanCrossColumnDrop) => void) | undefined,
+}));
+const scrolled = vi.hoisted(() => vi.fn());
+const visibility = vi.hoisted(() => ({ end: (): boolean => true }));
+
+vi.mock('@app/components/kanban/kanban', async (importOriginal) => {
+ const original =
+ await importOriginal<typeof import('@app/components/kanban/kanban')>();
+
+ return {
+ ...original,
+ Kanban: (props: ComponentProps<typeof Kanban>) => {
+ if (props.mode === 'cross-column') drag.drop = props.onDrop;
+ return original.Kanban(props);
+ },
+ };
+});
+
+vi.mock('@app/components/kanban/kanban-virtualizer', () => ({
+ createKanbanVirtualizer: (options: {
+ direction: string;
+ keys: Accessor<readonly (string | number)[]>;
+ }) => ({
+ getVirtualItems: () =>
+ options
+ .keys()
+ .map((key, index) => ({
+ key,
+ index,
+ start: index * 100,
+ size: 100,
+ }))
+ .filter((item) => item.key !== -1 || visibility.end()),
+ getTotalSize: () => options.keys().length * 100,
+ scrollToIndex: (index: number, scrollOptions: { align?: string }) =>
+ scrolled(options.direction, index, scrollOptions),
+ measureElement: vi.fn(),
+ takeSnapshot: () => [],
+ }),
+}));
+
+beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe = vi.fn();
+ unobserve = vi.fn();
+ disconnect = vi.fn();
+ }
+ );
+});
+afterEach(() => {
+ cleanup();
+ drag.drop = undefined;
+ vi.clearAllMocks();
+ visibility.end = () => true;
+ vi.unstubAllGlobals();
+});
+
+const task: TaskBoardTask = {
+ id: 'task',
+ name: 'Original',
+ statusId: 'todo',
+ assigneeIds: [],
+ projectIds: [],
+};
+
+function column(id: string, tasks: readonly TaskBoardTask[]): TaskBoardColumn {
+ return { id, label: id, tasks, hasMore: true, loadingMore: false };
+}
+
+function mountBoard(options: {
+ columns: Accessor<readonly TaskBoardColumn[]>;
+ hidden: Accessor<boolean>;
+ endColumn?: () => JSX.Element;
+ move(): Promise<boolean>;
+}) {
+ const card = (current: Accessor<TaskBoardTask>) => {
+ const content = document.createElement('span');
+ createEffect(() => {
+ content.textContent = current().name;
+ });
+
+ return createComponent(TaskBoard.Card, {
+ get task() {
+ return current();
+ },
+ canDrag: true,
+ pending: false,
+ onOpen: vi.fn(),
+ children: content,
+ });
+ };
+ const cards = (current: Accessor<TaskBoardColumn>) =>
+ createComponent(TaskBoard.Cards, {
+ children: card,
+ get footer() {
+ const footer = document.createElement('button');
+ footer.textContent = `${current().id} paging`;
+ return footer;
+ },
+ });
+
+ return render(() =>
+ createComponent(TaskBoard.Root, {
+ get columns() {
+ return options.columns();
+ },
+ animationScope: 'scope',
+ canMove: () => true,
+ onMove: options.move,
+ get children() {
+ return createComponent(TaskBoard.Columns, {
+ get endColumn() {
+ if (!options.hidden()) return undefined;
+ return (
+ options.endColumn ??
+ (() => {
+ const end = document.createElement('section');
+ end.textContent = 'Hidden';
+ return end;
+ })
+ );
+ },
+ children: (current) =>
+ createComponent(TaskBoard.Column, {
+ get children() {
+ const heading = document.createElement('h2');
+ createEffect(() => {
+ heading.textContent = current().label;
+ });
+ return [
+ createComponent(TaskBoard.Header, { children: heading }),
+ cards(current),
+ ];
+ },
+ }),
+ });
+ },
+ })
+ );
+}
+
+it('preserves reactive card content and column ownership across regrouping and final-column changes', async () => {
+ const [columns, setColumns] = createSignal([column('todo', [task])]);
+ const [hidden, setHidden] = createSignal(false);
+ const view = mountBoard({ columns, hidden, move: async () => true });
+ const original = view.container.querySelector('[data-kanban-card]');
+
+ setColumns([column('todo', [{ ...task, name: 'Updated' }])]);
+ expect(view.container.querySelector('[data-kanban-card]')).toBe(original);
+ expect(original?.textContent).toBe('Updated');
+
+ setHidden(true);
+ expect(view.getByText('Hidden')).toBeTruthy();
+ setColumns([]);
+ expect(view.container.querySelector('[data-kanban-card]')).toBeNull();
+ setColumns([column('alice', [{ ...task, name: 'Regrouped' }])]);
+ expect(view.getByText('Regrouped')).toBeTruthy();
+ expect(view.queryByText('todo paging')).toBeNull();
+ expect(view.getByText('alice paging')).toBeTruthy();
+ const lane = view.container.querySelector('[data-kanban-lane="alice"]');
+ const labelId = lane?.getAttribute('aria-labelledby');
+ expect(document.getElementById(labelId ?? '')?.textContent).toBe('alice');
+ expect(
+ lane
+ ?.querySelector('[data-task-board-scroll]')
+ ?.getAttribute('aria-labelledby')
+ ).toBe(labelId);
+ setHidden(false);
+ expect(view.queryByText('Hidden')).toBeNull();
+
+ await Promise.resolve();
+ const spacer = view.container.querySelector('[data-task-board-rows]');
+ expect(spacer?.nextElementSibling?.textContent).toBe('alice paging');
+});
+
+it('reveals the sorted destination card through both composed virtualizers after a successful move', async () => {
+ const [columns, setColumns] = createSignal([
+ column('todo', [task]),
+ column('done', [{ ...task, id: 'earlier', name: 'Earlier' }]),
+ ]);
+ const move = async () => {
+ setColumns([
+ column('todo', []),
+ column('done', [
+ { ...task, id: 'earlier', name: 'Earlier' },
+ { ...task, statusId: 'done' },
+ ]),
+ ]);
+ return true;
+ };
+ mountBoard({ columns, hidden: () => false, move });
+
+ drag.drop?.({ kind: 'card', id: task.id, fromLane: 'todo', toLane: 'done' });
+ await Promise.resolve();
+ expect(scrolled).toHaveBeenCalledWith('horizontal', 1, { align: 'auto' });
+ expect(scrolled).toHaveBeenCalledWith('vertical', 1, { align: 'auto' });
+});
+
+it('creates final-column resources only while that virtual column is mounted', () => {
+ const [visible, setVisible] = createSignal(false);
+ const [hidden, setHidden] = createSignal(true);
+ visibility.end = visible;
+ const disposed = vi.fn();
+ const endColumn = vi.fn(() => {
+ onCleanup(disposed);
+ const end = document.createElement('section');
+ end.textContent = 'Hidden';
+ return end;
+ });
+ const view = mountBoard({
+ columns: () => [column('todo', [task])],
+ hidden,
+ endColumn,
+ move: async () => true,
+ });
+
+ expect(endColumn).not.toHaveBeenCalled();
+ expect(view.queryByText('Hidden')).toBeNull();
+ setVisible(true);
+ expect(endColumn).toHaveBeenCalledTimes(1);
+ expect(view.getByText('Hidden')).toBeTruthy();
+ setVisible(false);
+ expect(disposed).toHaveBeenCalledTimes(1);
+ expect(view.queryByText('Hidden')).toBeNull();
+ setVisible(true);
+ expect(endColumn).toHaveBeenCalledTimes(2);
+ setHidden(false);
+ expect(disposed).toHaveBeenCalledTimes(2);
+ expect(view.queryByText('Hidden')).toBeNull();
+});
diff --git a/apps/web/src/features/tasks-view/components/task-board-property.tsx b/apps/web/src/features/tasks-view/components/task-board-property.tsx
new file mode 100644
index 0000000000..16045ac948
--- /dev/null
+++ b/apps/web/src/features/tasks-view/components/task-board-property.tsx
@@ -0,0 +1,133 @@
+import { UserIcon } from '@core/component/UserIcon';
+import CalendarIcon from '@phosphor/calendar.svg';
+import EmptyIcon from '@phosphor/circle-dashed.svg';
+import ProjectIcon from '@phosphor/stack.svg';
+import UsersIcon from '@phosphor/users.svg';
+import { Property } from '@property';
+import { PropertyValueIcon } from '@property/component/propertyValue/PropertyValueIcon';
+import type { PropertySaveFn } from '@property/core/context';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import type { Property as PropertyValue } from '@property/types';
+import { getEntityValues, getSelectValues } from '@property/utils/typeGuards';
+import { Match, Show, Switch } from 'solid-js';
+import type { TaskBoardGrouping } from '../core/task-board';
+
+export function TaskBoardColumnIcon(props: {
+ grouping: TaskBoardGrouping;
+ id: string;
+}) {
+ const hasOptionIcon = () => {
+ if (!props.id) {
+ return false;
+ }
+
+ return props.grouping === 'status' || props.grouping === 'priority';
+ };
+
+ return (
+ <Switch fallback={<EmptyIcon class="size-4 text-ink-muted" />}>
+ <Match when={hasOptionIcon()}>
+ <PropertyValueIcon optionId={props.id} class="size-4" />
+ </Match>
+ <Match when={props.grouping === 'project'}>
+ <ProjectIcon class="size-4 text-ink-muted" />
+ </Match>
+ <Match when={props.grouping === 'assignee'}>
+ <Show
+ when={props.id}
+ fallback={<UsersIcon class="size-4 text-ink-muted" />}
+ >
+ <UserIcon
+ id={props.id}
+ size="sm"
+ class="size-4"
+ suppressClick
+ showTooltip={false}
+ />
+ </Show>
+ </Match>
+ </Switch>
+ );
+}
+
+/** The same property editor primitives as task lists, without a block or row context. */
+export function TaskBoardProperty(props: {
+ property: PropertyValue;
+ taskId: string;
+ canEdit: boolean;
+ iconOnly?: boolean;
+ onSave: PropertySaveFn;
+}) {
+ const isAssignee = () =>
+ props.property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.ASSIGNEES;
+ const isProject = () =>
+ props.property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.PROJECT;
+ const isDate = () => props.property.valueType === 'DATE';
+ const hasSelectIcon = () => getSelectValues(props.property).length > 0;
+ const showProjectIcon = () =>
+ props.iconOnly || getEntityValues(props.property).length !== 1;
+
+ return (
+ <Property.Root
+ property={props.property}
+ canEdit={props.canEdit}
+ onSave={props.onSave}
+ >
+ <Property.Tooltip property={props.property}>
+ <Property.Pill
+ variant="ghost"
+ aria-label={props.property.displayName}
+ class={
+ props.iconOnly
+ ? 'min-h-6 min-w-6 justify-center p-0.5'
+ : 'max-w-40 gap-1 px-1.5'
+ }
+ >
+ <Switch
+ fallback={
+ <EmptyIcon class="size-3.5 shrink-0 text-ink-extra-muted" />
+ }
+ >
+ <Match when={isAssignee()}>
+ <Show
+ when={getEntityValues(props.property).length}
+ fallback={<UsersIcon class="size-3.5 shrink-0" />}
+ >
+ <Property.UserStack
+ property={props.property}
+ maxUsers={props.iconOnly ? 1 : 2}
+ avatarClass="size-4"
+ />
+ </Show>
+ </Match>
+ <Match when={isProject()}>
+ <Show when={showProjectIcon()}>
+ <ProjectIcon class="size-3.5 shrink-0" />
+ </Show>
+ </Match>
+ <Match when={isDate()}>
+ <CalendarIcon class="size-3.5 shrink-0" />
+ </Match>
+ <Match when={hasSelectIcon()}>
+ <Property.Icon
+ property={props.property}
+ class="size-3.5 shrink-0"
+ />
+ </Match>
+ </Switch>
+ <Show when={!props.iconOnly}>
+ <Property.Text
+ property={props.property}
+ resolveSingleEntity={isProject()}
+ class="min-w-0 truncate"
+ fallback={<span>{props.property.displayName}</span>}
+ />
+ </Show>
+ </Property.Pill>
+ </Property.Tooltip>
+ <Property.PopoverEditor
+ entitySelfFilter={{ entityType: 'TASK', blockId: props.taskId }}
+ />
+ </Property.Root>
+ );
+}
diff --git a/apps/web/src/features/tasks-view/components/task-board.tsx b/apps/web/src/features/tasks-view/components/task-board.tsx
new file mode 100644
index 0000000000..f1f3a3453d
--- /dev/null
+++ b/apps/web/src/features/tasks-view/components/task-board.tsx
@@ -0,0 +1,613 @@
+import {
+ Kanban,
+ KanbanCard,
+ KanbanLane,
+ useKanbanDropTarget,
+} from '@app/components/kanban/kanban';
+import {
+ createKanbanAnimation,
+ type KanbanAnimationItem,
+} from '@app/components/kanban/kanban-animation';
+import {
+ createKanbanVirtualizer,
+ type KanbanScrollSnapshot,
+} from '@app/components/kanban/kanban-virtualizer';
+import { createKanbanWheelScroll } from '@app/components/kanban/kanban-wheel-scroll';
+import EmptyStateNoFilterMatchGraphic from '@design/empty-state-no-filter-match.svg';
+import { Key } from '@solid-primitives/keyed';
+import { Button } from '@ui/components/Button';
+import { Scroll } from '@ui/components/Scroll';
+import {
+ type Accessor,
+ createContext,
+ createEffect,
+ createMemo,
+ createSignal,
+ createUniqueId,
+ type JSX,
+ on,
+ onCleanup,
+ Show,
+ useContext,
+} from 'solid-js';
+import type {
+ TaskBoardColumn,
+ TaskBoardMove,
+ TaskBoardTask,
+} from '../core/task-board';
+import { taskBoardRevealIndices } from '../core/task-board-reveal';
+
+const END_COLUMN_KEY = -1;
+
+type Reveal = { id: string; toLane: string; scope?: string };
+
+type BoardContextValue = {
+ columns: Accessor<readonly TaskBoardColumn[]>;
+ animationScope: Accessor<string | undefined>;
+ reveal: Accessor<Reveal | undefined>;
+ onRevealed(request: Reveal): void;
+ attachViewport(element: HTMLDivElement): () => void;
+};
+
+type ColumnContextValue = {
+ column: Accessor<TaskBoardColumn>;
+ headerId: string;
+ snapshot?: KanbanScrollSnapshot;
+ onSnapshot(snapshot: KanbanScrollSnapshot): void;
+};
+
+const BoardContext = createContext<BoardContextValue>();
+const ColumnContext = createContext<ColumnContextValue>();
+const ColumnHoverContext = createContext<Accessor<boolean>>();
+
+function useBoardContext() {
+ const context = useContext(BoardContext);
+ if (!context) throw new Error('TaskBoard.Root is required');
+ return context;
+}
+
+function useColumnContext() {
+ const context = useContext(ColumnContext);
+ if (!context) throw new Error('TaskBoard.Columns is required');
+ return context;
+}
+
+/** Owns drag motion and reveal requests, without task queries or property rendering. */
+function Root(props: {
+ columns: readonly TaskBoardColumn[];
+ animationScope?: string;
+ canMove(move: TaskBoardMove): boolean;
+ onMove(move: TaskBoardMove): Promise<boolean>;
+ ref?: (element: HTMLDivElement) => void;
+ children: JSX.Element;
+}) {
+ let viewport: HTMLDivElement | undefined;
+ let revealGeneration = 0;
+ const [reveal, setReveal] = createSignal<Reveal>();
+ const motion = createKanbanAnimation({
+ viewport: () => viewport,
+ items: () => {
+ if (!viewport) {
+ return [];
+ }
+
+ const items: KanbanAnimationItem[] = [];
+
+ for (const layout of viewport.querySelectorAll<HTMLElement>(
+ '[data-task-board-column]'
+ )) {
+ const element = layout.firstElementChild;
+
+ if (!(element instanceof HTMLElement)) {
+ continue;
+ }
+
+ const key = JSON.stringify(['column', layout.dataset.taskBoardColumn]);
+ items.push({ key, element, layout });
+
+ for (const card of element.querySelectorAll<HTMLElement>(
+ '[data-kanban-card]'
+ )) {
+ const row = card.parentElement;
+
+ if (!row) {
+ continue;
+ }
+
+ items.push({
+ key: JSON.stringify([key, card.dataset.kanbanCard]),
+ identity: card.dataset.kanbanCard,
+ parentKey: key,
+ element: card,
+ layout: row,
+ });
+ }
+ }
+
+ return items;
+ },
+ });
+
+ let finishHover: (() => void) | undefined;
+ const endHover = () => {
+ finishHover?.();
+ finishHover = undefined;
+ document.removeEventListener('mouseup', endHover);
+ };
+ const startHover = (event: MouseEvent) => {
+ if (
+ !(event.target instanceof Element) ||
+ !event.target.closest('[data-kanban-card]')
+ ) {
+ return;
+ }
+
+ endHover();
+ finishHover = motion.beginHover();
+ document.addEventListener('mouseup', endHover);
+ };
+
+ createEffect(
+ on(
+ () => props.animationScope,
+ () => {
+ revealGeneration += 1;
+ setReveal(undefined);
+ motion.cancel();
+ }
+ )
+ );
+ onCleanup(() => {
+ viewport?.removeEventListener('mousedown', startHover);
+ endHover();
+ motion.cancel();
+ });
+
+ const context: BoardContextValue = {
+ columns: () => props.columns,
+ animationScope: () => props.animationScope,
+ reveal,
+ onRevealed: (request) =>
+ setReveal((current) => (current === request ? undefined : current)),
+ attachViewport: (element) => {
+ viewport?.removeEventListener('mousedown', startHover);
+ viewport = element;
+ viewport.addEventListener('mousedown', startHover);
+ props.ref?.(element);
+
+ return () => {
+ if (viewport !== element) return;
+ element.removeEventListener('mousedown', startHover);
+ viewport = undefined;
+ revealGeneration += 1;
+ setReveal(undefined);
+ endHover();
+ motion.cancel();
+ };
+ },
+ };
+
+ return (
+ <BoardContext.Provider value={context}>
+ <Kanban
+ getViewport={() => viewport}
+ canDropCard={props.canMove}
+ mode="cross-column"
+ targetActivationSpeed={600}
+ onDrop={(drop, visual) => {
+ if (!props.canMove(drop)) {
+ return;
+ }
+
+ const sourceParentKey = JSON.stringify(['column', drop.fromLane]);
+ const finish = motion.begin(
+ drop.id,
+ JSON.stringify(['column', drop.toLane]),
+ visual
+ ? {
+ ...visual,
+ key: JSON.stringify([sourceParentKey, drop.id]),
+ parentKey: sourceParentKey,
+ }
+ : undefined
+ );
+ const scope = props.animationScope;
+ const generation = ++revealGeneration;
+ setReveal(undefined);
+ const saveAndReveal = async () => {
+ try {
+ const moved = await props.onMove(drop);
+ if (
+ moved &&
+ generation === revealGeneration &&
+ props.animationScope === scope
+ ) {
+ setReveal({ id: drop.id, toLane: drop.toLane, scope });
+ }
+ } finally {
+ finish();
+ }
+ };
+ void saveAndReveal();
+ }}
+ >
+ {props.children}
+ </Kanban>
+ </BoardContext.Provider>
+ );
+}
+
+/** Virtualizes columns and an optional final column supplied by the caller. */
+function Columns(props: {
+ children(column: Accessor<TaskBoardColumn>): JSX.Element;
+ endColumn?: () => JSX.Element;
+}) {
+ const board = useBoardContext();
+ let viewport: HTMLDivElement | undefined;
+ let releaseViewport: (() => void) | undefined;
+ const scrollSnapshots = new Map<string, KanbanScrollSnapshot>();
+ const wheel = createKanbanWheelScroll({
+ viewport: () => viewport,
+ verticalViewport: (target) =>
+ target.closest<HTMLElement>('[data-task-board-scroll]') ??
+ target
+ .closest('[data-kanban-lane]')
+ ?.querySelector<HTMLElement>('[data-task-board-scroll]') ??
+ null,
+ });
+ onCleanup(() => {
+ wheel.reset();
+ releaseViewport?.();
+ });
+ createEffect(on(board.animationScope, wheel.reset));
+ const columnsById = createMemo(
+ () => new Map(board.columns().map((column) => [column.id, column]))
+ );
+ const virtualizer = createKanbanVirtualizer({
+ direction: 'horizontal',
+ keys: () => {
+ const keys: (string | number)[] = board
+ .columns()
+ .map((column) => column.id);
+
+ if (props.endColumn) {
+ keys.push(END_COLUMN_KEY);
+ }
+
+ return keys;
+ },
+ getScrollElement: () => viewport,
+ estimateSize: 336,
+ gap: 16,
+ overscan: 1,
+ paddingStart: 16,
+ paddingEnd: 16,
+ });
+ const virtualItems = createMemo(() =>
+ virtualizer.getVirtualItems().map((item) => ({ ...item }))
+ );
+ createEffect(
+ on(board.reveal, (request) => {
+ if (!request || request.scope !== board.animationScope()) {
+ return;
+ }
+
+ const indices = taskBoardRevealIndices(
+ board.columns(),
+ request.toLane,
+ request.id
+ );
+ if (indices) {
+ virtualizer.scrollToIndex(indices.column, { align: 'auto' });
+ }
+ })
+ );
+
+ return (
+ <Scroll
+ orientation="horizontal"
+ scrollbars="horizontal"
+ autoHide={false}
+ scrollRef={(element) => {
+ releaseViewport?.();
+ viewport = element;
+ releaseViewport = board.attachViewport(element);
+ }}
+ onWheel={wheel.onWheel}
+ class="ph-no-capture min-h-0 min-w-0 w-full flex-1"
+ viewportProps={{
+ tabindex: -1,
+ role: 'region',
+ 'aria-label': 'Task board',
+ class: 'pt-1 pb-4 outline-none',
+ }}
+ contentProps={{ style: { height: '100%' } }}
+ >
+ <div
+ class="relative h-full min-w-full"
+ data-task-board-columns
+ style={{ width: `${virtualizer.getTotalSize()}px` }}
+ >
+ <Key each={virtualItems()} by="key">
+ {(item) => {
+ const key = item().key;
+ return (
+ <div
+ class="absolute top-0 h-full"
+ data-task-board-column={key}
+ style={{
+ left: `${item().start}px`,
+ width: `${item().size}px`,
+ }}
+ >
+ <Show when={key === END_COLUMN_KEY}>{props.endColumn?.()}</Show>
+ <Show when={columnsById().get(String(key))}>
+ {(column) => {
+ // Cleanup runs after Show invalidates its column accessor.
+ const columnId = column().id;
+ const context: ColumnContextValue = {
+ column,
+ headerId: createUniqueId(),
+ snapshot: scrollSnapshots.get(columnId),
+ onSnapshot: (snapshot) => {
+ scrollSnapshots.set(columnId, snapshot);
+ },
+ };
+
+ return (
+ <ColumnContext.Provider value={context}>
+ {props.children(column)}
+ </ColumnContext.Provider>
+ );
+ }}
+ </Show>
+ </div>
+ );
+ }}
+ </Key>
+ </div>
+ </Scroll>
+ );
+}
+
+function Column(props: { children: JSX.Element }) {
+ const { column, headerId } = useColumnContext();
+ const [hovered, setHovered] = createSignal(false);
+
+ return (
+ <ColumnHoverContext.Provider value={hovered}>
+ <KanbanLane
+ id={column().id}
+ label={column().label}
+ aria-labelledby={headerId}
+ class="max-h-full min-h-0 w-84"
+ onPointerEnter={() => setHovered(true)}
+ onPointerLeave={() => setHovered(false)}
+ >
+ {props.children}
+ </KanbanLane>
+ </ColumnHoverContext.Provider>
+ );
+}
+
+function Header(props: { children: JSX.Element }) {
+ const { headerId } = useColumnContext();
+
+ return (
+ <header
+ id={headerId}
+ class="flex min-w-0 shrink-0 items-center gap-2 px-2 pt-1 pb-2"
+ >
+ {props.children}
+ </header>
+ );
+}
+
+function DropOverlay(props: { children: JSX.Element }) {
+ const { column } = useColumnContext();
+ const target = useKanbanDropTarget();
+
+ return (
+ <Show when={target()?.kind === 'card' && target()?.toLane === column().id}>
+ <div
+ aria-hidden="true"
+ class="pointer-events-none absolute inset-2 z-20 flex items-center justify-center rounded-lg bg-surface-0/95 p-4 text-center text-sm font-medium text-ink"
+ >
+ {props.children}
+ </div>
+ </Show>
+ );
+}
+
+/** Owns the vertical viewport and row measurements; card content stays with the caller. */
+function Cards(props: {
+ children(task: Accessor<TaskBoardTask>): JSX.Element;
+ empty?: JSX.Element;
+ footer?: JSX.Element;
+}) {
+ const board = useBoardContext();
+ const lane = useColumnContext();
+ const hovered = useContext(ColumnHoverContext);
+ if (!hovered) throw new Error('TaskBoard.Column is required');
+ let viewport: HTMLDivElement | undefined;
+ const rows = () => lane.column().tasks;
+ const rowsById = createMemo(
+ () => new Map(rows().map((task) => [task.id, task]))
+ );
+ const virtualizer = createKanbanVirtualizer({
+ direction: 'vertical',
+ laneId: () => lane.column().id,
+ keys: () => rows().map((task) => task.id),
+ getScrollElement: () => viewport,
+ estimateSize: 104,
+ gap: 12,
+ overscan: 3,
+ snapshot: lane.snapshot,
+ });
+ const virtualItems = createMemo(() =>
+ virtualizer.getVirtualItems().map((item) => ({ ...item }))
+ );
+
+ createEffect(() => {
+ const request = board.reveal();
+ // Wait for the horizontal lane and vertical viewport to mount.
+ const mountedRows = virtualItems();
+ if (
+ !request ||
+ request.scope !== board.animationScope() ||
+ request.toLane !== lane.column().id ||
+ !viewport?.isConnected ||
+ mountedRows.length === 0
+ ) {
+ return;
+ }
+
+ const row = rows().findIndex((task) => task.id === request.id);
+ if (row < 0) return;
+ virtualizer.scrollToIndex(row, { align: 'auto' });
+ board.onRevealed(request);
+ });
+
+ onCleanup(() => {
+ lane.onSnapshot({
+ offset: viewport?.scrollTop ?? 0,
+ measurements: virtualizer.takeSnapshot(),
+ });
+ });
+
+ return (
+ <Scroll
+ orientation="vertical"
+ scrollbars="vertical"
+ autoHide
+ autoHideDelay={200}
+ revealOn="hover"
+ hovered={hovered()}
+ fill={false}
+ scrollRef={(element) => {
+ viewport = element;
+ }}
+ class="min-h-0 flex-auto"
+ viewportProps={{
+ role: 'region',
+ 'aria-label': `${lane.column().label} tasks`,
+ 'aria-labelledby': lane.headerId,
+ tabindex: 0,
+ 'data-task-board-scroll': lane.column().id,
+ 'data-kanban-scroll': '',
+ style: { 'overflow-anchor': 'none' },
+ }}
+ >
+ <div
+ class="relative w-full"
+ data-task-board-rows
+ style={{ height: `${virtualizer.getTotalSize()}px` }}
+ >
+ <Key each={virtualItems()} by="key">
+ {(item) => {
+ const key = String(item().key);
+ let row: HTMLDivElement | undefined;
+
+ createEffect(
+ on(
+ () => item().index,
+ () => {
+ // Measure after content mounts, and again if a stable key moves.
+ queueMicrotask(() => {
+ if (row?.isConnected) {
+ virtualizer.measureElement(row);
+ }
+ });
+ }
+ )
+ );
+
+ return (
+ <div
+ ref={row}
+ data-index={item().index}
+ data-kanban-card-layout
+ class="absolute left-0 top-0 w-full"
+ style={{ transform: `translateY(${item().start}px)` }}
+ >
+ <Show when={rowsById().get(key)}>
+ {(task) => props.children(task)}
+ </Show>
+ </div>
+ );
+ }}
+ </Key>
+ </div>
+ <Show when={rows().length === 0}>{props.empty}</Show>
+ {props.footer}
+ </Scroll>
+ );
+}
+
+function Card(props: {
+ task: TaskBoardTask;
+ canDrag: boolean;
+ pending: boolean;
+ onOpen(task: TaskBoardTask, event: MouseEvent): void;
+ children: JSX.Element;
+}) {
+ const { column } = useColumnContext();
+
+ return (
+ <KanbanCard
+ id={props.task.id}
+ laneId={column().id}
+ canDrag={props.canDrag}
+ pending={props.pending}
+ onClick={(event) => {
+ if (event.target.closest('[data-kanban-no-drag], button')) {
+ return;
+ }
+
+ props.onOpen(props.task, event);
+ }}
+ >
+ {props.children}
+ </KanbanCard>
+ );
+}
+
+function HiddenColumns(props: {
+ count: number;
+ partial: boolean;
+ onReveal(): void;
+}) {
+ return (
+ <section
+ aria-label="Hidden columns"
+ class="flex h-full min-h-40 w-full flex-col items-center gap-3 rounded-xl border border-dashed border-ink-extra-muted/25 p-4 pt-8 text-ink-muted"
+ >
+ <div aria-hidden="true" class="h-20 w-32 shrink-0 text-ink-extra-muted">
+ <EmptyStateNoFilterMatchGraphic class="size-full" />
+ </div>
+ <h2
+ class="text-sm font-medium"
+ title={
+ props.partial ? `At least ${props.count} hidden columns` : undefined
+ }
+ >
+ {props.count}
+ {props.partial ? '+' : ''} hidden
+ </h2>
+ <Button size="sm" variant="outline" onClick={props.onReveal}>
+ Reveal hidden columns
+ </Button>
+ </section>
+ );
+}
+
+export const TaskBoard = {
+ Root,
+ Columns,
+ Column,
+ Header,
+ DropOverlay,
+ Cards,
+ Card,
+ HiddenColumns,
+};
diff --git a/apps/web/src/features/tasks-view/context/task-board.ts b/apps/web/src/features/tasks-view/context/task-board.ts
new file mode 100644
index 0000000000..5a764c5041
--- /dev/null
+++ b/apps/web/src/features/tasks-view/context/task-board.ts
@@ -0,0 +1,34 @@
+import type { Property, PropertyApiValues } from '@property/types';
+import type { Accessor } from 'solid-js';
+import type {
+ TaskBoardColumn,
+ TaskBoardGrouping,
+ TaskBoardMove,
+ TaskBoardTask,
+} from '../core/task-board';
+
+export type TaskBoardActions = {
+ canEditTask(id: string): boolean;
+ canMoveTo(grouping: TaskBoardGrouping, id: string): boolean;
+ save(move: TaskBoardMove, grouping: TaskBoardGrouping): Promise<void>;
+};
+
+export type TaskBoardData = {
+ columns: Accessor<readonly TaskBoardColumn[]>;
+ /** Known excluded columns; dynamic groupings can contain additional unloaded columns. */
+ hiddenColumnCount: Accessor<number>;
+ task(id: string): TaskBoardTask | undefined;
+ /** Instantiate under the mounted column label's owner. */
+ createAssigneeName(id: Accessor<string>): Accessor<string | undefined>;
+ compareTasks?: (left: string, right: string) => number;
+ actions: TaskBoardActions;
+ property(taskId: string, propertyId: string): Property | undefined;
+ canEditProperty(taskId: string, propertyId: string): boolean;
+ saveProperty(
+ taskId: string,
+ property: Property,
+ values: PropertyApiValues
+ ): Promise<void>;
+ definitionError: Accessor<boolean>;
+ retryDefinitions(): Promise<void>;
+};
diff --git a/apps/web/src/features/tasks-view/core/task-board-optimism.test.ts b/apps/web/src/features/tasks-view/core/task-board-optimism.test.ts
new file mode 100644
index 0000000000..fe31b1ce4a
--- /dev/null
+++ b/apps/web/src/features/tasks-view/core/task-board-optimism.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from 'vitest';
+import type { TaskBoardColumn, TaskBoardTask } from './task-board';
+import {
+ movedTask,
+ placementMatches,
+ projectTaskBoardPlacements,
+} from './task-board-optimism';
+
+const task: TaskBoardTask = {
+ id: 'moving',
+ name: 'Moving',
+ statusId: 'todo',
+ priorityId: 'low',
+ assigneeIds: ['alice', 'carol'],
+ projectIds: ['old-project'],
+};
+
+function column(id: string, tasks: TaskBoardTask[] = []): TaskBoardColumn {
+ return {
+ id,
+ label: id,
+ tasks,
+ count: tasks.length,
+ hasMore: false,
+ loadingMore: false,
+ };
+}
+
+describe('optimistic task placements', () => {
+ it.each([
+ ['status', 'todo', 'done', { statusId: 'done' }],
+ ['priority', 'low', '', { priorityId: undefined }],
+ ['project', 'old-project', 'new-project', { projectIds: ['new-project'] }],
+ ['assignee', 'alice', 'bob', { assigneeIds: ['carol', 'bob'] }],
+ ['assignee', 'alice', '', { assigneeIds: [] }],
+ ] as const)(
+ 'projects %s values without mutating the shared task',
+ (grouping, fromLane, toLane, expected) => {
+ const updated = movedTask(task, grouping, {
+ id: task.id,
+ fromLane,
+ toLane,
+ });
+ expect(updated).toMatchObject(expected);
+ expect(task.assigneeIds).toEqual(['alice', 'carol']);
+ expect(task.statusId).toBe('todo');
+ }
+ );
+
+ it('preserves other assignees, deduplicates destinations, and adjusts loaded counts once', () => {
+ const placement = {
+ task: movedTask(task, 'assignee', {
+ id: task.id,
+ fromLane: 'alice',
+ toLane: 'carol',
+ }),
+ grouping: 'assignee' as const,
+ previousGroupKeys: ['alice', 'carol'],
+ scope: 'test',
+ confirmed: false,
+ };
+ const columns = [column('alice', [task]), column('carol', [task])];
+ const result = projectTaskBoardPlacements(columns, [placement]);
+ expect(result[0].tasks).toEqual([]);
+ expect(result[0].count).toBe(0);
+ expect(result[1].tasks).toEqual([placement.task]);
+ expect(result[1].count).toBe(1);
+ expect(placementMatches(result, placement)).toBe(true);
+ expect(columns[0].tasks).toEqual([task]);
+ });
+
+ it('inserts in host-provided order without reordering existing tasks or creating hidden columns', () => {
+ const earlier = { ...task, id: 'earlier' };
+ const later = { ...task, id: 'later' };
+ const placement = {
+ task: movedTask(task, 'status', {
+ id: task.id,
+ fromLane: 'todo',
+ toLane: 'done',
+ }),
+ grouping: 'status' as const,
+ previousGroupKeys: ['todo'],
+ scope: 'test',
+ confirmed: false,
+ };
+ const rank = ['earlier', 'moving', 'later'];
+ const result = projectTaskBoardPlacements(
+ [column('todo', [task]), column('done', [earlier, later])],
+ [placement],
+ (left, right) => rank.indexOf(left) - rank.indexOf(right)
+ );
+ expect(result[1].tasks.map((task) => task.id)).toEqual(rank);
+ const hidden = projectTaskBoardPlacements(
+ [column('todo', [task])],
+ [placement]
+ );
+ expect(hidden).toHaveLength(1);
+ expect(hidden[0].tasks).toEqual([]);
+ });
+
+ it('does not increase an existing assignee count when its task is outside the loaded page', () => {
+ const placement = {
+ task: movedTask(task, 'assignee', {
+ id: task.id,
+ fromLane: 'alice',
+ toLane: 'carol',
+ }),
+ previousGroupKeys: ['alice', 'carol'],
+ grouping: 'assignee' as const,
+ scope: 'test',
+ confirmed: false,
+ };
+ const destination = { ...column('carol'), count: 25, hasMore: true };
+ const result = projectTaskBoardPlacements(
+ [column('alice', [task]), destination],
+ [placement]
+ );
+
+ expect(result[0].count).toBe(0);
+ expect(result[1].tasks).toEqual([placement.task]);
+ expect(result[1].count).toBe(25);
+ });
+});
diff --git a/apps/web/src/features/tasks-view/core/task-board-optimism.ts b/apps/web/src/features/tasks-view/core/task-board-optimism.ts
new file mode 100644
index 0000000000..e036944d53
--- /dev/null
+++ b/apps/web/src/features/tasks-view/core/task-board-optimism.ts
@@ -0,0 +1,103 @@
+import {
+ moveTaskAssignees,
+ type TaskBoardColumn,
+ type TaskBoardGrouping,
+ type TaskBoardMove,
+ type TaskBoardTask,
+ taskBoardGroupKeys,
+} from './task-board';
+
+export type TaskBoardPlacement = {
+ task: TaskBoardTask;
+ /** Membership before the move, including groups outside loaded pages. */
+ previousGroupKeys: readonly string[];
+ grouping: TaskBoardGrouping;
+ scope: string;
+ confirmed: boolean;
+};
+
+export function movedTask(
+ task: TaskBoardTask,
+ grouping: TaskBoardGrouping,
+ move: TaskBoardMove
+): TaskBoardTask {
+ switch (grouping) {
+ case 'status':
+ return { ...task, statusId: move.toLane || undefined };
+ case 'priority':
+ return { ...task, priorityId: move.toLane || undefined };
+ case 'project':
+ return { ...task, projectIds: move.toLane ? [move.toLane] : [] };
+ case 'assignee':
+ return {
+ ...task,
+ assigneeIds: moveTaskAssignees(
+ task.assigneeIds,
+ move.fromLane,
+ move.toLane
+ ),
+ };
+ }
+}
+
+/** Compare loaded memberships only; never invent or load a hidden destination. */
+export function placementMatches(
+ columns: readonly TaskBoardColumn[],
+ placement: TaskBoardPlacement
+): boolean {
+ const keys = taskBoardGroupKeys(placement.task, placement.grouping);
+ return columns.every(
+ (column) =>
+ column.tasks.some((task) => task.id === placement.task.id) ===
+ keys.includes(column.id)
+ );
+}
+
+/** Keep server ordering intact; insert only the moved card using the host's rank. */
+export function projectTaskBoardPlacements(
+ columns: readonly TaskBoardColumn[],
+ placements: readonly TaskBoardPlacement[],
+ compare?: (left: string, right: string) => number
+): readonly TaskBoardColumn[] {
+ if (placements.length === 0) {
+ return columns;
+ }
+
+ return columns.map((column) => {
+ let tasks = [...column.tasks];
+ let count = column.count;
+
+ for (const placement of placements) {
+ const task = placement.task;
+ const index = tasks.findIndex((item) => item.id === task.id);
+ const belongs = taskBoardGroupKeys(task, placement.grouping).includes(
+ column.id
+ );
+
+ if (index >= 0 && belongs) {
+ tasks[index] = task;
+ continue;
+ }
+
+ if (index >= 0) {
+ tasks.splice(index, 1);
+ count = count === undefined ? undefined : Math.max(0, count - 1);
+ continue;
+ }
+
+ if (!belongs) {
+ continue;
+ }
+
+ const before = compare
+ ? tasks.findIndex((item) => compare(task.id, item.id) < 0)
+ : -1;
+ tasks.splice(before < 0 ? tasks.length : before, 0, task);
+ if (!placement.previousGroupKeys.includes(column.id)) {
+ count = count === undefined ? undefined : count + 1;
+ }
+ }
+
+ return { ...column, tasks, count };
+ });
+}
diff --git a/apps/web/src/features/tasks-view/core/task-board-reveal.ts b/apps/web/src/features/tasks-view/core/task-board-reveal.ts
new file mode 100644
index 0000000000..04e265d651
--- /dev/null
+++ b/apps/web/src/features/tasks-view/core/task-board-reveal.ts
@@ -0,0 +1,13 @@
+import type { TaskBoardColumn } from './task-board';
+
+/** Only reveal a loaded destination membership, never a guessed partial-page position. */
+export function taskBoardRevealIndices(
+ columns: readonly TaskBoardColumn[],
+ columnId: string,
+ taskId: string
+): { column: number; row: number } | undefined {
+ const column = columns.findIndex((item) => item.id === columnId);
+ if (column < 0) return undefined;
+ const row = columns[column].tasks.findIndex((task) => task.id === taskId);
+ return row < 0 ? undefined : { column, row };
+}
diff --git a/apps/web/src/features/tasks-view/core/task-board.ts b/apps/web/src/features/tasks-view/core/task-board.ts
new file mode 100644
index 0000000000..f131eaf6f5
--- /dev/null
+++ b/apps/web/src/features/tasks-view/core/task-board.ts
@@ -0,0 +1,92 @@
+import { match } from 'ts-pattern';
+import type { TaskGroupBy } from '../types';
+
+export type TaskBoardGrouping = 'status' | 'priority' | 'assignee' | 'project';
+
+export const TASK_BOARD_GROUP_OPTIONS: {
+ id: TaskBoardGrouping;
+ label: string;
+}[] = [
+ { id: 'status', label: 'Status' },
+ { id: 'priority', label: 'Priority' },
+ { id: 'assignee', label: 'Assignee' },
+ { id: 'project', label: 'Project' },
+];
+
+/** List-only groupings display Status columns in the board layout. */
+export function toTaskBoardGrouping(groupBy: TaskGroupBy): TaskBoardGrouping {
+ return match(groupBy)
+ .with('none', 'date', () => 'status' as const)
+ .with('status', 'priority', 'assignee', 'project', (grouping) => grouping)
+ .exhaustive();
+}
+
+export type TaskBoardTask = {
+ id: string;
+ name: string;
+ statusId?: string;
+ priorityId?: string;
+ assigneeIds: readonly string[];
+ projectIds: readonly string[];
+};
+
+export type TaskBoardColumn = {
+ id: string;
+ label: string;
+ tasks: readonly TaskBoardTask[];
+ /** Omitted for search results, whose complete count is not known. */
+ count?: number;
+ hasMore: boolean;
+ loadingMore: boolean;
+};
+
+export type TaskBoardMove = {
+ id: string;
+ fromLane: string;
+ toLane: string;
+};
+
+export function taskBoardGroupKeys(
+ task: TaskBoardTask,
+ grouping: TaskBoardGrouping
+): readonly string[] {
+ const values = match(grouping)
+ .with('status', () => (task.statusId ? [task.statusId] : []))
+ .with('priority', () => (task.priorityId ? [task.priorityId] : []))
+ .with('assignee', () => task.assigneeIds)
+ .with('project', () => task.projectIds)
+ .exhaustive();
+
+ return values.length ? values : [''];
+}
+
+/** An unassigned destination explicitly clears all assignments. */
+export function moveTaskAssignees(
+ ids: readonly string[],
+ from: string,
+ to: string
+): string[] {
+ if (!to) {
+ return [];
+ }
+
+ const remaining = ids.filter((id) => id !== from);
+
+ return [...new Set([...remaining, to])];
+}
+
+export function isTaskBoardMove(
+ task: TaskBoardTask | undefined,
+ grouping: TaskBoardGrouping,
+ move: TaskBoardMove
+): task is TaskBoardTask {
+ if (!task || task.id !== move.id) {
+ return false;
+ }
+
+ if (move.fromLane === move.toLane) {
+ return false;
+ }
+
+ return taskBoardGroupKeys(task, grouping).includes(move.fromLane);
+}
diff --git a/apps/web/src/features/tasks-view/filters/task-facets.ts b/apps/web/src/features/tasks-view/filters/task-facets.ts
index e5f4a92bf1..9862cc4e71 100644
--- a/apps/web/src/features/tasks-view/filters/task-facets.ts
+++ b/apps/web/src/features/tasks-view/filters/task-facets.ts
@@ -9,7 +9,7 @@ import {
TAG_FACET_ID,
type TagFacetContext,
tagFacetOption,
-} from '@app/features/soup';
+} from '@app/features/soup/filters/facets';
import type { TaskEntityWithProperties } from '@entity/types/entity';
import {
getTaskAssigneeIds,
diff --git a/apps/web/src/features/tasks-view/persistence.ts b/apps/web/src/features/tasks-view/persistence.ts
index 93346ee78b..04aefcf8ff 100644
--- a/apps/web/src/features/tasks-view/persistence.ts
+++ b/apps/web/src/features/tasks-view/persistence.ts
@@ -40,6 +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'),
tab: taskTabSchema.default('my-tasks'),
search: z.string().default(''),
groupBy: taskGroupBySchema.default('priority'),
@@ -54,6 +55,7 @@ type TasksEntryState = z.infer<typeof tasksEntryStateSchemaWithDefaults>;
const DEFAULT_TASKS_ENTRY_STATE = {
version: 1,
+ layout: 'list',
tab: 'my-tasks',
search: '',
groupBy: 'priority',
@@ -70,12 +72,6 @@ const tasksListStateSchemaWithDefaults = z.object({
type TasksListEntryState = z.infer<typeof tasksListStateSchemaWithDefaults>;
-const DEFAULT_TASKS_LIST_ENTRY_STATE = {
- version: 1,
- focusKey: undefined,
- scrollOffset: 0,
-} satisfies TasksListEntryState;
-
export type TasksListStateSnapshot = {
focusKey: TasksListEntryState['focusKey'];
scrollOffset: TasksListEntryState['scrollOffset'];
@@ -89,6 +85,7 @@ export const DEFAULT_TASKS_LIST_STATE: TasksListStateSnapshot = {
function selectEntryState(state: TasksViewState): TasksEntryState {
return {
version: 1,
+ layout: state.layout,
tab: state.tab,
search: state.search,
groupBy: state.groupBy,
@@ -115,6 +112,7 @@ function createTasksEntryStorage(options: {
const restored = result.success ? result.data : DEFAULT_TASKS_ENTRY_STATE;
return {
...current,
+ layout: restored.layout,
tab: restored.tab,
search: restored.search,
groupBy: restored.groupBy,
@@ -138,9 +136,7 @@ export function createTasksListEntryStorage(
: TASKS_LIST_ENTRY_STATE_KEY,
restore: (current, stored) => {
const result = tasksListStateSchemaWithDefaults.safeParse(stored);
- const restored = result.success
- ? result.data
- : DEFAULT_TASKS_LIST_ENTRY_STATE;
+ const restored = result.success ? result.data : DEFAULT_TASKS_LIST_STATE;
return {
...current,
diff --git a/apps/web/src/features/tasks-view/primitives/create-task-board.test.ts b/apps/web/src/features/tasks-view/primitives/create-task-board.test.ts
new file mode 100644
index 0000000000..dbd26ef6c7
--- /dev/null
+++ b/apps/web/src/features/tasks-view/primitives/create-task-board.test.ts
@@ -0,0 +1,146 @@
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import {
+ type TaskBoardColumn,
+ type TaskBoardTask,
+ toTaskBoardGrouping,
+} from '../core/task-board';
+import type { TaskGroupBy } from '../types';
+import { createTaskBoard } from './create-task-board';
+
+const disposers: (() => void)[] = [];
+const move = { id: 'one', fromLane: 'todo', toLane: 'done' };
+const task: TaskBoardTask = {
+ id: 'one',
+ name: 'One',
+ statusId: 'todo',
+ assigneeIds: [],
+ projectIds: [],
+};
+
+function rows(destination: string, statusId = destination): TaskBoardColumn[] {
+ return ['todo', 'done'].map((id) => ({
+ id,
+ label: id,
+ tasks: id === destination ? [{ ...task, statusId }] : [],
+ hasMore: false,
+ loadingMore: false,
+ }));
+}
+
+function setup() {
+ return createRoot((dispose) => {
+ disposers.push(dispose);
+ const [columns, setColumns] = createSignal(rows('todo'));
+ const [groupBy, setGroupBy] = createSignal<TaskGroupBy>('status');
+ const save = vi.fn(async () => {});
+ const board = createTaskBoard({
+ grouping: () => toTaskBoardGrouping(groupBy()),
+ scope: () => toTaskBoardGrouping(groupBy()),
+ columns,
+ task: (id) =>
+ columns()
+ .flatMap((column) => column.tasks)
+ .find((item) => item.id === id),
+ actions: { canEditTask: () => true, canMoveTo: () => true, save },
+ });
+
+ return { board, save, setColumns, setGroupBy };
+ });
+}
+
+function deferSave(save: ReturnType<typeof setup>['save']) {
+ let resolve!: () => void;
+ save.mockImplementationOnce(
+ () =>
+ new Promise<void>((done) => {
+ resolve = done;
+ })
+ );
+ return () => resolve();
+}
+
+afterEach(() => {
+ for (const dispose of disposers) {
+ dispose();
+ }
+ disposers.length = 0;
+});
+
+it('blocks concurrent moves and restores the previous placement after a failed second move', async () => {
+ const { board, save } = setup();
+ const resolve = deferSave(save);
+ const pending = board.move(move);
+
+ expect(board.pending('one')).toBe(true);
+ expect(board.columns()[0].tasks).toEqual([]);
+ expect(board.columns()[1].tasks[0].id).toBe('one');
+ expect(await board.move(move)).toBe(false);
+ expect(save).toHaveBeenCalledOnce();
+
+ resolve();
+ expect(await pending).toBe(true);
+ save.mockRejectedValueOnce(new Error('Forbidden'));
+
+ expect(await board.move({ ...move, fromLane: 'done', toLane: 'todo' })).toBe(
+ false
+ );
+ expect(board.pending('one')).toBe(false);
+ expect(board.error()).toContain('Could not move task');
+ expect(board.columns()[1].tasks[0].id).toBe('one');
+});
+
+it('ignores stale feed data until membership and properties acknowledge the saved move', async () => {
+ const { board, save, setColumns, setGroupBy } = setup();
+ const resolve = deferSave(save);
+ const pending = board.move(move);
+ await Promise.resolve();
+
+ setGroupBy('priority');
+ setGroupBy('status');
+ expect(board.columns()[1].tasks).toHaveLength(1);
+
+ setColumns(rows('done')); // Local cache optimism precedes save completion.
+ resolve();
+ await pending;
+ setColumns(rows('todo')); // A stale response cannot undo the saved placement.
+ expect(board.columns()[1].tasks).toHaveLength(1);
+
+ setColumns(rows('done', 'todo')); // Membership alone does not acknowledge properties.
+ expect(board.canMove({ ...move, fromLane: 'done', toLane: 'todo' })).toBe(
+ true
+ );
+
+ setColumns(rows('done'));
+ await Promise.resolve();
+ setColumns(rows('todo')); // After acknowledgement, later feed changes are authoritative.
+ expect(board.columns()[0].tasks).toHaveLength(1);
+ expect(board.columns()[1].tasks).toEqual([]);
+});
+
+it.each([false, true])(
+ 'discards confirmed placement across grouping changes (save completes away: %s)',
+ async (completeAway) => {
+ const { board, save, setColumns, setGroupBy } = setup();
+ const resolve = deferSave(save);
+ await Promise.resolve();
+ const pending = board.move(move);
+
+ if (!completeAway) {
+ resolve();
+ await pending;
+ }
+
+ setGroupBy('priority');
+
+ if (completeAway) {
+ resolve();
+ await pending;
+ }
+
+ setColumns(rows('todo'));
+ setGroupBy('date'); // List-only grouping falls back to Status in the board.
+ expect(board.columns()[0].tasks).toEqual([task]);
+ expect(board.columns()[1].tasks).toEqual([]);
+ }
+);
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
new file mode 100644
index 0000000000..474b8aeed7
--- /dev/null
+++ b/apps/web/src/features/tasks-view/primitives/create-task-board.ts
@@ -0,0 +1,194 @@
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+} from 'solid-js';
+import type { TaskBoardActions } from '../context/task-board';
+import {
+ isTaskBoardMove,
+ type TaskBoardColumn,
+ type TaskBoardGrouping,
+ type TaskBoardMove,
+ type TaskBoardTask,
+ taskBoardGroupKeys,
+} from '../core/task-board';
+import {
+ movedTask,
+ placementMatches,
+ projectTaskBoardPlacements,
+ type TaskBoardPlacement,
+} from '../core/task-board-optimism';
+
+type Placement = TaskBoardPlacement & {
+ confirmedColumns?: readonly TaskBoardColumn[];
+};
+/** Owns temporary placements; shared mutations still own property values and rollback. */
+export function createTaskBoard(options: {
+ grouping: Accessor<TaskBoardGrouping>;
+ scope: Accessor<string>;
+ columns: Accessor<readonly TaskBoardColumn[]>;
+ task(id: string): TaskBoardTask | undefined;
+ actions: TaskBoardActions;
+ compareTasks?: (left: string, right: string) => number;
+}) {
+ const [pending, setPending] = createSignal<ReadonlySet<string>>(new Set());
+ const [error, setError] = createSignal<{ scope: string; text: string }>();
+ const [placements, setPlacements] = createSignal<readonly Placement[]>([]);
+ const currentPlacements = createMemo(() =>
+ placements().filter(
+ (placement) =>
+ placement.scope === options.scope() && !!options.task(placement.task.id)
+ )
+ );
+ const columns = createMemo(() =>
+ projectTaskBoardPlacements(
+ options.columns(),
+ currentPlacements(),
+ options.compareTasks
+ )
+ );
+
+ createEffect(() => {
+ const retained = placements().filter((placement) => {
+ if (!placement.confirmed) {
+ return true;
+ }
+
+ // Completed overrides must not mask edits made in another view.
+ if (placement.scope !== options.scope()) {
+ return false;
+ }
+
+ // A local cache projection is not acknowledgement of a committed write.
+ if (options.columns() === placement.confirmedColumns) {
+ return true;
+ }
+
+ const current = options.task(placement.task.id);
+
+ if (!current) {
+ return false;
+ }
+
+ const expected = taskBoardGroupKeys(placement.task, placement.grouping);
+ const actual = taskBoardGroupKeys(current, placement.grouping);
+ const valuesMatch =
+ expected.length === actual.length &&
+ expected.every((key) => actual.includes(key));
+
+ return !valuesMatch || !placementMatches(options.columns(), placement);
+ });
+
+ if (retained.length !== placements().length) {
+ setPlacements(retained);
+ }
+ });
+
+ const canMove = (move: TaskBoardMove) => {
+ if (pending().has(move.id) || !options.actions.canEditTask(move.id)) {
+ return false;
+ }
+
+ const task =
+ currentPlacements().find((placement) => placement.task.id === move.id)
+ ?.task ?? options.task(move.id);
+ const grouping = options.grouping();
+
+ if (!isTaskBoardMove(task, grouping, move)) {
+ return false;
+ }
+
+ const destinationExists = options
+ .columns()
+ .some((column) => column.id === move.toLane);
+
+ if (!destinationExists) {
+ return false;
+ }
+
+ return options.actions.canMoveTo(grouping, move.toLane);
+ };
+
+ const move = async (request: TaskBoardMove): Promise<boolean> => {
+ if (!canMove(request)) {
+ return false;
+ }
+
+ const grouping = options.grouping();
+ const scope = options.scope();
+ const task =
+ currentPlacements().find((placement) => placement.task.id === request.id)
+ ?.task ?? options.task(request.id);
+
+ if (!task) {
+ return false;
+ }
+
+ const previous = currentPlacements().find(
+ (item) => item.task.id === request.id
+ );
+ const placement: Placement = {
+ task: movedTask(task, grouping, request),
+ previousGroupKeys: taskBoardGroupKeys(task, grouping),
+ grouping,
+ scope,
+ confirmed: false,
+ };
+ setPlacements((items) => [
+ ...items.filter((item) => item.task.id !== request.id),
+ placement,
+ ]);
+
+ setPending((ids) => new Set([...ids, request.id]));
+ setError(undefined);
+
+ try {
+ await options.actions.save(request, grouping);
+ setPlacements((items) =>
+ items.map((item) =>
+ item === placement
+ ? { ...item, confirmed: true, confirmedColumns: options.columns() }
+ : item
+ )
+ );
+
+ return true;
+ } catch {
+ setPlacements((items) => {
+ const retained = items.filter((item) => item !== placement);
+
+ if (previous) {
+ retained.push(previous);
+ }
+
+ return retained;
+ });
+ setError({
+ scope,
+ text: 'Could not move task. Refresh or try again.',
+ });
+ return false;
+ } finally {
+ setPending((ids) => new Set([...ids].filter((id) => id !== request.id)));
+ }
+ };
+
+ const currentError = () => {
+ const current = error();
+
+ if (current?.scope !== options.scope()) {
+ return undefined;
+ }
+
+ return current?.text;
+ };
+
+ return {
+ columns,
+ canMove,
+ move,
+ pending: (id: string) => pending().has(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
new file mode 100644
index 0000000000..2c3dabdedf
--- /dev/null
+++ b/apps/web/src/features/tasks-view/primitives/create-tasks-view-search.test.ts
@@ -0,0 +1,141 @@
+import { createRoot } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { afterEach, expect, it, vi } from 'vitest';
+import type { TasksTabSearchParams } from '../tasks-tab-search';
+import type { TasksTab, TasksViewState } from '../types';
+import { createTasksViewSearch } from './create-tasks-view-search';
+
+const disposers: (() => void)[] = [];
+
+afterEach(() => {
+ for (const dispose of disposers.splice(0)) dispose();
+});
+
+function setup(
+ options: {
+ state?: Partial<TasksViewState>;
+ search?: Partial<TasksTabSearchParams>;
+ scopedTab?: TasksTab;
+ enabled?: boolean;
+ } = {}
+) {
+ return createRoot((dispose) => {
+ disposers.push(dispose);
+ const [state, setState] = createStore<TasksViewState>({
+ layout: 'list',
+ tab: 'my-tasks',
+ search: 'keep this search',
+ groupBy: 'priority',
+ sort: [{ id: 'updated_at' }],
+ facets: { priority: ['high'] },
+ collapsedGroupIds: ['collapsed'],
+ collapsedSidebarSectionIds: [],
+ ...options.state,
+ });
+ const [search, setSearch] = createStore<TasksTabSearchParams>({
+ tab: 'my-tasks',
+ layout: undefined,
+ groupBy: undefined,
+ sort: undefined,
+ sortReversed: undefined,
+ ...options.search,
+ });
+ const writeSearch = vi.fn((patch: Partial<TasksTabSearchParams>) => {
+ setSearch(patch);
+ });
+ const controls = createTasksViewSearch({
+ state,
+ setState,
+ search,
+ setSearch: writeSearch,
+ tab: () => options.scopedTab ?? search.tab,
+ enabled: options.enabled ?? true,
+ });
+
+ return { state, search, setSearch, writeSearch, ...controls };
+ });
+}
+
+it('restores layout and controls from URL history without losing entry-only state', () => {
+ const view = setup({
+ state: { layout: 'board', groupBy: 'date' },
+ search: {
+ layout: 'list',
+ groupBy: 'assignee',
+ sort: 'created_at',
+ sortReversed: 'true',
+ },
+ });
+
+ expect(view.state.layout).toBe('list');
+ expect(view.state.groupBy).toBe('assignee');
+ expect(view.state.sort).toEqual([{ id: 'created_at', reversed: true }]);
+ view.setState('layout', 'board');
+ expect(view.search.layout).toBe('board');
+ view.setSearch('layout', 'list');
+ expect(view.state.layout).toBe('list');
+ view.setSearch('layout', 'board');
+ expect(view.state.layout).toBe('board');
+ view.setSearch('layout', 'list');
+
+ view.setSearch({
+ layout: undefined,
+ groupBy: undefined,
+ sort: undefined,
+ sortReversed: undefined,
+ });
+ expect(view.state.layout).toBe('board');
+ expect(view.state.groupBy).toBe('date');
+ expect(view.state.sort).toEqual([{ id: 'updated_at' }]);
+ expect(view.state.search).toBe('keep this search');
+ expect(view.state.facets).toEqual({ priority: ['high'] });
+ expect(view.state.collapsedGroupIds).toEqual(['collapsed']);
+});
+
+it('keeps project controls independent from the parent Tasks URL and tab', () => {
+ const parent = setup({ search: { groupBy: 'priority' } });
+ const project = setup({
+ state: { tab: 'team-tasks', groupBy: 'status' },
+ scopedTab: 'team-tasks',
+ });
+
+ project.setState('layout', 'board');
+ project.setState('groupBy', 'assignee');
+ project.setPrimarySort('created_at');
+ project.setPrimarySort('created_at');
+ expect(project.state.tab).toBe('team-tasks');
+ expect(project.search).toMatchObject({
+ layout: 'board',
+ groupBy: 'assignee',
+ sort: 'created_at',
+ sortReversed: 'true',
+ });
+ expect(parent.state.layout).toBe('list');
+ expect(parent.state.groupBy).toBe('priority');
+ expect(parent.state.sort).toEqual([{ id: 'updated_at' }]);
+ expect(parent.writeSearch).not.toHaveBeenCalled();
+
+ project.setSearch('layout', 'list');
+ expect(project.state.layout).toBe('list');
+ expect(project.state.tab).toBe('team-tasks');
+ parent.setState('layout', 'board');
+ expect(project.state.layout).toBe('list');
+});
+
+it('leaves embedded entry state and the parent URL untouched without a URL capability', () => {
+ const view = setup({
+ state: { tab: 'team-tasks', groupBy: 'status' },
+ search: { layout: 'board', groupBy: 'assignee', sort: 'created_at' },
+ enabled: false,
+ });
+
+ expect(view.state.layout).toBe('list');
+ expect(view.state.tab).toBe('team-tasks');
+ expect(view.state.groupBy).toBe('status');
+ view.setState('layout', 'board');
+ view.setState('groupBy', 'priority');
+ view.setPrimarySort('viewed_at');
+ expect(view.state.sort).toEqual([{ id: 'viewed_at', reversed: false }]);
+ expect(view.writeSearch).not.toHaveBeenCalled();
+ expect(view.search.sort).toBe('created_at');
+});
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
new file mode 100644
index 0000000000..1bf781c931
--- /dev/null
+++ b/apps/web/src/features/tasks-view/primitives/create-tasks-view-search.ts
@@ -0,0 +1,87 @@
+import { normalizeFacetSelection } from '@app/features/soup/filters/facets';
+import { type Accessor, createEffect, on } from 'solid-js';
+import { produce, type SetStoreFunction, type Store } from 'solid-js/store';
+import { TASK_DEFAULT_GROUP_BY } from '../constants';
+import { DEFAULT_TASK_FACET_SELECTION } from '../filters/task-facets';
+import type { TasksTabSearchParams } from '../tasks-tab-search';
+import type { TaskSortId, TasksTab, TasksViewState } from '../types';
+
+/** Coordinates one host's URL controls without knowing its route or namespace. */
+export function createTasksViewSearch(options: {
+ state: Store<TasksViewState>;
+ setState: SetStoreFunction<TasksViewState>;
+ search: TasksTabSearchParams;
+ setSearch: (patch: Partial<TasksTabSearchParams>) => void;
+ tab: Accessor<TasksTab>;
+ enabled: boolean;
+}) {
+ const { state, search } = options;
+ // Missing URL controls restore the entry snapshot, not the latest selection.
+ const entrySort = state.sort.map((item) => ({ ...item }));
+ const entryTab = state.tab;
+ const entryGroupBy = state.groupBy;
+ const entryLayout = state.layout;
+
+ createEffect(
+ on(
+ () =>
+ [
+ options.tab(),
+ search.layout,
+ search.sort,
+ search.sortReversed,
+ search.groupBy,
+ ] as const,
+ ([tab, layout, sort, sortReversed, groupBy]) => {
+ if (!options.enabled) return;
+
+ options.setState(
+ produce((draft) => {
+ if (draft.tab !== tab) {
+ draft.tab = tab;
+ draft.facets = normalizeFacetSelection(
+ DEFAULT_TASK_FACET_SELECTION
+ );
+ draft.collapsedGroupIds = [];
+ }
+
+ draft.layout = layout ?? entryLayout;
+ draft.groupBy =
+ groupBy ??
+ (tab === entryTab ? entryGroupBy : TASK_DEFAULT_GROUP_BY[tab]);
+ draft.sort = sort
+ ? [{ id: sort, reversed: sortReversed === 'true' }]
+ : entrySort.map((item) => ({ ...item }));
+ })
+ );
+ }
+ )
+ );
+
+ const setState = new Proxy(options.setState, {
+ apply(target, thisArg, args: unknown[]) {
+ Reflect.apply(target, thisArg, args);
+ if (!options.enabled) return;
+
+ if (args[0] === 'layout') {
+ options.setSearch({ layout: state.layout });
+ }
+
+ if (args[0] === 'groupBy') {
+ options.setSearch({ groupBy: state.groupBy });
+ }
+ },
+ });
+
+ const setPrimarySort = (id: TaskSortId) => {
+ const current = state.sort[0];
+ const reversed = current?.id === id ? !current.reversed : false;
+
+ options.setState('sort', [{ id, reversed }]);
+ if (!options.enabled) return;
+
+ options.setSearch({ sort: id, sortReversed: reversed ? 'true' : 'false' });
+ };
+
+ return { setState, setPrimarySort };
+}
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
new file mode 100644
index 0000000000..8e83fe6dab
--- /dev/null
+++ b/apps/web/src/features/tasks-view/queries/task-board-queries.test.ts
@@ -0,0 +1,171 @@
+import { createSoupEntityRow } from '@app/features/soup/collection/rows';
+import { PROPERTY_OPTION_IDS } from '@property/constants';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { boardEntity, boardProperty } from '../tests/task-board-fixture';
+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,
+ save: vi.fn(async (_input: unknown) => {}),
+ ensureProject: vi.fn(async (_options: unknown) => ({
+ project: { id: 'launch', access: 'edit' },
+ })),
+}));
+
+vi.mock('@queries/storage/document-metadata', () => ({
+ useDocumentAccessLevelsQuery: (ids: () => readonly string[]) => {
+ fixture.ids = ids;
+ return fixture.permissions;
+ },
+}));
+vi.mock('@queries/properties/definitions', () => ({
+ useListPropertiesQuery: () => fixture.definitions,
+}));
+vi.mock('@queries/properties/entity', () => ({
+ useBulkSaveEntityPropertiesMutation: () => ({ mutateAsync: fixture.save }),
+}));
+vi.mock('@tanstack/solid-query', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@tanstack/solid-query')>()),
+ useQueries: () => [],
+ useQueryClient: () => ({ ensureQueryData: fixture.ensureProject }),
+}));
+vi.mock('@service-storage/initiative', () => ({ initiativeClient: {} }));
+vi.mock('@app/features/projects/queries/project-identity', () => ({
+ projectDetailQueryOptions: () => ({}),
+}));
+
+const disposers: (() => void)[] = [];
+
+function setup(
+ options: Partial<Parameters<typeof createTaskBoardQueries>[0]> = {}
+) {
+ return createRoot((dispose) => {
+ disposers.push(dispose);
+ return createTaskBoardQueries({
+ rows: () => [createSoupEntityRow(boardEntity('one'))],
+ grouping: () => 'status',
+ searching: () => false,
+ userId: () => 'viewer',
+ projectsEnabled: () => true,
+ ...options,
+ });
+ });
+}
+
+beforeEach(() => {
+ fixture.permissions = [
+ { isSuccess: true, data: { documentId: 'one', accessLevel: 'edit' } },
+ ];
+ fixture.definitions = {
+ isSuccess: false,
+ get data() {
+ throw new Error('pending data must not be read');
+ },
+ };
+ fixture.save.mockReset();
+ fixture.save.mockResolvedValue(undefined);
+ fixture.ensureProject.mockReset();
+ fixture.ensureProject.mockResolvedValue({
+ project: { id: 'launch', access: 'edit' },
+ });
+});
+
+afterEach(() => {
+ for (const dispose of disposers) {
+ dispose();
+ }
+ 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',
+ });
+
+ expect(fixture.ids?.()).toEqual(['one']);
+ expect(source.actions.canEditTask('one')).toBe(false);
+ expect(source.actions.canMoveTo('assignee', 'b')).toBe(false);
+ }
+);
+
+it('blocks overlapping property writes and restores editability when a write fails', async () => {
+ fixture.definitions = {
+ isSuccess: true,
+ data: [
+ boardProperty(SYSTEM_PROPERTY_IDS.PRIORITY, null, 'SELECT_STRING')
+ .definition,
+ ],
+ };
+ let reject!: (error: Error) => void;
+ fixture.save.mockImplementationOnce(
+ () =>
+ new Promise<void>((_resolve, fail) => {
+ reject = fail;
+ })
+ );
+ const source = setup();
+ const property = source.property('one', SYSTEM_PROPERTY_IDS.PRIORITY)!;
+ const values = {
+ valueType: 'SELECT_STRING' as const,
+ values: [PROPERTY_OPTION_IDS.PRIORITY.HIGH],
+ };
+ const pending = source.saveProperty('one', property, values);
+ const failed = expect(pending).rejects.toThrow('rejected');
+
+ expect(source.actions.canEditTask('one')).toBe(false);
+ await expect(source.saveProperty('one', property, values)).rejects.toThrow(
+ 'no longer editable'
+ );
+ reject(new Error('rejected'));
+ await failed;
+
+ expect(fixture.save).toHaveBeenCalledOnce();
+ expect(source.actions.canEditTask('one')).toBe(true);
+});
+
+it('checks project edit access before writing and releases the task lock on rejection', async () => {
+ fixture.definitions = {
+ isSuccess: true,
+ data: [boardProperty(SYSTEM_PROPERTY_IDS.PROJECT, null).definition],
+ };
+ fixture.ensureProject.mockResolvedValueOnce({
+ project: { id: 'launch', access: 'view' },
+ });
+ const source = setup();
+
+ await expect(
+ source.saveProperty(
+ 'one',
+ source.property('one', SYSTEM_PROPERTY_IDS.PROJECT)!,
+ {
+ valueType: 'ENTITY',
+ refs: [{ entity_id: 'launch', entity_type: 'INITIATIVE' }],
+ }
+ )
+ ).rejects.toThrow('not editable');
+
+ expect(fixture.ensureProject).toHaveBeenCalledOnce();
+ expect(fixture.save).not.toHaveBeenCalled();
+ expect(source.actions.canEditTask('one')).toBe(true);
+});
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
new file mode 100644
index 0000000000..8e594cf6a4
--- /dev/null
+++ b/apps/web/src/features/tasks-view/queries/task-board-queries.ts
@@ -0,0 +1,356 @@
+import { canEditProject } from '@app/features/projects/core/project';
+import { projectDetailQueryOptions } from '@app/features/projects/queries/project-identity';
+import type { FacetSelection, SortSelection } from '@app/features/soup';
+import { sortItems } from '@app/features/soup/collection/transforms';
+import { soupPropertyToProperty } from '@entity/extractors-property/property-helpers';
+import type { TaskEntityWithProperties } from '@entity/types/entity';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+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 { initiativeClient } from '@service-storage/initiative';
+import { useQueries, useQueryClient } from '@tanstack/solid-query';
+import { type Accessor, createMemo, createSignal } from 'solid-js';
+import { TASK_SORT_DEFINITIONS } from '../constants';
+import type { TaskBoardActions } from '../context/task-board';
+import type { TaskBoardColumn, TaskBoardGrouping } from '../core/task-board';
+import type { TaskSortId } from '../types';
+import {
+ filterTaskBoardColumns,
+ taskBoardColumns,
+ taskBoardMoveValue,
+ taskBoardPropertyId,
+ toBoardTask,
+} from './task-board';
+import type { TasksDataSourceItem } from './use-tasks-query';
+
+/** Adapts shared query caches to the board's narrow read/write capabilities. */
+export function createTaskBoardQueries(options: {
+ rows: Accessor<readonly TasksDataSourceItem[]>;
+ grouping: Accessor<TaskBoardGrouping>;
+ searching: Accessor<boolean>;
+ userId: Accessor<string | undefined>;
+ projectsEnabled: Accessor<boolean>;
+ facets?: Accessor<FacetSelection>;
+ sort?: Accessor<SortSelection<TaskSortId>[]>;
+}) {
+ const queryClient = useQueryClient();
+ const [propertySaving, setPropertySaving] = createSignal<ReadonlySet<string>>(
+ new Set()
+ );
+
+ const entities = createMemo(() => {
+ const result = new Map<string, TaskEntityWithProperties>();
+
+ for (const row of options.rows()) {
+ if (row.kind !== 'entity') {
+ continue;
+ }
+
+ result.set(row.entity.id, row.entity);
+ }
+
+ return result;
+ });
+
+ const ranks = createMemo(() => {
+ const values = [...entities().values()];
+ const ordered = options.searching()
+ ? values
+ : sortItems(
+ values,
+ options.sort?.() ?? [{ id: 'updated_at' }],
+ TASK_SORT_DEFINITIONS
+ );
+
+ 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,
+ }));
+ const properties = createMemo(() => {
+ const available = definitions.isSuccess ? definitions.data : [];
+
+ return new Map(
+ available.map((item) => {
+ const definition = 'definition' in item ? item.definition : item;
+ const propertyOptions =
+ 'property_options' in item ? item.property_options : [];
+ const property = toPropertyDefinitionDomain(
+ definition,
+ propertyOptions
+ );
+
+ return [definition.id, property];
+ })
+ );
+ });
+
+ const allColumns = createMemo(() =>
+ taskBoardColumns(options.rows(), options.grouping(), options.searching())
+ );
+ const rawColumns = createMemo(() =>
+ filterTaskBoardColumns(
+ allColumns(),
+ options.grouping(),
+ options.facets?.() ?? {}
+ )
+ );
+
+ const projectIds = createMemo(() => {
+ if (options.grouping() !== 'project' || !options.projectsEnabled()) {
+ return [];
+ }
+
+ return rawColumns().flatMap((column) => (column.id ? [column.id] : []));
+ });
+
+ const projects = useQueries(() => ({
+ queries: projectIds().map((id) => ({
+ ...projectDetailQueryOptions(initiativeClient, options.userId(), id),
+ enabled: !!options.userId(),
+ })),
+ }));
+
+ const projectMap = createMemo(() => {
+ const entries = projects.flatMap((query) => {
+ if (!query.isSuccess) {
+ return [];
+ }
+
+ const project = query.data.project;
+
+ return [[project.id, project] as const];
+ });
+
+ return new Map(entries);
+ });
+
+ const columnLabel = (column: TaskBoardColumn) => {
+ if (!column.id) {
+ return column.label;
+ }
+
+ if (options.grouping() === 'project') {
+ return projectMap().get(column.id)?.name ?? 'Unavailable project';
+ }
+
+ return column.label;
+ };
+
+ const columns = createMemo(() => {
+ return rawColumns().map((column) => ({
+ ...column,
+ label: columnLabel(column),
+ }));
+ });
+
+ const save = useBulkSaveEntityPropertiesMutation();
+
+ const actions: TaskBoardActions = {
+ canEditTask(id) {
+ if (!entities().has(id) || !editableTasks().has(id)) {
+ return false;
+ }
+
+ return !propertySaving().has(id);
+ },
+ canMoveTo(grouping, id) {
+ const property = properties().get(taskBoardPropertyId(grouping));
+
+ if (!property) {
+ return false;
+ }
+
+ if (grouping === 'status') {
+ return !!id && !!property.options?.some((option) => option.id === id);
+ }
+
+ if (grouping === 'priority') {
+ 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);
+ },
+ async save(move, grouping) {
+ const entity = entities().get(move.id);
+ const property = properties().get(taskBoardPropertyId(grouping));
+
+ if (!entity || !property) {
+ throw new Error('Task or destination is no longer editable');
+ }
+
+ const canEdit = actions.canEditTask(move.id);
+ const canMove = canEdit && actions.canMoveTo(grouping, move.toLane);
+
+ if (!canMove) {
+ throw new Error('Task or destination is no longer editable');
+ }
+
+ await save.mutateAsync({
+ properties: [
+ {
+ entityId: entity.id,
+ entityType: 'TASK',
+ property,
+ apiValues: taskBoardMoveValue(entity, grouping, move),
+ },
+ ],
+ });
+ },
+ };
+
+ const property = (id: string, definitionId: string): Property | undefined => {
+ const entity = entities().get(id);
+
+ if (!entity) {
+ return undefined;
+ }
+
+ const definition = properties().get(definitionId);
+ const existing = entity.properties?.find(
+ (item) => item.definition.id === definitionId
+ );
+
+ if (existing) {
+ const value = soupPropertyToProperty(existing);
+
+ return { ...value, options: definition?.options ?? value.options };
+ }
+
+ if (!definition || definition.valueType === 'TAG') {
+ return undefined;
+ }
+
+ return {
+ propertyId: `${id}:${definitionId}`,
+ propertyDefinitionId: definitionId,
+ displayName: definition.displayName,
+ isMultiSelect: definition.isMultiSelect,
+ isMetadata: definition.isMetadata,
+ isSystemProperty: definition.isSystem,
+ isRequired: definitionId === SYSTEM_PROPERTY_IDS.STATUS,
+ owner: definition.owner,
+ specificEntityType: definition.specificEntityType,
+ createdAt: definition.createdAt,
+ updatedAt: definition.updatedAt,
+ options: definition.options,
+ valueType: definition.valueType,
+ value: null,
+ };
+ };
+
+ const saveProperty = async (
+ id: string,
+ value: Property,
+ apiValues: PropertyApiValues
+ ) => {
+ const definition = properties().get(value.propertyDefinitionId);
+
+ if (!actions.canEditTask(id) || !definition || definition.isMetadata) {
+ throw new Error('Task is no longer editable');
+ }
+
+ setPropertySaving((ids) => new Set([...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 ?? []) {
+ const detail = await queryClient.ensureQueryData(
+ projectDetailQueryOptions(
+ initiativeClient,
+ options.userId(),
+ ref.entity_id
+ )
+ );
+
+ if (!canEditProject(detail.project)) {
+ throw new Error('Project is not editable');
+ }
+ }
+ }
+
+ if (!entities().has(id) || !editableTasks().has(id)) {
+ throw new Error('Task is no longer editable');
+ }
+
+ await save.mutateAsync({
+ properties: [
+ { entityId: id, entityType: 'TASK', property: definition, apiValues },
+ ],
+ });
+ } finally {
+ setPropertySaving(
+ (ids) => new Set([...ids].filter((pendingId) => pendingId !== id))
+ );
+ }
+ };
+
+ return {
+ actions,
+ columns,
+ compareTasks: (left: string, right: string) =>
+ (ranks().get(left) ?? Infinity) - (ranks().get(right) ?? Infinity),
+ hiddenColumnCount: () => allColumns().length - rawColumns().length,
+ task: (id: string) => {
+ const entity = entities().get(id);
+
+ return entity ? toBoardTask(entity) : undefined;
+ },
+ entity: (id: string) => entities().get(id),
+ property,
+ saveProperty,
+ canEditProperty: (id: string, definitionId: string) => {
+ const definition = properties().get(definitionId);
+
+ if (!actions.canEditTask(id) || !definition) {
+ return false;
+ }
+
+ return !definition.isMetadata;
+ },
+ definitionError: () => definitions.isError,
+ retryDefinitions: async () => {
+ await definitions.refetch();
+ },
+ };
+}
diff --git a/apps/web/src/features/tasks-view/queries/task-board.test.ts b/apps/web/src/features/tasks-view/queries/task-board.test.ts
new file mode 100644
index 0000000000..dee8a355a9
--- /dev/null
+++ b/apps/web/src/features/tasks-view/queries/task-board.test.ts
@@ -0,0 +1,118 @@
+import {
+ createSoupEntityRow,
+ createSoupGroupHeaderRow,
+ createSoupLoadMoreRow,
+} from '@app/features/soup/collection/rows';
+import { PROPERTY_OPTION_IDS } from '@property/constants';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import { describe, expect, it } from 'vitest';
+import { boardEntity, boardProperty } from '../tests/task-board-fixture';
+import {
+ filterTaskBoardColumns,
+ taskBoardColumns,
+ taskBoardMoveValue,
+} from './task-board';
+
+describe('board query projection', () => {
+ it('restricts server groups and pagination to selected statuses', () => {
+ const allowed = PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS;
+ const excluded = PROPERTY_OPTION_IDS.STATUS.COMPLETED;
+ const rows = [
+ createSoupGroupHeaderRow({ id: excluded, label: 'Completed', count: 10 }),
+ createSoupEntityRow(boardEntity('hidden'), { groupId: excluded }),
+ createSoupLoadMoreRow({ scopeId: excluded, groupId: excluded }),
+ createSoupGroupHeaderRow({
+ id: allowed,
+ label: 'In progress',
+ count: 23,
+ }),
+ createSoupEntityRow(boardEntity('visible'), { groupId: allowed }),
+ createSoupEntityRow(boardEntity('second'), { groupId: allowed }),
+ createSoupLoadMoreRow({
+ scopeId: allowed,
+ groupId: allowed,
+ isLoading: true,
+ }),
+ ];
+
+ const columns = filterTaskBoardColumns(
+ taskBoardColumns(rows, 'status', false),
+ 'status',
+ { status: ['in-progress'] }
+ );
+
+ expect(columns.map((column) => column.id)).toEqual([allowed]);
+ expect(columns[0]).toMatchObject({
+ count: 23,
+ hasMore: true,
+ loadingMore: true,
+ tasks: [{ id: 'visible' }, { id: 'second' }],
+ });
+ });
+
+ it('deduplicates multi-assignee search placements and preserves hit order when filtering', () => {
+ const first = boardEntity('first', [
+ boardProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {
+ type: 'EntityReference',
+ value: [
+ { entity_id: 'alice', entity_type: 'USER' },
+ { entity_id: 'bob', entity_type: 'USER' },
+ ],
+ }),
+ ]);
+ const rows = [
+ createSoupEntityRow(first),
+ createSoupEntityRow(first),
+ createSoupEntityRow(
+ boardEntity('second', [
+ boardProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {
+ type: 'EntityReference',
+ value: [{ entity_id: 'bob', entity_type: 'USER' }],
+ }),
+ ])
+ ),
+ ];
+ const columns = taskBoardColumns(rows, 'assignee', true);
+
+ expect(
+ columns.find((column) => column.id === 'alice')?.tasks
+ ).toMatchObject([{ id: 'first' }]);
+ expect(columns.find((column) => column.id === 'bob')).toMatchObject({
+ count: undefined,
+ tasks: [{ id: 'first' }, { id: 'second' }],
+ });
+ expect(
+ filterTaskBoardColumns(columns, 'assignee', {
+ assignees: ['bob'],
+ }).map((column) => column.id)
+ ).toEqual(['bob']);
+ });
+});
+
+describe('board property writes', () => {
+ const entity = boardEntity('task', [
+ boardProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {
+ type: 'EntityReference',
+ value: [
+ { entity_id: 'alice', entity_type: 'USER' },
+ { entity_id: 'agent', entity_type: 'USER' },
+ ],
+ }),
+ ]);
+
+ it('preserves other assignees when replacing one', () => {
+ expect(
+ taskBoardMoveValue(entity, 'assignee', {
+ id: 'task',
+ fromLane: 'alice',
+ toLane: 'bob',
+ })
+ ).toEqual({
+ valueType: 'ENTITY',
+ refs: [
+ { entity_id: 'agent', entity_type: 'USER' },
+ { entity_id: 'bob', entity_type: 'USER' },
+ ],
+ });
+ });
+});
diff --git a/apps/web/src/features/tasks-view/queries/task-board.ts b/apps/web/src/features/tasks-view/queries/task-board.ts
new file mode 100644
index 0000000000..bb5fce52fe
--- /dev/null
+++ b/apps/web/src/features/tasks-view/queries/task-board.ts
@@ -0,0 +1,250 @@
+import type { FacetSelection } from '@app/features/soup';
+import type { TaskEntityWithProperties } from '@entity/types/entity';
+import {
+ getTaskPriorityOptionId,
+ getTaskReferencedEntityIds,
+ getTaskStatusOptionId,
+ TASK_PRIORITY_OPTIONS,
+ TASK_STATUS_OPTIONS,
+} from '@entity/utils/task-properties';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import type { PropertyApiValues } from '@property/types';
+import {
+ moveTaskAssignees,
+ type TaskBoardColumn,
+ type TaskBoardGrouping,
+ type TaskBoardMove,
+ type TaskBoardTask,
+ taskBoardGroupKeys,
+} from '../core/task-board';
+import {
+ EMPTY_TASK_FACET_CONTEXT,
+ getTaskFacetOption,
+} from '../filters/task-facets';
+import type { TasksDataSourceItem } from './use-tasks-query';
+
+const BOARD_PROPERTY_IDS = {
+ status: SYSTEM_PROPERTY_IDS.STATUS,
+ priority: SYSTEM_PROPERTY_IDS.PRIORITY,
+ assignee: SYSTEM_PROPERTY_IDS.ASSIGNEES,
+ project: SYSTEM_PROPERTY_IDS.PROJECT,
+};
+
+export function taskBoardPropertyId(grouping: TaskBoardGrouping): string {
+ return BOARD_PROPERTY_IDS[grouping];
+}
+
+export function toBoardTask(task: TaskEntityWithProperties): TaskBoardTask {
+ return {
+ id: task.id,
+ name: task.name,
+ statusId: getTaskStatusOptionId(task),
+ priorityId: getTaskPriorityOptionId(task),
+ // Include both people and agent assignees. Their original reference types are retained on writes.
+ assigneeIds: getTaskReferencedEntityIds(
+ task,
+ SYSTEM_PROPERTY_IDS.ASSIGNEES
+ ),
+ projectIds: getTaskReferencedEntityIds(task, SYSTEM_PROPERTY_IDS.PROJECT),
+ };
+}
+
+export function taskBoardFacetId(grouping: TaskBoardGrouping): string {
+ return grouping === 'assignee' ? 'assignees' : grouping;
+}
+
+function allowedBoardColumns(
+ grouping: TaskBoardGrouping,
+ facets: FacetSelection
+) {
+ const facetId = taskBoardFacetId(grouping);
+ const selected = facets[facetId] ?? [];
+ const columnIds = selected.flatMap((id) => {
+ if (id === '' || grouping === 'project') {
+ return [id];
+ }
+
+ const option = getTaskFacetOption(facetId, id, EMPTY_TASK_FACET_CONTEXT);
+
+ if (!option) {
+ return [];
+ }
+
+ if (grouping === 'assignee') {
+ return [option.propertyEntityId ?? id];
+ }
+
+ return option.propertyOptionId ? [option.propertyOptionId] : [];
+ });
+
+ return new Set(columnIds);
+}
+
+export function filterTaskBoardColumns(
+ columns: readonly TaskBoardColumn[],
+ grouping: TaskBoardGrouping,
+ facets: FacetSelection
+): TaskBoardColumn[] {
+ const allowedColumnIds = allowedBoardColumns(grouping, facets);
+
+ return columns.filter((column) => {
+ return allowedColumnIds.size === 0 || allowedColumnIds.has(column.id);
+ });
+}
+
+/** The query owns pagination and membership; the board never regroups a partial normal page. */
+export function taskBoardColumns(
+ rows: readonly TasksDataSourceItem[],
+ grouping: TaskBoardGrouping,
+ searching: boolean
+): TaskBoardColumn[] {
+ const columns = new Map<
+ string,
+ Omit<TaskBoardColumn, 'tasks'> & { tasks: TaskBoardTask[] }
+ >();
+
+ const addColumn = (id: string, label: string) => {
+ let column = columns.get(id);
+
+ if (column) {
+ return column;
+ }
+
+ column = {
+ id,
+ label,
+ tasks: [],
+ count: searching ? undefined : 0,
+ hasMore: false,
+ loadingMore: false,
+ };
+ columns.set(id, column);
+
+ return column;
+ };
+
+ const options = {
+ status: TASK_STATUS_OPTIONS,
+ priority: TASK_PRIORITY_OPTIONS,
+ assignee: [],
+ project: [],
+ }[grouping];
+
+ for (const option of options) {
+ addColumn(option.value, option.label);
+ }
+
+ addColumn(
+ '',
+ {
+ status: 'No status',
+ priority: 'No priority',
+ assignee: 'Unassigned',
+ project: 'No project',
+ }[grouping]
+ );
+
+ for (const row of rows) {
+ if (row.kind !== 'group-header') {
+ continue;
+ }
+
+ const column = addColumn(row.groupId, row.label);
+
+ column.count = row.count;
+ }
+
+ const seen = new Map<string, Set<string>>();
+
+ for (const row of rows) {
+ if (row.kind === 'load-more' && row.groupId !== undefined) {
+ const column = columns.get(row.groupId);
+
+ if (column) {
+ column.hasMore = true;
+ column.loadingMore = !!row.isLoading;
+ }
+ }
+
+ if (row.kind !== 'entity') {
+ continue;
+ }
+
+ const task = toBoardTask(row.entity);
+ const keys =
+ searching || row.groupId === undefined
+ ? taskBoardGroupKeys(task, grouping)
+ : [row.groupId];
+
+ for (const key of keys) {
+ const column = addColumn(key, key || 'Not set');
+
+ const ids = seen.get(key) ?? new Set<string>();
+ seen.set(key, ids);
+
+ if (ids.has(task.id)) {
+ continue;
+ }
+
+ ids.add(task.id);
+ column.tasks.push(task);
+ }
+ }
+
+ return [...columns.values()].map((column) => ({
+ ...column,
+ count:
+ column.count === undefined
+ ? undefined
+ : Math.max(column.count, column.tasks.length),
+ }));
+}
+
+/** Preserve untouched assignees and their wire reference types. */
+export function taskBoardMoveValue(
+ entity: TaskEntityWithProperties,
+ grouping: TaskBoardGrouping,
+ move: TaskBoardMove
+): PropertyApiValues {
+ if (grouping === 'status' || grouping === 'priority') {
+ return {
+ valueType: 'SELECT_STRING',
+ values: move.toLane ? [move.toLane] : null,
+ };
+ }
+
+ if (grouping === 'project') {
+ return {
+ valueType: 'ENTITY',
+ refs: move.toLane
+ ? [{ entity_id: move.toLane, entity_type: 'INITIATIVE' }]
+ : null,
+ };
+ }
+
+ const property = entity.properties?.find(
+ (property) => property.definition.id === SYSTEM_PROPERTY_IDS.ASSIGNEES
+ );
+ const refs =
+ property?.value?.type === 'EntityReference' &&
+ Array.isArray(property.value.value)
+ ? property.value.value
+ : [];
+ const nextIds = moveTaskAssignees(
+ toBoardTask(entity).assigneeIds,
+ move.fromLane,
+ move.toLane
+ );
+
+ if (nextIds.length === 0) {
+ return { valueType: 'ENTITY', refs: null };
+ }
+
+ const nextRefs = nextIds.map((id) => {
+ const existing = refs.find((ref) => ref.entity_id === id);
+
+ return existing ?? { entity_id: id, entity_type: 'USER' as const };
+ });
+
+ return { valueType: 'ENTITY', refs: nextRefs };
+}
diff --git a/apps/web/src/features/tasks-view/queries/task-query.test.ts b/apps/web/src/features/tasks-view/queries/task-query.test.ts
index 1b88868a73..d54f4063c2 100644
--- a/apps/web/src/features/tasks-view/queries/task-query.test.ts
+++ b/apps/web/src/features/tasks-view/queries/task-query.test.ts
@@ -53,3 +53,25 @@ describe('task reference scope', () => {
]);
});
});
+
+it('uses the initiative Project property for board columns without changing legacy list grouping', () => {
+ const boardQuery = buildTaskQuery({
+ ...options,
+ groupBy: 'project',
+ board: true,
+ });
+ const listQuery = buildTaskQuery({ ...options, groupBy: 'project' });
+ const sortedBoardQuery = buildTaskQuery({ ...options, board: true });
+
+ expect(boardQuery.groupBy).toEqual({
+ type: 'property',
+ propertyDefinitionId: '00000001-0000-0000-0000-000000000014',
+ });
+ expect(listQuery.groupBy).toEqual({
+ type: 'project',
+ });
+ expect(sortedBoardQuery.params).toMatchObject({
+ sort_method: 'updated_at',
+ sort_direction: 'asc',
+ });
+});
diff --git a/apps/web/src/features/tasks-view/queries/task-query.ts b/apps/web/src/features/tasks-view/queries/task-query.ts
index 07ea73638d..035cd292f5 100644
--- a/apps/web/src/features/tasks-view/queries/task-query.ts
+++ b/apps/web/src/features/tasks-view/queries/task-query.ts
@@ -113,6 +113,8 @@ export type BuildTaskQueryOptions = {
sort: SortSelection<TaskSortId>[];
/** Only tasks whose property references this entity. */
reference?: TaskReferenceScope;
+ /** Board Project columns use the initiative property, not legacy folders. */
+ board?: boolean;
};
/** Builds the concrete Soup AST used only by the production Tasks view. */
@@ -160,6 +162,12 @@ export function buildTaskQuery(
sort_direction: sortDirection,
},
body,
- groupBy: taskGroupByField(options.groupBy),
+ groupBy:
+ options.board && options.groupBy === 'project'
+ ? {
+ type: 'property',
+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.PROJECT,
+ }
+ : taskGroupByField(options.groupBy),
};
}
diff --git a/apps/web/src/features/tasks-view/queries/use-tasks-query.test.ts b/apps/web/src/features/tasks-view/queries/use-tasks-query.test.ts
index c44110ee46..e08af089c8 100644
--- a/apps/web/src/features/tasks-view/queries/use-tasks-query.test.ts
+++ b/apps/web/src/features/tasks-view/queries/use-tasks-query.test.ts
@@ -125,7 +125,7 @@ it.each([false, true])(
}
);
-it('retains cached rows while a referenced list refetches and hides them when disabled', () => {
+it('retains referenced list rows but hides stale board groups and inaccessible tasks', () => {
const [placeholder, setPlaceholder] = createSignal(false);
const [enabled, setEnabled] = createSignal(true);
const task = {
@@ -177,13 +177,16 @@ it('retains cached rows while a referenced list refetches and hides them when di
}
);
expect(source.items()).toHaveLength(1);
+ expect(source.boardRows?.()).toHaveLength(1);
expect(source.isLoading()).toBe(false);
setPlaceholder(true);
expect(source.items()).toHaveLength(1);
+ expect(source.boardRows?.()).toEqual([]);
expect(source.isLoading()).toBe(false);
setPlaceholder(false);
setEnabled(false);
expect(source.items()).toEqual([]);
+ expect(source.boardRows?.()).toEqual([]);
expect(source.isLoading()).toBe(false);
} finally {
dispose();
@@ -191,60 +194,125 @@ it('retains cached rows while a referenced list refetches and hides them when di
});
});
-it('scopes grouped load-more pages to the referenced entity', () => {
- const companies = 'companies-definition';
- const task = (id: string, companyId: string) =>
- ({
- type: 'document',
- fileType: 'md',
- id,
- name: id,
- ownerId: 'viewer',
- createdAt: new Date(),
- updatedAt: new Date(),
- subType: { type: 'task', is_completed: false },
- properties: [
- {
- definition: { id: companies },
- value: {
- type: 'EntityReference',
- value: [{ entity_type: 'COMPANY', entity_id: companyId }],
+it.each([false, true])(
+ 'scopes grouped continuation rows to the referenced entity (board: %s)',
+ (board) => {
+ const companies = 'companies-definition';
+ const task = (id: string, companyId: string) =>
+ ({
+ type: 'document',
+ fileType: 'md',
+ id,
+ name: id,
+ ownerId: 'viewer',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ subType: { type: 'task', is_completed: false },
+ properties: [
+ {
+ definition: { id: companies },
+ value: {
+ type: 'EntityReference',
+ value: [{ entity_type: 'COMPANY', entity_id: companyId }],
+ },
},
+ ],
+ }) as unknown as TaskEntityWithProperties;
+ fixture.query = {
+ isLoading: false,
+ isPlaceholderData: false,
+ data: {
+ entities: [],
+ itemsById: {},
+ groups: [
+ {
+ key: 'todo',
+ label: 'To do',
+ displayOrder: 0,
+ totalCount: 2,
+ itemIds: [],
+ nextCursor: 'next',
+ },
+ ],
+ },
+ };
+ // A "Load more" page holding one task that no longer references Acme.
+ fixture.groupQueries = new Map([
+ [
+ 'todo',
+ {
+ data: () => ({
+ entities: [task('linked', 'acme'), task('unlinked', 'globex')],
+ }),
+ hasNextPage: () => false,
+ isFetchingNextPage: () => false,
+ fetchNextPage: async () => {},
},
],
- }) as unknown as TaskEntityWithProperties;
+ ]);
+ createRoot((dispose) => {
+ try {
+ const source = useTasksDataSource(
+ {
+ tab: 'team-tasks',
+ search: '',
+ facets: {},
+ groupBy: 'status',
+ sort: [],
+ },
+ {
+ userId: () => 'viewer',
+ tagSets: () => [],
+ tagSetsReady: () => true,
+ isGroupExpanded: () => !board,
+ board: () => board,
+ reference: () => ({
+ propertyDefinitionId: companies,
+ entityId: 'acme',
+ }),
+ }
+ );
+ const rows = board ? source.boardRows?.() : source.items();
+ expect(
+ rows?.flatMap((row) => (row.kind === 'entity' ? [row.entity.id] : []))
+ ).toEqual(['linked']);
+ } finally {
+ dispose();
+ fixture.groupQueries = new Map();
+ }
+ });
+ }
+);
+
+it('exposes uncollapsed board rows and hides stale groups during query changes', () => {
+ const [pending, setPending] = createSignal(false);
+ const task: TaskEntityWithProperties = {
+ type: 'document',
+ fileType: 'md',
+ id: 'task',
+ name: 'Task',
+ ownerId: 'viewer',
+ subType: { type: 'task', is_completed: false },
+ properties: [],
+ };
+
fixture.query = {
- isLoading: false,
- isPlaceholderData: false,
+ get isPending() {
+ return pending();
+ },
+ get isLoading() {
+ return pending();
+ },
data: {
- entities: [],
+ entities: [task],
itemsById: {},
groups: [
- {
- key: 'todo',
- label: 'To do',
- displayOrder: 0,
- totalCount: 2,
- itemIds: [],
- nextCursor: 'next',
- },
+ { key: 'todo', label: 'To do', totalCount: 1, itemIds: ['task'] },
],
},
};
- // A "Load more" page holding one task that no longer references Acme.
- fixture.groupQueries = new Map([
- [
- 'todo',
- {
- data: () => ({
- entities: [task('linked', 'acme'), task('unlinked', 'globex')],
- }),
- hasNextPage: () => false,
- isFetchingNextPage: () => false,
- fetchNextPage: async () => {},
- },
- ],
- ]);
+ fixture.groupQueries = new Map();
+
createRoot((dispose) => {
try {
const source = useTasksDataSource(
@@ -259,21 +327,30 @@ it('scopes grouped load-more pages to the referenced entity', () => {
userId: () => 'viewer',
tagSets: () => [],
tagSetsReady: () => true,
- isGroupExpanded: () => true,
- reference: () => ({
- propertyDefinitionId: companies,
- entityId: 'acme',
- }),
+ isGroupExpanded: () => false,
+ board: () => true,
}
);
+
+ expect(
+ source.items().filter((row) => row.kind === 'entity')
+ ).toHaveLength(0);
+ expect(
+ source.boardRows?.().filter((row) => row.kind === 'entity')
+ ).toHaveLength(1);
+
+ setPending(true);
+
+ expect(source.boardRows?.()).toEqual([]);
+ expect(source.boardLoading?.()).toBe(true);
+
+ setPending(false);
+
expect(
- source
- .items()
- .flatMap((row) => (row.kind === 'entity' ? [row.entity.id] : []))
- ).toEqual(['linked']);
+ source.boardRows?.().filter((row) => row.kind === 'entity')
+ ).toHaveLength(1);
} finally {
dispose();
- fixture.groupQueries = new Map();
}
});
});
diff --git a/apps/web/src/features/tasks-view/queries/use-tasks-query.ts b/apps/web/src/features/tasks-view/queries/use-tasks-query.ts
index e9861ea6d7..b07b9496a0 100644
--- a/apps/web/src/features/tasks-view/queries/use-tasks-query.ts
+++ b/apps/web/src/features/tasks-view/queries/use-tasks-query.ts
@@ -53,6 +53,7 @@ export type UseTasksDataSourceOptions = {
networkPaused?: Accessor<boolean>;
/** Project lists drain all cursors instead of requiring per-group Load More. */
loadAll?: boolean;
+ board?: Accessor<boolean>;
};
export type TasksDataSourceItem = SoupRow<TaskEntityWithProperties>;
@@ -61,6 +62,11 @@ export type TasksDataSource = ListDataSource<TasksDataSourceItem> & {
loadMoreGroup: (groupId: string) => Promise<void>;
paginationError?: Accessor<unknown>;
retryPagination?: () => void;
+ /** Uncollapsed rows for alternative layouts; the query owner is shared. */
+ boardRows?: Accessor<TasksDataSourceItem[]>;
+ boardSearching?: Accessor<boolean>;
+ boardLoading?: Accessor<boolean>;
+ groupError?: (groupId: string) => unknown;
};
type TaskGroupContinuationReader = {
@@ -106,6 +112,7 @@ export function useTasksDataSource(
groupBy: state.groupBy,
sort: state.sort,
reference: options.reference?.(),
+ board: options.board?.(),
});
const scoped = Boolean(options.reference);
@@ -407,8 +414,40 @@ export function useTasksDataSource(
await query.refresh();
};
+ const boardRows = () => {
+ if (options.enabled?.() === false) {
+ return [];
+ }
+
+ if (search.isSearching()) {
+ return rows();
+ }
+
+ if (query.isPending || query.isPlaceholderData) {
+ return [];
+ }
+
+ return rows();
+ };
+
+ const boardLoading = () => {
+ if (search.isSearching()) {
+ return isLoading();
+ }
+
+ if (options.enabled?.() === false) {
+ return false;
+ }
+
+ return query.isPending || !facetOptionsReady();
+ };
+
return {
items,
+ boardRows,
+ boardLoading,
+ groupError: (id) => groupQueryFor(id)?.error(),
+ boardSearching: search.isSearching,
isLoading,
isFetching,
error,
diff --git a/apps/web/src/features/tasks-view/tasks-board.tsx b/apps/web/src/features/tasks-view/tasks-board.tsx
new file mode 100644
index 0000000000..bc451162ca
--- /dev/null
+++ b/apps/web/src/features/tasks-view/tasks-board.tsx
@@ -0,0 +1,61 @@
+import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { useUserId } from '@core/context/user';
+import { usePropertyUserDisplay } from '@property/hooks/usePropertyUserDisplay';
+import type { Accessor } from 'solid-js';
+import { toTaskBoardGrouping } from './core/task-board';
+import { createTaskBoardQueries } from './queries/task-board-queries';
+import { useTasksView } from './tasks-view-context';
+import { TaskBoardView } from './views/task-board-view';
+
+/** Connects the task view to query adapters and app navigation. */
+export function TasksBoard(props: { ref?: (element: HTMLDivElement) => void }) {
+ const { state, source, openTask, projectsEnabled } = useTasksView();
+ const panel = useSplitPanelOrThrow();
+ const queries = createTaskBoardQueries({
+ rows: source.boardRows ?? source.items,
+ grouping: () => toTaskBoardGrouping(state.groupBy),
+ searching: source.boardSearching ?? (() => !!state.search.trim()),
+ userId: useUserId(),
+ projectsEnabled,
+ facets: () => state.facets,
+ sort: () => state.sort,
+ });
+ const data = {
+ ...queries,
+ createAssigneeName: (id: Accessor<string>) =>
+ usePropertyUserDisplay(id).name,
+ };
+
+ return (
+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
+ <TaskBoardView
+ ref={props.ref}
+ data={data}
+ onOpen={(task, event) => {
+ const opened = openTask(
+ { id: task.id, fallbackName: task.name },
+ { event }
+ );
+
+ if (opened) {
+ return;
+ }
+
+ const entity = data.entity(task.id);
+
+ if (!entity) {
+ return;
+ }
+
+ void openEntityInSplitFromUnifiedList(entity, {
+ splitHandle: panel.handle,
+ referredFrom: 'tasks',
+ openInNewSplit:
+ event.shiftKey || event.metaKey || event.ctrlKey || event.altKey,
+ });
+ }}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/tasks-view/tasks-content.tsx b/apps/web/src/features/tasks-view/tasks-content.tsx
new file mode 100644
index 0000000000..a811aa0b14
--- /dev/null
+++ b/apps/web/src/features/tasks-view/tasks-content.tsx
@@ -0,0 +1,31 @@
+import SpinnerIcon from '@phosphor/spinner.svg';
+import { Show, Suspense } from 'solid-js';
+import { TaskList } from './components/task-list/TaskList';
+import { TasksBoard } from './tasks-board';
+import { useTasksView } from './tasks-view-context';
+
+export function TasksLoading() {
+ return (
+ <div class="grid size-full min-h-0 min-w-0 place-items-center text-ink-muted">
+ <SpinnerIcon aria-label="Loading tasks" class="size-5 animate-spin" />
+ </div>
+ );
+}
+
+/** Renders either layout from the host's task scope and navigation capabilities. */
+export function TasksContent(props: {
+ ref?: (element: HTMLDivElement) => void;
+}) {
+ const { state } = useTasksView();
+
+ return (
+ <Suspense fallback={<TasksLoading />}>
+ <Show
+ when={state.layout === 'board'}
+ fallback={<TaskList ref={props.ref} />}
+ >
+ <TasksBoard ref={props.ref} />
+ </Show>
+ </Suspense>
+ );
+}
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 0948ecb502..c5dc099c44 100644
--- a/apps/web/src/features/tasks-view/tasks-tab-search.ts
+++ b/apps/web/src/features/tasks-view/tasks-tab-search.ts
@@ -1,13 +1,32 @@
import { createSearchParamsCodec } from '@app/lib/split-router';
import { z } from 'zod';
-import type { TasksTab } from './types';
+import type {
+ TaskGroupBy,
+ TaskSortId,
+ TasksTab,
+ TasksViewState,
+} from './types';
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(),
+ sort: z.enum(['updated_at', 'created_at', 'viewed_at']).optional(),
+ sortReversed: z.enum(['true', 'false']).optional(),
+ groupBy: z
+ .enum(['none', 'status', 'priority', 'assignee', 'project', 'date'])
+ .optional(),
}),
- defaults: { tab: 'my-tasks' as TasksTab },
+ defaults: {
+ tab: 'my-tasks' as TasksTab,
+ layout: undefined as TasksViewState['layout'] | undefined,
+ sort: undefined as TaskSortId | undefined,
+ sortReversed: undefined as 'true' | 'false' | undefined,
+ groupBy: undefined as TaskGroupBy | undefined,
+ },
};
export const tasksTabSearchCodec = createSearchParamsCodec(tasksTabSearch);
+
+export type TasksTabSearchParams = z.infer<typeof tasksTabSearch.schema>;
diff --git a/apps/web/src/features/tasks-view/tasks-view-context.test.tsx b/apps/web/src/features/tasks-view/tasks-view-context.test.tsx
deleted file mode 100644
index 7a6fd5dd28..0000000000
--- a/apps/web/src/features/tasks-view/tasks-view-context.test.tsx
+++ /dev/null
@@ -1,333 +0,0 @@
-import { createOwnedSlots } from '@components/app/split-layout/utils/createOwnedSlots';
-import { cleanup, render, screen } from '@solidjs/testing-library';
-import { createRoot, createSignal, For, onCleanup, Show } from 'solid-js';
-import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { TasksMobileTabs } from './components/TasksMobileTabs';
-import { TaskListHeader } from './components/task-list/TaskListHeader';
-import type { TasksDataSource } from './queries/use-tasks-query';
-import {
- type TasksViewContext,
- TasksViewProvider,
- useTasksView,
-} from './tasks-view-context';
-
-const mocks = vi.hoisted(() => ({
- replace: undefined as (<T>(name: string, factory: () => T) => T) | undefined,
- routeTab: 'my-tasks',
- captured: {} as Record<string, unknown>,
- captors: new Map<string, () => unknown>(),
- projectsEnabled: (() => true) as () => boolean,
- touch: false,
- dockOpen: (): boolean => false,
- dockText: (): string => '',
-}));
-vi.mock('@app/lib/split-router', () => ({
- useNavigate: () => vi.fn(),
- useParams: () => ({}),
- createSearchParams: () => [
- {
- get tab() {
- return mocks.routeTab;
- },
- },
- ],
-}));
-vi.mock('./tasks-tab-search', () => ({
- tasksTabSearch: {},
- tasksTabSearchCodec: { serialize: () => ({}) },
-}));
-vi.mock('@app/routes/routes', () => ({
- taskDetailRoute: {},
- tasksProjectsRoute: {},
- tasksSplitRoute: {},
- reviewsSplitRoute: {},
-}));
-vi.mock('@app/lib/analytics/posthog', () => ({
- useFeatureFlag: () => () => ({ enabled: mocks.projectsEnabled() }),
-}));
-vi.mock('@components/app/mobile/PillTabs', () => ({
- PillTabs: (props: { items: { label: string }[] }) => (
- <nav aria-label="Task tabs">
- <For each={props.items}>{(item) => <span>{item.label}</span>}</For>
- </nav>
- ),
-}));
-vi.mock('./components/TasksFilterDrawer', () => ({
- TasksFilterDrawer: () => null,
-}));
-vi.mock('@ui', () => ({
- cn: (...values: unknown[]) => values.filter(Boolean).join(' '),
-}));
-vi.mock('@components/app/split-layout/layoutUtils', () => {
- const panel = {
- handle: {
- isActive: () => true,
- currentEntryState: () => mocks.captured,
- registerEntryStateCaptor: (key: string, getter: () => unknown) => {
- mocks.captors.set(key, getter);
- return () => {
- if (mocks.captors.get(key) === getter) mocks.captors.delete(key);
- };
- },
- captureEntryState: () => {
- for (const [key, getter] of mocks.captors)
- mocks.captured[key] = getter();
- },
- },
- };
- return {
- useSplitPanel: () => panel,
- useSplitPanelOrThrow: () => panel,
- withSplitPanelOwner: (key: string, factory: () => unknown) =>
- mocks.replace!(key, factory),
- };
-});
-vi.mock('@components/app/createPreviewSelectionGuard', () => ({
- createPreviewSelectionGuard: () =>
- Object.assign(() => true, { canSelect: () => true }),
-}));
-vi.mock('@core/mobile/isTouchDevice', () => ({
- isTouchDevice: () => mocks.touch,
-}));
-vi.mock('@app/features/command/mobile/mobileSearchState', () => ({
- SearchState: {
- isOpen: () => mocks.dockOpen(),
- query: () => mocks.dockText(),
- },
-}));
-vi.mock('@app/components/view-shell', () => ({
- setSidebarSectionCollapsed: () => [],
- createCollapsedSidebarSectionsStorage: () => ({
- restore: () => undefined,
- write: () => {},
- }),
-}));
-vi.mock('@app/features/soup', () => ({
- normalizeFacetSelection: (value: unknown) => value,
-}));
-vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user' }));
-vi.mock('@property/tags/tag-sets-context', () => ({
- useTagSets: () => () => [],
- useTagSetsReady: () => () => true,
-}));
-vi.mock('./constants', () => ({
- TASK_DEFAULT_GROUP_BY: {
- 'team-tasks': 'status',
- 'my-tasks': 'priority',
- projects: 'status',
- },
- TASK_TABS: [
- { id: 'my-tasks', label: 'My tasks' },
- { id: 'projects', label: 'Projects' },
- ],
-}));
-vi.mock('./filters/task-facets', () => ({ DEFAULT_TASK_FACET_SELECTION: {} }));
-vi.mock('./queries/use-tasks-query', () => ({
- useTasksDataSource: () => {
- throw new Error('must use project source');
- },
-}));
-
-let disposeSlots: () => void;
-beforeEach(() => {
- mocks.routeTab = 'my-tasks';
- mocks.touch = false;
- mocks.dockOpen = () => false;
- mocks.dockText = () => '';
- mocks.captured = {};
- mocks.captors.clear();
- mocks.projectsEnabled = () => true;
- createRoot((dispose) => {
- disposeSlots = dispose;
- mocks.replace = createOwnedSlots().replace;
- });
-});
-afterEach(() => {
- cleanup();
- disposeSlots();
-});
-
-it('restores grouping and search after task breadcrumbs and section changes using the real split resource lifecycle', () => {
- const activated = [vi.fn(), vi.fn(), vi.fn(), vi.fn()];
- let mounts = 0;
- const disposed = vi.fn();
- const sourceFactory = vi.fn((state: { search: string }): TasksDataSource => {
- onCleanup(disposed);
- return {
- items: () => [
- { kind: 'load-more', id: `row-${state.search}`, scopeId: 'scope' },
- ],
- isLoading: () => false,
- isFetching: () => false,
- error: () => undefined,
- hasMore: () => false,
- isLoadingMore: () => false,
- loadMore: async () => {},
- loadMoreGroup: async () => {},
- refresh: async () => {},
- };
- });
- let current!: TasksViewContext;
- const [projectId, setProjectId] = createSignal('one');
- const [showTasks, updateShowTasks] = createSignal(true);
- const setShowTasks = (show: boolean) => {
- if (!show)
- for (const [key, getter] of mocks.captors) mocks.captured[key] = getter();
- updateShowTasks(show);
- };
- const Probe = () => {
- current = useTasksView();
- current.registerListActivationHandler(activated[mounts++]);
- return null;
- };
- render(() => (
- <Show when={showTasks() ? projectId() : undefined} keyed>
- {(id) => (
- <TasksViewProvider
- scopeKey={`initiative:${id}:tasks`}
- initialState={{ tab: 'team-tasks', groupBy: 'status', facets: {} }}
- restoreEntryState
- sourceFactory={sourceFactory}
- onOpenTask={() => {
- setShowTasks(false);
- return true;
- }}
- onCloseTask={() => {}}
- >
- <Probe />
- </TasksViewProvider>
- )}
- </Show>
- ));
-
- current.setState('groupBy', 'priority');
- current.setState('search', 'launch');
- current.setState('collapsedGroupIds', ['not-set']);
- const originalSource = current.source;
- current.openTask({ id: 'task' });
- setShowTasks(true);
-
- expect(current.state.groupBy).toBe('priority');
- expect(current.state.search).toBe('launch');
- expect(current.state.collapsedGroupIds).toEqual(['not-set']);
- expect(current.source).not.toBe(originalSource);
- expect(sourceFactory).toHaveBeenCalledTimes(2);
- expect(disposed).toHaveBeenCalledOnce();
- current.setState('search', 'release');
- expect(current.source.items()[0].id).toBe('row-release');
- current.list.activate.key('row-release');
- expect(activated[1]).toHaveBeenCalledOnce();
- expect(activated[0]).not.toHaveBeenCalled();
- current.setFacets({ status: ['completed'] });
- expect(showTasks()).toBe(true);
-
- setShowTasks(false);
- setShowTasks(true);
- expect(current.state.groupBy).toBe('priority');
- expect(current.state.facets).toEqual({ status: ['completed'] });
- setProjectId('two');
- expect(current.state.groupBy).toBe('status');
- expect(current.state.search).toBe('');
-});
-
-it('hides project tabs and columns while disabled without overwriting a restored Projects selection', () => {
- const [enabled, setEnabled] = createSignal(false);
- mocks.projectsEnabled = enabled;
- mocks.routeTab = 'projects';
- mocks.captured['tasks.view'] = { version: 1, tab: 'projects' };
- let current!: TasksViewContext;
- let queryState!: { tab: string };
- const sourceFactory = (state: { tab: string }): TasksDataSource => {
- queryState = state;
- return {
- items: () => [],
- isLoading: () => false,
- isFetching: () => false,
- error: () => undefined,
- hasMore: () => false,
- isLoadingMore: () => false,
- loadMore: async () => {},
- loadMoreGroup: async () => {},
- refresh: async () => {},
- };
- };
- const Probe = () => {
- current = useTasksView();
- return (
- <>
- <TasksMobileTabs />
- <TaskListHeader />
- </>
- );
- };
- render(() => (
- <TasksViewProvider sourceFactory={sourceFactory}>
- <Probe />
- </TasksViewProvider>
- ));
-
- expect(current.state.tab).toBe('my-tasks');
- expect(queryState.tab).toBe('my-tasks');
- expect(screen.queryByText('Projects')).toBeNull();
- expect(screen.queryByRole('columnheader', { name: 'Project' })).toBeNull();
- expect(mocks.captors.get('tasks.view')!()).toMatchObject({ tab: 'projects' });
- current.setTab('projects');
- expect(current.state.tab).toBe('my-tasks');
-
- setEnabled(true);
- expect(current.state.tab).toBe('projects');
- expect(queryState.tab).toBe('projects');
- expect(screen.getByText('Projects')).toBeTruthy();
- expect(screen.getByRole('columnheader', { name: 'Project' })).toBeTruthy();
-
- setEnabled(false);
- expect(current.state.tab).toBe('my-tasks');
- expect(screen.queryByText('Projects')).toBeNull();
- // Explicitly choosing the visible fallback is a real navigation preference.
- current.setTab('my-tasks');
- setEnabled(true);
- expect(current.state.tab).toBe('my-tasks');
- expect(mocks.captors.get('tasks.view')!()).toMatchObject({ tab: 'my-tasks' });
-});
-
-it.each([undefined, 'initiative:one:tasks'])(
- 'isolates dock search from saved and embedded task search (scope %s)',
- (scopeKey) => {
- mocks.touch = true;
- const [open, setOpen] = createSignal(true);
- mocks.dockOpen = open;
- mocks.dockText = () => 'dock query';
- let current!: TasksViewContext;
- const sourceFactory = (): TasksDataSource => ({
- items: () => [],
- isLoading: () => false,
- isFetching: () => false,
- error: () => undefined,
- hasMore: () => false,
- isLoadingMore: () => false,
- loadMore: async () => {},
- loadMoreGroup: async () => {},
- refresh: async () => {},
- });
- const Probe = () => {
- current = useTasksView();
- return null;
- };
- render(() => (
- <TasksViewProvider
- scopeKey={scopeKey}
- initialState={{ search: 'saved query' }}
- sourceFactory={sourceFactory}
- >
- <Probe />
- </TasksViewProvider>
- ));
- expect(current.state.search).toBe(scopeKey ? 'saved query' : 'dock query');
- current.setState('search', 'updated saved query');
- expect(current.state.search).toBe(
- scopeKey ? 'updated saved query' : 'dock query'
- );
- setOpen(false);
- expect(current.state.search).toBe('updated saved query');
- }
-);
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 084feb937f..6da25ff130 100644
--- a/apps/web/src/features/tasks-view/tasks-view-context.tsx
+++ b/apps/web/src/features/tasks-view/tasks-view-context.tsx
@@ -47,8 +47,10 @@ import {
type Store,
} from 'solid-js/store';
import { TASK_DEFAULT_GROUP_BY } from './constants';
+import { toTaskBoardGrouping } from './core/task-board';
import { DEFAULT_TASK_FACET_SELECTION } from './filters/task-facets';
import { createTasksViewPersistence } from './persistence';
+import { createTasksViewSearch } from './primitives/create-tasks-view-search';
import {
type TasksDataSource,
type TasksDataSourceItem,
@@ -68,6 +70,8 @@ export type TasksViewProviderProps = ContextProviderProps & {
initialState?: TasksViewStateOptions;
restoreEntryState?: boolean;
scopeKey?: string;
+ /** Enables URL controls for an embedded view without sharing the parent namespace. */
+ searchNamespace?: string;
sourceFactory?: (
state: Store<TasksViewState>,
options: UseTasksDataSourceOptions
@@ -129,7 +133,12 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
projectId?: string;
projectsTab?: 'projects';
}>();
- const [tabSearch] = createSearchParams(tasksTabSearch);
+ const searchNamespace = props.searchNamespace ?? tasksTabSearch.namespace;
+ const syncSearch = !props.scopeKey || !!props.searchNamespace;
+ const [tabSearch, setTabSearch] = createSearchParams({
+ ...tasksTabSearch,
+ namespace: searchNamespace,
+ });
const selectPreview = createPreviewSelectionGuard();
const userId = useUserId();
const tagSets = useTagSets();
@@ -145,6 +154,7 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
const createState = () =>
makePersistedState(
createStore<TasksViewState>({
+ layout: initial.layout ?? 'list',
tab: initialTab,
search: initial.search ?? '',
groupBy: initial.groupBy ?? TASK_DEFAULT_GROUP_BY[initialTab],
@@ -180,6 +190,14 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
get search() {
return searchText();
},
+ get groupBy() {
+ if (persistedState.layout !== 'board') {
+ return persistedState.groupBy;
+ }
+
+ const grouping = toTaskBoardGrouping(persistedState.groupBy);
+ return grouping === 'project' && !projectsEnabled() ? 'status' : grouping;
+ },
get tab(): TasksTab {
return persistedState.tab === 'projects' && !projectsEnabled()
? 'my-tasks'
@@ -187,31 +205,44 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
},
});
- const routeTab = (): TasksTab =>
- routeParams.projectId || routeParams.projectsTab
- ? 'projects'
- : tabSearch.tab;
- createEffect(
- on(routeTab, (tab) => {
- if (props.scopeKey || persistedState.tab === tab) return;
- setState(
- produce((draft) => {
- draft.tab = tab;
- draft.groupBy = TASK_DEFAULT_GROUP_BY[tab];
- draft.facets = normalizeFacetSelection(DEFAULT_TASK_FACET_SELECTION);
- draft.collapsedGroupIds = [];
- })
- );
- })
- );
+ const routeTab = (): TasksTab => {
+ if (props.scopeKey) return initialTab;
+ if (routeParams.projectId || routeParams.projectsTab) return 'projects';
+
+ return tabSearch.tab;
+ };
+ const { setState: setStateWithSearch, setPrimarySort } =
+ createTasksViewSearch({
+ state: persistedState,
+ setState,
+ search: tabSearch,
+ setSearch: setTabSearch,
+ tab: routeTab,
+ enabled: syncSearch,
+ });
+ const currentSearch = () =>
+ tasksTabSearchCodec.serialize({
+ tab: state.tab,
+ layout: state.layout,
+ sort: state.sort[0]?.id,
+ sortReversed: state.sort[0]
+ ? state.sort[0].reversed
+ ? 'true'
+ : 'false'
+ : undefined,
+ // Layout and rollout fallbacks must not overwrite the selected grouping.
+ groupBy: persistedState.groupBy,
+ });
const isGroupExpanded = (groupId: string) =>
!state.collapsedGroupIds.includes(groupId);
+
const source = withSplitPanelOwner(ownedSlot('data-source'), () =>
(props.sourceFactory ?? useTasksDataSource)(state, {
userId,
tagSets,
tagSetsReady,
isGroupExpanded,
+ board: () => state.layout === 'board',
})
);
type ActivationHandler = (
@@ -265,9 +296,7 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
},
{
search: {
- [tasksTabSearch.namespace]: tasksTabSearchCodec.serialize({
- tab: state.tab,
- }),
+ [searchNamespace]: currentSearch(),
},
}
);
@@ -283,9 +312,7 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
{ route: taskDetailRoute, params: { taskId: task.id } },
{
search: {
- [tasksTabSearch.namespace]: tasksTabSearchCodec.serialize({
- tab: state.tab,
- }),
+ [searchNamespace]: currentSearch(),
},
}
);
@@ -302,9 +329,7 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
{
replace: true,
search: {
- [tasksTabSearch.namespace]: tasksTabSearchCodec.serialize({
- tab: state.tab,
- }),
+ [searchNamespace]: currentSearch(),
},
}
);
@@ -318,9 +343,7 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
{
replace: true,
search: {
- [tasksTabSearch.namespace]: tasksTabSearchCodec.serialize({
- tab: state.tab,
- }),
+ [searchNamespace]: currentSearch(),
},
}
);
@@ -359,13 +382,6 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
setState('facets', reconcile(normalizeFacetSelection(facets)));
};
- const setPrimarySort = (id: TaskSortId) => {
- const current = state.sort[0];
- const reversed = current?.id === id ? !current.reversed : false;
-
- setState('sort', [{ id, reversed }]);
- };
-
const isSidebarSectionOpen = (id: string) =>
!state.collapsedSidebarSectionIds.includes(id);
@@ -379,7 +395,7 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
scopeKey: props.scopeKey,
state,
projectsEnabled,
- setState,
+ setState: setStateWithSearch,
selectedTask,
source,
list,
diff --git a/apps/web/src/features/tasks-view/tasks-view.tsx b/apps/web/src/features/tasks-view/tasks-view.tsx
index 5be280dec2..f77ad15d5c 100644
--- a/apps/web/src/features/tasks-view/tasks-view.tsx
+++ b/apps/web/src/features/tasks-view/tasks-view.tsx
@@ -8,7 +8,6 @@ import { useSplitLayout } from '@components/app/split-layout/layout';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { SplitPanel } from '@components/app/split-panel';
import { ListEntityMetadataQueryProvider } from '@entity';
-import SpinnerIcon from '@phosphor/spinner.svg';
import {
createSignal,
onMount,
@@ -23,7 +22,7 @@ import {
} from './components/TasksHeader';
import { TasksMobileTabs } from './components/TasksMobileTabs';
import { TasksSidebar } from './components/TasksSidebar';
-import { TaskList } from './components/task-list/TaskList';
+import { TasksContent, TasksLoading } from './tasks-content';
import { TasksViewProvider, useTasksView } from './tasks-view-context';
import { tasksTour } from './tour';
import type { TasksViewStateOptions } from './types';
@@ -33,14 +32,6 @@ export type TasksViewProps = {
initialState?: TasksViewStateOptions;
};
-function TasksListFallback() {
- return (
- <div class="grid size-full min-h-0 min-w-0 place-items-center text-ink-muted">
- <SpinnerIcon aria-label="Loading tasks" class="size-5 animate-spin" />
- </div>
- );
-}
-
function TasksViewBreadcrumbs(props: ParentProps) {
const { closeTask, selectedTask } = useTasksView();
const params = useParams<{
@@ -107,9 +98,7 @@ function TasksViewRoot() {
</ViewShell.Header>
<ViewTour tour={tasksTour} actions={<ImportLinearAction />} />
<ViewShell.Content>
- <Suspense fallback={<TasksListFallback />}>
- <TaskList ref={setListElement} />
- </Suspense>
+ <TasksContent ref={setListElement} />
</ViewShell.Content>
</>
);
@@ -127,7 +116,7 @@ function TasksViewRoot() {
<TasksSidebar />
</ViewShell.Aside>
<ViewShell.Main>
- <Suspense fallback={<TasksListFallback />}>
+ <Suspense fallback={<TasksLoading />}>
<SplitRouter.Outlet
fallback={() => (
<Show
diff --git a/apps/web/src/features/tasks-view/tests/task-board-fixture.ts b/apps/web/src/features/tasks-view/tests/task-board-fixture.ts
new file mode 100644
index 0000000000..307bd01170
--- /dev/null
+++ b/apps/web/src/features/tasks-view/tests/task-board-fixture.ts
@@ -0,0 +1,40 @@
+import type { TaskEntityWithProperties } from '@entity/types/entity';
+import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';
+
+export function boardEntity(
+ id: string,
+ properties: SoupProperty[] = []
+): TaskEntityWithProperties {
+ return {
+ id,
+ name: id,
+ ownerId: 'viewer',
+ type: 'document',
+ fileType: 'md',
+ subType: { type: 'task', is_completed: false },
+ properties,
+ };
+}
+
+export function boardProperty(
+ id: string,
+ value: SoupProperty['value'],
+ dataType: 'ENTITY' | 'SELECT_STRING' = 'ENTITY'
+): SoupProperty {
+ return {
+ id: `assignment:${id}`,
+ definition: {
+ id,
+ display_name: id,
+ data_type: dataType,
+ is_multi_select: dataType === 'ENTITY',
+ specific_entity_type: null,
+ is_metadata: false,
+ is_system: true,
+ owner: { scope: 'system' },
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ },
+ value,
+ };
+}
diff --git a/apps/web/src/features/tasks-view/types.ts b/apps/web/src/features/tasks-view/types.ts
index fef111dd40..c596e61932 100644
--- a/apps/web/src/features/tasks-view/types.ts
+++ b/apps/web/src/features/tasks-view/types.ts
@@ -25,6 +25,7 @@ export type TaskDetailTarget = {
};
export type TasksViewState = {
+ layout: 'list' | 'board';
tab: TasksTab;
search: string;
groupBy: TaskGroupBy;
diff --git a/apps/web/src/features/tasks-view/views/task-board-view.tsx b/apps/web/src/features/tasks-view/views/task-board-view.tsx
new file mode 100644
index 0000000000..d8c87a0170
--- /dev/null
+++ b/apps/web/src/features/tasks-view/views/task-board-view.tsx
@@ -0,0 +1,372 @@
+import { toast } from '@core/component/Toast/Toast';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import { hasValue } from '@property/utils/typeGuards';
+import { Button } from '@ui/components/Button';
+import { type Accessor, createSignal, For, Show, Suspense } from 'solid-js';
+import { TaskBoard } from '../components/task-board';
+import {
+ TaskBoardColumnIcon,
+ TaskBoardProperty,
+} from '../components/task-board-property';
+import { TASK_SORT_OPTIONS } from '../constants';
+import type { TaskBoardData } from '../context/task-board';
+import {
+ type TaskBoardColumn,
+ type TaskBoardGrouping,
+ type TaskBoardTask,
+ toTaskBoardGrouping,
+} from '../core/task-board';
+import { createTaskBoard } from '../primitives/create-task-board';
+import { taskBoardFacetId, taskBoardPropertyId } from '../queries/task-board';
+import { useTasksView } from '../tasks-view-context';
+
+const CARD_PROPERTY_IDS = [
+ SYSTEM_PROPERTY_IDS.PRIORITY,
+ SYSTEM_PROPERTY_IDS.DUE_DATE,
+ SYSTEM_PROPERTY_IDS.PROJECT,
+];
+
+export function TaskBoardView(props: {
+ data: TaskBoardData;
+ onOpen(task: TaskBoardTask, event: MouseEvent): void;
+ ref?: (element: HTMLDivElement) => void;
+}) {
+ const { state, source, projectsEnabled, setFacets } = useTasksView();
+ const grouping = () => toTaskBoardGrouping(state.groupBy);
+ const scope = () =>
+ JSON.stringify([
+ state.tab,
+ grouping(),
+ state.search,
+ state.facets,
+ state.sort,
+ ]);
+ const board = createTaskBoard({
+ grouping,
+ scope,
+ columns: props.data.columns,
+ task: props.data.task,
+ actions: props.data.actions,
+ compareTasks: props.data.compareTasks,
+ });
+ const [readError, setReadError] = createSignal<string>();
+ const loading = source.boardLoading ?? source.isLoading;
+ const sortLabel = () =>
+ TASK_SORT_OPTIONS.find(
+ (option) => option.id === (state.sort[0]?.id ?? 'updated_at')
+ )?.label ?? 'Updated';
+ const cardPropertyIds = () =>
+ CARD_PROPERTY_IDS.filter((id) => {
+ if (id === taskBoardPropertyId(grouping())) {
+ return false;
+ }
+
+ return id !== SYSTEM_PROPERTY_IDS.PROJECT || projectsEnabled();
+ });
+
+ const revealHiddenColumns = () => {
+ const facets = { ...state.facets };
+ delete facets[taskBoardFacetId(grouping())];
+ setFacets(facets);
+ };
+
+ const read = async (operation: () => Promise<void>) => {
+ setReadError(undefined);
+
+ try {
+ await operation();
+ } catch {
+ setReadError('Could not load tasks. Try again.');
+ }
+ };
+
+ const loadMore = async (columnId?: string) => {
+ if (columnId === undefined) {
+ await source.loadMore();
+ const error = source.error();
+
+ if (error) {
+ throw error;
+ }
+
+ return;
+ }
+
+ await source.loadMoreGroup(columnId);
+ const error = source.groupError?.(columnId);
+
+ if (error) {
+ throw error;
+ }
+ };
+
+ const renderProperty = (
+ task: Accessor<TaskBoardTask>,
+ readOnly: Accessor<boolean>,
+ id: string,
+ iconOnly: boolean,
+ includeEmpty = true
+ ) => (
+ <Show when={props.data.property(task().id, id)}>
+ {(property) => (
+ <Show when={includeEmpty || hasValue(property())}>
+ <Suspense fallback={<span class="size-6" />}>
+ <TaskBoardProperty
+ property={property()}
+ taskId={task().id}
+ canEdit={!readOnly() && props.data.canEditProperty(task().id, id)}
+ iconOnly={iconOnly}
+ onSave={async (value, apiValues) => {
+ try {
+ if (readOnly()) {
+ throw new Error('Task is no longer editable');
+ }
+
+ await props.data.saveProperty(task().id, value, apiValues);
+ } catch (error) {
+ toast.failure(
+ `Could not update ${value.displayName.toLowerCase()}`
+ );
+ throw error;
+ }
+ }}
+ />
+ </Suspense>
+ </Show>
+ )}
+ </Show>
+ );
+
+ const renderCard = (
+ task: Accessor<TaskBoardTask>,
+ readOnly: Accessor<boolean>
+ ) => (
+ <>
+ <div class="grid grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-2 p-3 pb-2">
+ <div data-kanban-no-drag class="flex shrink-0 items-center">
+ {renderProperty(task, readOnly, SYSTEM_PROPERTY_IDS.STATUS, true)}
+ </div>
+ <button
+ type="button"
+ class="min-w-0 break-words text-left text-sm font-medium leading-6 text-ink hover:underline"
+ onClick={(event) => {
+ if (event.detail > 1) {
+ return;
+ }
+
+ props.onOpen(task(), event);
+ }}
+ >
+ {task().name || 'Untitled task'}
+ </button>
+ <div data-kanban-no-drag class="flex shrink-0 items-center">
+ {renderProperty(task, readOnly, SYSTEM_PROPERTY_IDS.ASSIGNEES, true)}
+ </div>
+ </div>
+ <div class="flex flex-wrap items-center gap-1 px-3 pb-3 text-xs text-ink-muted">
+ <div data-kanban-no-drag class="contents">
+ <For each={cardPropertyIds()}>
+ {(id) => {
+ const iconOnly = id === SYSTEM_PROPERTY_IDS.PRIORITY;
+ const includeEmpty = id === SYSTEM_PROPERTY_IDS.PRIORITY;
+
+ return renderProperty(task, readOnly, id, iconOnly, includeEmpty);
+ }}
+ </For>
+ </div>
+ </div>
+ </>
+ );
+
+ return (
+ <div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
+ <Show when={loading()}>
+ <p role="status" class="p-4 text-sm text-ink-muted">
+ Loading tasks…
+ </p>
+ </Show>
+ <Show when={source.error() || readError()}>
+ <div
+ role="alert"
+ class="flex items-center gap-2 px-4 py-2 text-sm text-failure"
+ >
+ Could not load all tasks.
+ <Button size="sm" onClick={() => void read(source.refresh)}>
+ Retry
+ </Button>
+ </div>
+ </Show>
+ <Show when={props.data.definitionError()}>
+ <div role="alert" class="px-4 py-2 text-sm text-failure">
+ Could not load task properties. Moving tasks is unavailable.
+ <Button
+ size="sm"
+ onClick={() => void read(props.data.retryDefinitions)}
+ >
+ Retry
+ </Button>
+ </div>
+ </Show>
+ <Show when={board.error()}>
+ {(error) => (
+ <p role="alert" class="px-4 py-2 text-sm text-ink-muted">
+ {error()}
+ </p>
+ )}
+ </Show>
+ <TaskBoard.Root
+ ref={props.ref}
+ animationScope={scope()}
+ columns={board.columns()}
+ canMove={board.canMove}
+ onMove={board.move}
+ >
+ <TaskBoard.Columns
+ endColumn={
+ props.data.hiddenColumnCount() > 0
+ ? () => (
+ <TaskBoard.HiddenColumns
+ count={props.data.hiddenColumnCount()}
+ partial={
+ grouping() === 'assignee' || grouping() === 'project'
+ }
+ onReveal={revealHiddenColumns}
+ />
+ )
+ : undefined
+ }
+ >
+ {(column) => (
+ <TaskBoard.Column>
+ <TaskBoard.Header>
+ <TaskBoardColumnHeader
+ column={column()}
+ grouping={grouping()}
+ createAssigneeName={props.data.createAssigneeName}
+ />
+ </TaskBoard.Header>
+ <TaskBoard.DropOverlay>
+ Board sorted by {sortLabel()}
+ </TaskBoard.DropOverlay>
+ <TaskBoard.Cards
+ empty={
+ <p class="px-2 py-6 text-center text-xs text-ink-extra-muted">
+ No matching tasks
+ </p>
+ }
+ footer={
+ <Show when={column().hasMore}>
+ <div class="py-3">
+ <Button
+ size="sm"
+ disabled={column().loadingMore}
+ onClick={() => void read(() => loadMore(column().id))}
+ >
+ {column().loadingMore ? 'Loading…' : 'Load more tasks'}
+ </Button>
+ </div>
+ </Show>
+ }
+ >
+ {(task) => {
+ const readOnly = () =>
+ !props.data.actions.canEditTask(task().id) ||
+ board.pending(task().id);
+
+ return (
+ <TaskBoard.Card
+ task={task()}
+ canDrag={!readOnly()}
+ pending={board.pending(task().id)}
+ onOpen={props.onOpen}
+ >
+ {renderCard(task, readOnly)}
+ </TaskBoard.Card>
+ );
+ }}
+ </TaskBoard.Cards>
+ </TaskBoard.Column>
+ )}
+ </TaskBoard.Columns>
+ </TaskBoard.Root>
+ <Show when={source.hasMore()}>
+ <div class="p-3">
+ <Button
+ size="sm"
+ disabled={source.isLoadingMore()}
+ onClick={() => void read(() => loadMore())}
+ >
+ {source.isLoadingMore() ? 'Loading…' : 'Load more tasks'}
+ </Button>
+ </div>
+ </Show>
+ </div>
+ );
+}
+
+function TaskBoardColumnHeader(props: {
+ column: TaskBoardColumn;
+ grouping: TaskBoardGrouping;
+ createAssigneeName: TaskBoardData['createAssigneeName'];
+}) {
+ const label = () => (
+ <h2 class="truncate text-sm font-medium" title={props.column.label}>
+ {props.column.label}
+ </h2>
+ );
+ const countLabel = () => {
+ const loaded = props.column.tasks.length;
+
+ if (props.column.count === undefined) {
+ return `${loaded} loaded tasks`;
+ }
+
+ return `${loaded} loaded of ${props.column.count} tasks`;
+ };
+
+ return (
+ <>
+ <span
+ class="flex size-4 shrink-0 items-center justify-center"
+ aria-hidden="true"
+ >
+ <Suspense>
+ <TaskBoardColumnIcon grouping={props.grouping} id={props.column.id} />
+ </Suspense>
+ </span>
+ <Show
+ when={props.grouping === 'assignee' && props.column.id}
+ fallback={label()}
+ >
+ <Suspense fallback={label()}>
+ <AssigneeColumnLabel
+ id={props.column.id}
+ fallback={props.column.label}
+ createAssigneeName={props.createAssigneeName}
+ />
+ </Suspense>
+ </Show>
+ <span
+ class="ml-auto shrink-0 text-xs text-ink-muted"
+ aria-label={countLabel()}
+ >
+ {props.column.count ?? props.column.tasks.length}
+ </span>
+ </>
+ );
+}
+
+function AssigneeColumnLabel(props: {
+ id: string;
+ fallback: string;
+ createAssigneeName: TaskBoardData['createAssigneeName'];
+}) {
+ const resolvedName = props.createAssigneeName(() => props.id);
+ const name = () => resolvedName() || props.fallback;
+
+ return (
+ <h2 class="truncate text-sm font-medium" title={name()}>
+ {name()}
+ </h2>
+ );
+}
diff --git a/apps/web/src/lib/queries/storage/document-metadata.ts b/apps/web/src/lib/queries/storage/document-metadata.ts
index 79c4115e12..091916d098 100644
--- a/apps/web/src/lib/queries/storage/document-metadata.ts
+++ b/apps/web/src/lib/queries/storage/document-metadata.ts
@@ -1,7 +1,7 @@
import { storageServiceClient } from '@service-storage/client';
import type { DocumentMetadata } from '@service-storage/generated/schemas';
import type { AccessLevel } from '@service-storage/generated/schemas/accessLevel';
-import { useQuery } from '@tanstack/solid-query';
+import { useQueries, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { entityKeys } from './keys';
@@ -38,13 +38,34 @@ export function useDocumentMetadataQuery(documentId: Accessor<string>) {
}));
}
-/** Loads the current user's access level for a document. */
-export function useDocumentAccessLevelQuery(documentId: Accessor<string>) {
- return useQuery(() => ({
- queryKey: entityKeys.documentAccessLevel(documentId()).queryKey,
- queryFn: () => fetchDocumentAccessLevel(documentId()),
+/** Shared options keep single-document and collection access checks on the same cache key. */
+export function documentAccessLevelQueryOptions(documentId: string) {
+ return {
+ queryKey: entityKeys.documentAccessLevel(documentId).queryKey,
+ queryFn: () => fetchDocumentAccessLevel(documentId),
staleTime: STALE_TIME,
gcTime: GC_TIME,
- enabled: !!documentId(),
- }));
+ enabled: !!documentId,
+ };
+}
+
+/** Loads the current user's access level for a document. */
+export function useDocumentAccessLevelQuery(documentId: Accessor<string>) {
+ return useQuery(() => documentAccessLevelQueryOptions(documentId()));
+}
+
+/** One shared query per unique document, even when a board renders several occurrences. */
+export function useDocumentAccessLevelsQuery(
+ documentIds: Accessor<readonly string[]>
+) {
+ return useQueries(() => {
+ const uniqueDocumentIds = [...new Set(documentIds())];
+
+ return {
+ queries: uniqueDocumentIds.map((documentId) => ({
+ ...documentAccessLevelQueryOptions(documentId),
+ select: (accessLevel: AccessLevel) => ({ documentId, accessLevel }),
+ })),
+ };
+ });
}
diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.md
index a6f4569543..d660c17c3a 100644
--- a/docs/AGENT_GUIDE/tasks.md
+++ b/docs/AGENT_GUIDE/tasks.md
@@ -3,7 +3,7 @@
## Surface
`Go to Tasks` → `/app/component/tasks`. Tabs: `My tasks`, `Created by me`, `Team tasks`, and `Projects`.
-The desktop toolbar contains search (`Ctrl+F`), `Sort`, `Group`, and `Filter`;
+The desktop toolbar contains search (`Ctrl+F`), an icon-only `Task layout` dropdown, `Sort`, `Group`, and `Filter`;
the filter uses the legacy compact option rows and searchable Assignee, Created by,
and Tags submenus. Multi-select choices keep the menu open; Escape dismisses it.
The top of the `Filter` menu is a `Filter with AI…` textbox, focused when the menu opens: type a plain-English
@@ -72,6 +72,96 @@ the originating tab breadcrumb, a task tab, or a tag to return to the list.
Shift-click a row or favorite to open it in a new split
instead. Keyboard list navigation only moves focus; press Enter to open the focused task.
+## Board layout
+
+Open the icon-only **Task layout** dropdown in the toolbar and choose **Board**
+(or **List** to switch back). Its icon reflects the current layout. **Group by**
+offers Status, Priority, Assignee, and (when Projects is enabled) Project.
+Both layouts share one grouping, which restores with the Tasks navigation entry.
+List-only None and Date groupings display Status columns in Board; switching
+back to List retains those selections and collapsed groups until grouping changes.
+
+Click a card's body or title to open the task. Move at least 10 pixels with the
+mouse button held to start dragging to another column; holding still does not
+start a drag. Property pills remain interactive and do not start a drag.
+A new destination column highlights once movement slows
+or pauses for about 100 ms. Fast travel suppresses activation of new columns.
+A valid hover shows **Board sorted by Updated**, **Created**, or **Viewed**
+using the active sort label. The drop does not choose a pointer insertion slot:
+its card takes its place in the current sort (or search relevance order).
+Same-column moves and column reordering remain disabled.
+Layout, primary sort, sort direction, and grouping are reflected in `tasks.layout`,
+`tasks.sort`, `tasks.sortReversed`, and `tasks.groupBy` search parameters.
+Explicit URL values override saved preferences; back/forward navigation
+restores the corresponding controls, including the layout.
+Columns are 336px wide. Each column pages independently with **Load more tasks**.
+Use the horizontal scrollbar to reach more columns. Vertical wheel input over
+empty board background or gaps also scrolls horizontally. A wheel gesture stays
+with its original scroll area until momentum stops, even if another column moves
+under the pointer. A new gesture inside an overflowing column scrolls vertically.
+Each column has its own vertical scrollbar when its cards overflow, while keeping
+its heading visible. Lane scrollbars appear while hovering the lane or scroll track
+and hide 200 ms after leaving. Off-hover momentum does not reveal them; focus and
+active scrollbar dragging retain visibility.
+Normal columns fit their content up to the viewport height; only the hidden-column
+summary fills the height. Both columns and cards are virtualized, so offscreen
+content is not all present in the DOM. A column's vertical position restores when
+scrolling away and back. The active drag source
+stays mounted while scrolling to a destination.
+While dragging, hold the card near a column's top or bottom edge to scroll its
+cards vertically. Hold near the board's left or right edge to scroll horizontally;
+moving beyond that edge keeps scrolling until release or cancellation. Valid drops
+still require the pointer to be inside a visible destination column.
+
+Column titles use status/priority icons, assignee avatars, or the project icon.
+Active filters also restrict columns: excluded values do not remain as empty
+boards. Allowed Status and Priority values retain empty destinations. Assignee
+and Project columns come from matching task groups; there is no extra-column
+selector. When filters hide known columns, a full-height dashed summary appears
+at the end. A filter illustration, count, and outline **Reveal hidden columns**
+button stay near the top of that column.
+Status and Priority show **N hidden**. Assignee and Project show **N+ hidden**:
+these lower bounds count known groups, not every group excluded by server filters.
+**Reveal hidden columns** clears only the current grouping's filter;
+other filters, the current tab, and search stay active. The dashed column is not
+a drop target.
+
+An icon-only status pill appears before the task title, and an icon-only assignee
+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.
+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;
+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
+immediately while the save is pending; failures restore its prior membership.
+After a successful save, the board scrolls only as needed to reveal the destination
+card, including virtualized columns and rows; already visible cards stay in place.
+It does not scroll after a cancelled or failed drop, or when the current board
+scope changes during the save. Successful moves show no notification.
+A cross-column drop settles one opaque visual copy from the card's release position
+into its sorted destination; the real card appears when the copy lands. The release
+snapshot survives source unmounting after edge scrolling. Sorting updates retarget
+an in-flight copy without restarting from the source column.
+Visible placements animate during moves and rollback without animating ordinary
+scrolling or paging. In Assignee grouping, moving to an already assigned person
+reveals the existing card rather than creating a duplicate.
+Reduced-motion preferences disable these transitions.
+Filters remain active: completing a task or removing yourself as assignee can
+hide the card from the current view. Click its title to open the task; modified
+clicks can open a separate split.
+
+Due-date columns and priority/due-date sorting are not in this version.
+The shared board primitives remain independent of Tasks queries and mutations.
+
## Cached grouped lists
With GraphQL caching enabled, previously loaded grouped task lists remain usable
@@ -369,8 +459,14 @@ set only on tasks. Setting it needs edit access to the task and the project;
removing it needs edit access to the task. The project's Tasks tab lists the
tasks whose Project property names the project.
-The project's Tasks tab starts with the task search, controls, and unified list;
-the project title and property pills appear only on Overview. Use
+The project's Tasks tab starts with task search, controls, and the selected List or
+Board layout; the project title and property pills appear only on Overview.
+Use the same icon-only **Task layout** dropdown to choose a layout. Both layouts
+show only tasks linked to the current project and use the same filters and editors.
+Layout, sort direction, and grouping use `projectTasks.layout`, `projectTasks.sort`,
+`projectTasks.sortReversed`, and `projectTasks.groupBy` URL parameters, independent
+of the main Tasks view's controls. Saved project entry state remains the fallback
+when URL parameters are absent. Use
`New task` to create a task in the project: the composer opens with its Project
set to this project (change or clear it like any property), and the create
request carries it, so there is no separate assignment step. The new row appears
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
index b03b796720..5f0d6a8e48 100644
--- a/rules/ast-grep/ts-feature-components-presentational.yml
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -13,6 +13,7 @@ note: |-
untyped wire JSON for property-changed rows. In block-agent, `ui/` is
the presentation layer and `component/` is the composition layer.
files:
+ - apps/web/src/features/tasks-view/components/task-board*
- apps/web/src/features/routines/components/**
- apps/web/src/features/scheduling/components/**
- apps/web/src/features/usage/components/**
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
index 8ed4046c27..9b5ab5f10c 100644
--- a/rules/ast-grep/ts-feature-core-pure.yml
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -15,6 +15,7 @@ note: |-
The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.
Block-agent names its rendering layers `ui/` and `component/`.
files:
+ - apps/web/src/features/tasks-view/core/task-board*
- apps/web/src/features/routines/core/**
- apps/web/src/features/scheduling/core/**
- apps/web/src/features/usage/core/**
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
index 3fd93e32cc..53a6f86395 100644
--- a/rules/ast-grep/ts-feature-data-no-ui.yml
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -11,6 +11,8 @@ note: |-
with fake clients and controllers with fake capabilities; neither imports
rendering code, including block-agent’s `ui/` and `component/` layers.
files:
+ - apps/web/src/features/tasks-view/queries/task-board*
+ - apps/web/src/features/tasks-view/primitives/create-task-board*
- apps/web/src/features/routines/queries/**
- apps/web/src/features/routines/primitives/**
- apps/web/src/features/scheduling/core/**
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
index e3ec0a59ec..babec682fd 100644
--- a/rules/ast-grep/ts-feature-layers-use-context.yml
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -15,6 +15,11 @@ note: |-
`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` for
presentation and `component/` for composition.
files:
+ - apps/web/src/features/tasks-view/queries/task-board*
+ - apps/web/src/features/tasks-view/primitives/create-task-board*
+ - apps/web/src/features/tasks-view/components/task-board*
+ - apps/web/src/features/tasks-view/views/task-board*
+ - apps/web/src/features/tasks-view/context/task-board*
- apps/web/src/features/routines/queries/**
- apps/web/src/features/routines/primitives/**
- apps/web/src/features/routines/components/**
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
index ac971352d0..e30b8f3694 100644
--- a/rules/ast-grep/tsx-feature-components-presentational.yml
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -13,6 +13,7 @@ note: |-
untyped wire JSON for property-changed rows. In block-agent, `ui/` is
the presentation layer and `component/` is the composition layer.
files:
+ - apps/web/src/features/tasks-view/components/task-board*
- apps/web/src/features/routines/components/**
- apps/web/src/features/scheduling/components/**
- apps/web/src/features/usage/components/**
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
index 8efcf3740e..4f5726a538 100644
--- a/rules/ast-grep/tsx-feature-core-pure.yml
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -15,6 +15,7 @@ note: |-
The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.
Block-agent names its rendering layers `ui/` and `component/`.
files:
+ - apps/web/src/features/tasks-view/core/task-board*
- apps/web/src/features/routines/core/**
- apps/web/src/features/scheduling/core/**
- apps/web/src/features/usage/core/**
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
index 67710e6772..fddd564dc2 100644
--- a/rules/ast-grep/tsx-feature-data-no-ui.yml
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -11,6 +11,8 @@ note: |-
with fake clients and controllers with fake capabilities; neither imports
rendering code, including block-agent’s `ui/` and `component/` layers.
files:
+ - apps/web/src/features/tasks-view/queries/task-board*
+ - apps/web/src/features/tasks-view/primitives/create-task-board*
- apps/web/src/features/routines/queries/**
- apps/web/src/features/routines/primitives/**
- apps/web/src/features/scheduling/core/**
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
index cec3bd277d..10e0b03acc 100644
--- a/rules/ast-grep/tsx-feature-layers-use-context.yml
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -15,6 +15,11 @@ note: |-
`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` for
presentation and `component/` for composition.
files:
+ - apps/web/src/features/tasks-view/queries/task-board*
+ - apps/web/src/features/tasks-view/primitives/create-task-board*
+ - apps/web/src/features/tasks-view/components/task-board*
+ - apps/web/src/features/tasks-view/views/task-board*
+ - apps/web/src/features/tasks-view/context/task-board*
- apps/web/src/features/routines/queries/**
- apps/web/src/features/routines/primitives/**
- apps/web/src/features/routines/components/**