Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(issues): repair the issue Table's column interactions, loading states and scroll rendering (#6036)

Naiyuan Qinge70e71fea13b
diff --git a/packages/ui/components/ui/data-table.tsx b/packages/ui/components/ui/data-table.tsx
index b81b3e5707..004719e35e 100644
--- a/packages/ui/components/ui/data-table.tsx
+++ b/packages/ui/components/ui/data-table.tsx
@@ -2,12 +2,14 @@
import {
flexRender,
+ type ColumnSizingState,
type Header as TanstackHeader,
type Row,
type Table as TanstackTable,
} from "@tanstack/react-table";
-import { useVirtualizer } from "@tanstack/react-virtual";
+import { useVirtualizer, type VirtualItem } from "@tanstack/react-virtual";
import * as React from "react";
+import { createPortal } from "react-dom";
// We deliberately use the lower-level shadcn primitives (TableHeader /
// TableBody / TableRow / TableHead / TableCell) but NOT the wrapping
@@ -22,9 +24,14 @@ import {
TableHeader,
TableRow,
} from "@multica/ui/components/ui/table";
-import { getCellStyle } from "@multica/ui/lib/data-table";
+import { columnSizeVar, getCellStyle } from "@multica/ui/lib/data-table";
import { cn } from "@multica/ui/lib/utils";
+// Pointer travel that turns a press on the resize handle into a drag. Matches
+// the column-reorder sensor's activation distance so both gestures on the same
+// header behave alike, and keeps a plain click from committing a width.
+const RESIZE_DRAG_THRESHOLD = 4;
+
interface DataTableProps<TData> extends React.ComponentProps<"div"> {
table: TanstackTable<TData>;
// Optional bar shown below the table when ≥1 row is selected. We
@@ -93,19 +100,101 @@ export function DataTable<TData>({
[columnSizing],
);
+ const clampColumnWidth = React.useCallback(
+ (columnId: string, width: number) => {
+ const columnDef = table.getColumn(columnId)?.columnDef;
+ const minSize = columnDef?.minSize ?? 48;
+ const maxSize = columnDef?.maxSize ?? Number.MAX_SAFE_INTEGER;
+ return Math.min(maxSize, Math.max(minSize, Math.round(width)));
+ },
+ [table],
+ );
+
const setColumnWidth = React.useCallback(
(header: TanstackHeader<TData, unknown>, width: number) => {
- const minSize = header.column.columnDef.minSize ?? 48;
- const maxSize =
- header.column.columnDef.maxSize ?? Number.MAX_SAFE_INTEGER;
- const next = Math.min(maxSize, Math.max(minSize, Math.round(width)));
-
table.setColumnSizing((old) => ({
...old,
- [header.column.id]: next,
+ [header.column.id]: clampColumnWidth(header.column.id, width),
}));
},
- [table],
+ [clampColumnWidth, table],
+ );
+
+ // Fixed table-layout shares out whatever space is left when the configured
+ // widths add up to less than the table, so every column renders wider than
+ // it is configured. Committing one column changes that leftover and rescales
+ // all the others, which makes a drag run ahead of the pointer. Pinning every
+ // column to the width it already renders at removes the leftover, so from
+ // that point the drag maps 1:1 onto pointer movement.
+ const freezeRenderedWidths = React.useCallback(
+ (headerRow: Element | null): ColumnSizingState => {
+ const frozen: ColumnSizingState = {};
+ const cells =
+ headerRow?.querySelectorAll<HTMLElement>("th[data-column-id]") ?? [];
+ for (const cell of cells) {
+ const columnId = cell.dataset.columnId;
+ if (!columnId) continue;
+ frozen[columnId] = clampColumnWidth(
+ columnId,
+ cell.getBoundingClientRect().width,
+ );
+ }
+ return frozen;
+ },
+ [clampColumnWidth],
+ );
+
+ // Double-click on the resize handle sizes the column to its content, the
+ // convention every spreadsheet and grid shares. It replaces column.resetSize,
+ // which cleared the stored width and let TanStack fall back to its generic
+ // 150 — a number unrelated to any of this table's designed widths, so
+ // "reset" widened some columns and collapsed others.
+ //
+ // Fixed table-layout ignores content, and cells truncate their own text, so
+ // nothing on screen reports the width the content actually wants. The
+ // measurement lifts both constraints on the column's cells, reads them, and
+ // puts everything back within the same task — the browser paints once, after
+ // the restore, so the intermediate layout is never seen.
+ const autoFitColumn = React.useCallback(
+ (header: TanstackHeader<TData, unknown>) => {
+ const container = scrollRef.current;
+ const tableElement = container?.querySelector("table");
+ if (!container || !tableElement) return;
+ const cells = container.querySelectorAll<HTMLElement>(
+ `[data-column-id="${CSS.escape(header.column.id)}"]`,
+ );
+ if (!cells.length) return;
+
+ const previousLayout = tableElement.style.tableLayout;
+ const previous = Array.from(cells, (cell) => ({
+ cell,
+ width: cell.style.width,
+ maxWidth: cell.style.maxWidth,
+ overflow: cell.style.overflow,
+ }));
+
+ tableElement.style.tableLayout = "auto";
+ for (const cell of cells) {
+ cell.style.width = "max-content";
+ cell.style.maxWidth = "none";
+ cell.style.overflow = "visible";
+ }
+
+ let widest = 0;
+ for (const cell of cells) {
+ widest = Math.max(widest, cell.getBoundingClientRect().width);
+ }
+
+ for (const entry of previous) {
+ entry.cell.style.width = entry.width;
+ entry.cell.style.maxWidth = entry.maxWidth;
+ entry.cell.style.overflow = entry.overflow;
+ }
+ tableElement.style.tableLayout = previousLayout;
+
+ if (widest > 0) setColumnWidth(header, widest);
+ },
+ [setColumnWidth],
);
const beginColumnResize = React.useCallback(
@@ -119,36 +208,62 @@ export function DataTable<TData>({
event.stopPropagation();
const startX = event.clientX;
- const headerCell = event.currentTarget.closest("th");
+ const handleEl = event.currentTarget;
+ const { pointerId } = event;
+ const headerCell = handleEl.closest("th");
+ // The rendered width, not column.getSize(): the drag has to continue from
+ // the edge the user grabbed, which sits wherever the stretch put it.
const startWidth =
headerCell?.getBoundingClientRect().width ?? header.column.getSize();
setResizingColumnId(header.column.id);
- setColumnWidth(header, startWidth);
- const originalCursor = document.body.style.cursor;
- const originalUserSelect = document.body.style.userSelect;
- document.body.style.cursor = "col-resize";
- document.body.style.userSelect = "none";
+ let frozen: ColumnSizingState | null = null;
const handlePointerMove = (pointerEvent: PointerEvent) => {
- setColumnWidth(header, startWidth + pointerEvent.clientX - startX);
+ const delta = pointerEvent.clientX - startX;
+ // Nothing is committed below the threshold, so a press on its own can
+ // no longer pin a column at the width the stretch happened to give it.
+ if (!frozen && Math.abs(delta) < RESIZE_DRAG_THRESHOLD) return;
+ // Measured once, on the frame the drag starts — every later frame
+ // reuses it, so the baseline can't drift as widths change underneath.
+ frozen ??= freezeRenderedWidths(handleEl.closest("tr"));
+
+ table.setColumnSizing((old) => ({
+ ...old,
+ ...frozen,
+ [header.column.id]: clampColumnWidth(
+ header.column.id,
+ startWidth + delta,
+ ),
+ }));
};
const stopResize = () => {
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", stopResize);
window.removeEventListener("pointercancel", stopResize);
- document.body.style.cursor = originalCursor;
- document.body.style.userSelect = originalUserSelect;
+ window.removeEventListener("blur", stopResize);
+ // Detached before releasing capture — releasing fires this same event.
+ handleEl.removeEventListener("lostpointercapture", stopResize);
+ if (handleEl.hasPointerCapture?.(pointerId)) {
+ handleEl.releasePointerCapture?.(pointerId);
+ }
setResizingColumnId(null);
};
window.addEventListener("pointermove", handlePointerMove);
window.addEventListener("pointerup", stopResize);
window.addEventListener("pointercancel", stopResize);
+ // Releasing outside the window or switching apps mid-drag never delivers
+ // pointerup. Without these the gesture stays armed and the column keeps
+ // tracking the pointer once the user comes back.
+ window.addEventListener("blur", stopResize);
+ handleEl.addEventListener("lostpointercapture", stopResize);
+ // Optional call: jsdom has no pointer capture.
+ handleEl.setPointerCapture?.(pointerId);
},
- [setColumnWidth],
+ [clampColumnWidth, freezeRenderedWidths, table],
);
const handleResizeKeyDown = React.useCallback(
@@ -174,7 +289,55 @@ export function DataTable<TData>({
[hasExplicitSize, setColumnWidth],
);
+ // Every column's width, published once on the <table>. Cells reference these
+ // instead of each calling column.getSize(), so a resize costs one style
+ // update on one element rather than one per cell.
+ const leafColumns = table.getVisibleLeafColumns();
+ const columnSizeVars = React.useMemo(() => {
+ const vars: Record<string, string> = {};
+ for (const column of leafColumns) {
+ vars[columnSizeVar(column.id)] = `${column.getSize()}px`;
+ }
+ return vars;
+ // column.getSize() reads columnSizing, which the rule cannot see through
+ // the call. getVisibleLeafColumns is memoised on visibility and order, so
+ // without it the widths would freeze at whatever they were on mount.
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- getSize() reads columnSizing
+ }, [columnSizing, leafColumns]);
+
const scrollRef = React.useRef<HTMLDivElement | null>(null);
+
+ // Drives the pinned columns' trailing shadow. It only means something once
+ // content is passing beneath them, so it stays off at rest. The state is a
+ // boolean rather than the offset: it flips twice per scroll excursion
+ // instead of once per scroll event, and React bails out on the repeats.
+ const [isScrolledHorizontally, setIsScrolledHorizontally] =
+ React.useState(false);
+
+ // Where the frozen block ends, in the scroll container's own coordinates.
+ const [pinnedEdge, setPinnedEdge] = React.useState<number | null>(null);
+
+ React.useEffect(() => {
+ const element = scrollRef.current;
+ if (!element) return;
+ const sync = () => {
+ setIsScrolledHorizontally(element.scrollLeft > 0);
+ const edge = element.querySelector("thead th[data-pinned-edge]");
+ setPinnedEdge(
+ edge
+ ? edge.getBoundingClientRect().right -
+ element.getBoundingClientRect().left
+ : null,
+ );
+ };
+ sync();
+ element.addEventListener("scroll", sync, { passive: true });
+ return () => element.removeEventListener("scroll", sync);
+ // Re-measured on column sizing too, not scrolling alone: resizing a frozen
+ // column while the surface is scrolled moves the boundary the shadow is
+ // pinned to, and no scroll event follows to correct it.
+ }, [columnSizing]);
+
const rows = table.getRowModel().rows;
const getVirtualRowKey = React.useCallback(
(index: number) => rows[index]?.id ?? index,
@@ -186,6 +349,13 @@ export function DataTable<TData>({
estimateSize: () => virtualRowHeight,
getItemKey: getVirtualRowKey,
overscan: virtualOverscan,
+ // Rows are not all one height. Callers use renderRow for group headers and
+ // end-of-column footers, which are shorter than a data row, so a single
+ // estimate drifts from the real layout as those accumulate — the window
+ // lands off the rows it should be showing and the scrollbar overshoots the
+ // bottom. Each mounted row reports its own height instead, and the
+ // estimate only covers rows that have never been on screen.
+ measureElement: (element) => element.getBoundingClientRect().height,
});
const virtualItems = rowVirtualizer.getVirtualItems();
const firstVirtualItem = virtualItems[0];
@@ -195,79 +365,46 @@ export function DataTable<TData>({
? rowVirtualizer.getTotalSize() - lastVirtualItem.end
: 0;
- const renderDataRow = (row: Row<TData>) => {
- const customRow = renderRow?.(row);
- if (customRow != null) {
- return <React.Fragment key={row.id}>{customRow}</React.Fragment>;
- }
- return (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- onClick={onRowClick ? () => onRowClick(row) : undefined}
- // `group` lets pinned cells track row hover via group-hover (their bg
- // is in className, not on the row, so they stay opaque enough to cover
- // content scrolling beneath them).
- className={cn("group", onRowClick && "cursor-pointer")}
- >
- {row.getVisibleCells().map((cell) => {
- const isPinned = cell.column.getIsPinned();
- const columnHasExplicitSize = hasExplicitSize(cell.column.id);
- return (
- <TableCell
- key={cell.id}
- // px-4 across the board so cell content aligns with the
- // surrounding toolbar's px-4. Narrow trailing columns
- // (chevron / actions) declare enough width for icon + padding.
- // Pinned cells need an opaque bg + group-hover so they cover
- // content scrolling beneath them and follow row hover state.
- className={cn(
- "overflow-hidden px-4 py-2",
- isPinned &&
- "bg-background group-hover:bg-[color-mix(in_oklab,var(--muted)_50%,var(--background))]",
- )}
- style={getCellStyle(cell.column, {
- withBorder: true,
- hasExplicitSize: columnHasExplicitSize,
- })}
- >
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- );
- })}
- </TableRow>
- );
+ const bodyProps: DataTableBodyProps<TData> = {
+ table,
+ rows,
+ emptyMessage,
+ onRowClick,
+ renderRow,
+ hasExplicitSize,
+ measureRow: rowVirtualizer.measureElement,
+ virtualizeRows,
+ virtualItems,
+ virtualPaddingTop,
+ virtualPaddingBottom,
};
- const renderVirtualSpacer = (position: "top" | "bottom", height: number) =>
- height > 0 ? (
- <TableRow
- key={`virtual-spacer-${position}`}
- aria-hidden
- className="pointer-events-none border-0 hover:bg-transparent"
- >
- <TableCell
- colSpan={table.getVisibleLeafColumns().length}
- className="p-0"
- style={{ height: `${height}px` }}
- />
- </TableRow>
- ) : null;
-
return (
<div
className={cn("flex min-h-0 flex-1 flex-col", className)}
{...props}
>
+ <div className="relative flex min-h-0 flex-1 flex-col">
<div
ref={scrollRef}
className="flex min-h-0 flex-1 flex-col overflow-auto bg-background"
>
<table
className="w-full table-fixed caption-bottom text-sm"
- style={{ minWidth: `${table.getTotalSize()}px` }}
+ style={{
+ minWidth: `${table.getTotalSize()}px`,
+ ...columnSizeVars,
+ }}
>
- <TableHeader className="sticky top-0 z-10 bg-muted/30 backdrop-blur">
+ {/* Opaque rather than translucent-and-blurred. A backdrop-filter on
+ * a sticky element with content scrolling beneath it is a known
+ * Chromium compositing fault (electron#12906, chromium#339841685) —
+ * the blur layer has to recompute its backdrop every frame while
+ * virtualisation adds and removes the rows underneath it, and the
+ * strip flickers black. The mix resolves to the same colour
+ * bg-muted/30 composited to, and a header that scrolled content
+ * passes behind has no reason to show it through anyway. */}
+ <TableHeader className="sticky top-0 z-10 bg-[color-mix(in_oklab,var(--muted)_30%,var(--background))]">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="hover:bg-transparent">
{headerGroup.headers.map((header) => {
@@ -283,6 +420,19 @@ export function DataTable<TData>({
<TableHead
key={header.id}
colSpan={header.colSpan}
+ // Lets a drag measure every column by id instead of
+ // pairing <th> elements with columns positionally.
+ data-column-id={header.column.id}
+ // Marks the frozen block's trailing edge for the scroll
+ // shadow to measure against. Rendered widths differ from
+ // configured ones under fixed table-layout, so the
+ // boundary has to be read off the DOM, not summed.
+ data-pinned-edge={
+ isPinned === "left" &&
+ header.column.getIsLastColumn("left")
+ ? ""
+ : undefined
+ }
// Header typography overrides for a "spreadsheet
// header" look: smaller, all-caps, wider letter
// spacing, muted colour. shadcn's <TableHead>
@@ -299,12 +449,11 @@ export function DataTable<TData>({
// muted with background to preserve the same visual tone
// as muted/30 without introducing alpha.
className={cn(
- "relative h-8 overflow-hidden px-4 py-2 text-xs uppercase tracking-wider text-muted-foreground",
+ "relative h-8 overflow-hidden border-r px-4 py-2 text-xs uppercase tracking-wider text-muted-foreground last:border-r-0",
isPinned &&
"bg-[color-mix(in_oklab,var(--muted)_30%,var(--background))]",
)}
style={getCellStyle(header.column, {
- withBorder: true,
hasExplicitSize: columnHasExplicitSize,
})}
>
@@ -322,11 +471,27 @@ export function DataTable<TData>({
aria-orientation="vertical"
tabIndex={0}
className={cn(
+ // The line sits exactly on the column's own
+ // border (hence -right-px, since `right-0` would
+ // land just inside it and read as a double rule)
+ // and recolours it. Three states have to stay
+ // apart on one hairline: at rest it is the faint
+ // grid rule, hovered it goes translucent brand,
+ // and for the whole drag it holds at full brand —
+ // brightening rather than fading, so the edge
+ // being moved stays the most definite thing on
+ // screen even once the pointer leaves the handle.
+ // right-0, never a negative offset: the <th> is
+ // overflow-hidden and clips at its padding edge,
+ // so anything nudged out to sit on the border
+ // itself is simply not painted. The bar lands
+ // just inside the rule instead, and at 2px it
+ // stays legible next to it.
"absolute top-0 right-0 h-full w-2 cursor-col-resize touch-none select-none outline-none",
- "after:absolute after:top-1/2 after:right-0 after:h-4 after:w-px after:-translate-y-1/2 after:bg-border after:opacity-0 after:transition-opacity",
- "hover:after:opacity-100 focus-visible:after:opacity-100",
+ "after:absolute after:inset-y-0 after:right-0 after:w-0.5 after:bg-transparent after:transition-colors after:duration-100",
+ "hover:after:bg-brand/60 focus-visible:after:bg-brand/60",
resizingColumnId === header.column.id &&
- "after:bg-primary after:opacity-100",
+ "after:bg-brand after:transition-none",
)}
onPointerDown={(event) =>
beginColumnResize(header, event)
@@ -334,7 +499,7 @@ export function DataTable<TData>({
onDoubleClick={(event) => {
event.preventDefault();
event.stopPropagation();
- header.column.resetSize();
+ autoFitColumn(header);
}}
onKeyDown={(event) =>
handleResizeKeyDown(header, event)
@@ -347,37 +512,199 @@ export function DataTable<TData>({
</TableRow>
))}
</TableHeader>
- <TableBody>
- {rows.length ? (
- virtualizeRows ? (
- <>
- {renderVirtualSpacer("top", virtualPaddingTop)}
- {virtualItems.map((virtualItem) => {
- const row = rows[virtualItem.index];
- return row ? renderDataRow(row) : null;
- })}
- {renderVirtualSpacer("bottom", virtualPaddingBottom)}
- </>
- ) : (
- rows.map(renderDataRow)
- )
- ) : (
- <TableRow>
- <TableCell
- colSpan={table.getAllColumns().length}
- className="h-24 text-center text-muted-foreground"
- >
- {emptyMessage}
- </TableCell>
- </TableRow>
- )}
- </TableBody>
+ {/* Widths reach the body through the custom properties above, so
+ * while a column is being dragged the body has nothing to re-render:
+ * swap in the memoized copy and let the browser do the resizing. */}
+ {resizingColumnId !== null ? (
+ <MemoizedDataTableBody {...bodyProps} />
+ ) : (
+ <DataTableBody {...bodyProps} />
+ )}
{footer}
</table>
</div>
+ {/* Cast past the frozen block rather than drawn inside it. The border
+ * between the frozen columns and the rest is permanent and says where
+ * the boundary is; this says something is currently passing underneath,
+ * so it appears only while scrolled. An inset box-shadow on the pinned
+ * cell could only darken that cell's own edge — the depth belongs on
+ * the content sliding beneath it. */}
+ {isScrolledHorizontally && pinnedEdge !== null && (
+ <div
+ aria-hidden
+ data-slot="data-table-pinned-shadow"
+ className="pointer-events-none absolute inset-y-0 w-3"
+ style={{
+ left: `${pinnedEdge}px`,
+ background:
+ "linear-gradient(to right, color-mix(in oklab, var(--foreground) 7%, transparent), transparent)",
+ }}
+ />
+ )}
+ </div>
+ {/* A viewport-wide layer that only exists for the duration of a column
+ * drag. It owns the cursor so descendants that declare their own
+ * (rows are `cursor-pointer`, cells hold text) cannot override it, and
+ * it keeps the text underneath unselectable. Setting these on
+ * document.body instead loses both fights, since a descendant's own
+ * cursor wins over an inherited one. Pointer events still reach the
+ * gesture: it listens on `window`, which the layer's events bubble to.
+ * Portaled to body so an ancestor with a transform / filter / contain
+ * cannot turn `fixed` into "relative to that ancestor". */}
+ {resizingColumnId !== null &&
+ typeof document !== "undefined" &&
+ createPortal(
+ <div
+ aria-hidden
+ data-slot="data-table-resize-overlay"
+ className="fixed inset-0 z-50 cursor-col-resize touch-none select-none"
+ />,
+ document.body,
+ )}
{actionBar &&
table.getFilteredSelectedRowModel().rows.length > 0 &&
actionBar}
</div>
);
}
+
+interface DataTableBodyProps<TData> {
+ table: TanstackTable<TData>;
+ rows: Row<TData>[];
+ emptyMessage: React.ReactNode;
+ onRowClick?: (row: Row<TData>) => void;
+ renderRow?: (row: Row<TData>) => React.ReactNode;
+ hasExplicitSize: (columnId: string) => boolean;
+ // The virtualizer's own measuring ref; rows report their height through it.
+ measureRow: (element: HTMLElement | null) => void;
+ virtualizeRows: boolean;
+ virtualItems: VirtualItem[];
+ virtualPaddingTop: number;
+ virtualPaddingBottom: number;
+}
+
+function DataTableBody<TData>({
+ table,
+ rows,
+ emptyMessage,
+ onRowClick,
+ renderRow,
+ hasExplicitSize,
+ measureRow,
+ virtualizeRows,
+ virtualItems,
+ virtualPaddingTop,
+ virtualPaddingBottom,
+}: DataTableBodyProps<TData>) {
+ const renderDataRow = (row: Row<TData>, index?: number) => {
+ // The virtualizer reads an element's own height off `data-index`, so a row
+ // has to be tagged and handed the measuring ref. renderRow returns a <tr>
+ // the caller built; cloning is how it joins in without every caller having
+ // to thread the two through.
+ const measured =
+ index === undefined
+ ? {}
+ : { "data-index": index, ref: measureRow };
+
+ const customRow = renderRow?.(row);
+ if (customRow != null) {
+ return React.isValidElement(customRow) && index !== undefined
+ ? React.cloneElement(
+ customRow as React.ReactElement<Record<string, unknown>>,
+ { key: row.id, ...measured },
+ )
+ : <React.Fragment key={row.id}>{customRow}</React.Fragment>;
+ }
+ return (
+ <TableRow
+ key={row.id}
+ {...measured}
+ data-state={row.getIsSelected() && "selected"}
+ onClick={onRowClick ? () => onRowClick(row) : undefined}
+ // `group` lets pinned cells track row hover via group-hover (their bg
+ // is in className, not on the row, so they stay opaque enough to cover
+ // content scrolling beneath them).
+ className={cn("group", onRowClick && "cursor-pointer")}
+ >
+ {row.getVisibleCells().map((cell) => {
+ const isPinned = cell.column.getIsPinned();
+ const columnHasExplicitSize = hasExplicitSize(cell.column.id);
+ return (
+ <TableCell
+ key={cell.id}
+ data-column-id={cell.column.id}
+ // px-4 across the board so cell content aligns with the
+ // surrounding toolbar's px-4. Narrow trailing columns
+ // (chevron / actions) declare enough width for icon + padding.
+ // Pinned cells need an opaque bg + group-hover so they cover
+ // content scrolling beneath them and follow row hover state.
+ className={cn(
+ "overflow-hidden border-r px-4 py-2 last:border-r-0",
+ isPinned &&
+ "bg-background group-hover:bg-[color-mix(in_oklab,var(--muted)_50%,var(--background))]",
+ )}
+ style={getCellStyle(cell.column, {
+ hasExplicitSize: columnHasExplicitSize,
+ })}
+ >
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ );
+ })}
+ </TableRow>
+ );
+ };
+
+ const renderVirtualSpacer = (position: "top" | "bottom", height: number) =>
+ height > 0 ? (
+ <TableRow
+ key={`virtual-spacer-${position}`}
+ aria-hidden
+ className="pointer-events-none border-0 hover:bg-transparent"
+ >
+ <TableCell
+ colSpan={table.getVisibleLeafColumns().length}
+ className="p-0"
+ style={{ height: `${height}px` }}
+ />
+ </TableRow>
+ ) : null;
+
+ return (
+ <TableBody>
+ {rows.length ? (
+ virtualizeRows ? (
+ <>
+ {renderVirtualSpacer("top", virtualPaddingTop)}
+ {virtualItems.map((virtualItem) => {
+ const row = rows[virtualItem.index];
+ return row ? renderDataRow(row, virtualItem.index) : null;
+ })}
+ {renderVirtualSpacer("bottom", virtualPaddingBottom)}
+ </>
+ ) : (
+ rows.map(renderDataRow)
+ )
+ ) : (
+ <TableRow>
+ <TableCell
+ colSpan={table.getAllColumns().length}
+ className="h-24 text-center text-muted-foreground"
+ >
+ {emptyMessage}
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ );
+}
+
+// Rendered in place of DataTableBody for the duration of a column drag. Only
+// the row data is compared: during a drag the widths travel as custom
+// properties and nothing else in the body can change, so skipping the render
+// entirely is what keeps hundreds of cells off the main thread per frame.
+// React.memo erases the generic, so the cast restores the original signature.
+const MemoizedDataTableBody = React.memo(
+ DataTableBody,
+ (prev, next) => prev.table.options.data === next.table.options.data,
+) as typeof DataTableBody;
diff --git a/packages/ui/lib/data-table.ts b/packages/ui/lib/data-table.ts
index 1b508525a4..16b976527d 100644
--- a/packages/ui/lib/data-table.ts
+++ b/packages/ui/lib/data-table.ts
@@ -13,45 +13,72 @@ declare module "@tanstack/react-table" {
}
}
+// Custom-property name carrying a column's width. Column ids are app-defined
+// and may hold characters that are not valid in a CSS ident (`property:<uuid>`
+// is the live example), so everything outside the ident set is folded to `_`.
+// The ids in play differ well before that point, so folding cannot collide.
+export function columnSizeVar(columnId: string) {
+ return `--col-${columnId.replace(/[^a-zA-Z0-9_-]/g, "_")}-size`;
+}
+
// Combined sizing + pinning style for a `<th>` / `<td>` cell. Width is
// emitted unless the column is flagged `meta.grow` (those rely on
// fixed-layout's leftover-space distribution). Pinned columns get
// sticky positioning — see notes below.
//
+// The width is a reference to a custom property published once on the <table>
+// rather than a number read per cell. During a resize that lets the browser
+// apply every new width from a single declaration change, with no React work
+// in the hundreds of cells that would otherwise each re-read column.getSize().
+//
// Background is intentionally NOT set inline — the upstream Dice UI
// version writes `background: var(--background)` here, which can't
// react to `:hover`. Consumers set bg via Tailwind classes paired with
// `group-hover:`.
export function getCellStyle<TData>(
column: Column<TData>,
- options?: { withBorder?: boolean; hasExplicitSize?: boolean },
+ options?: { hasExplicitSize?: boolean },
): React.CSSProperties {
const grow = column.columnDef.meta?.grow;
- const width = grow && !options?.hasExplicitSize ? undefined : column.getSize();
+ const width =
+ grow && !options?.hasExplicitSize
+ ? undefined
+ : `var(${columnSizeVar(column.id)})`;
const isPinned = column.getIsPinned();
if (!isPinned) {
return width !== undefined ? { width } : {};
}
- const withBorder = options?.withBorder ?? false;
- const isLastLeftPinned =
- isPinned === "left" && column.getIsLastColumn("left");
- const isFirstRightPinned =
- isPinned === "right" && column.getIsFirstColumn("right");
-
+ // No edge marker here. Where the frozen columns end is drawn by the scroll
+ // container's mask instead — a shadow inside the pinned cell can only darken
+ // the frozen column's own edge, while the mask fades the content that is
+ // actually sliding underneath, which is the thing being described.
return {
width,
position: "sticky",
left: isPinned === "left" ? `${column.getStart("left")}px` : undefined,
right: isPinned === "right" ? `${column.getAfter("right")}px` : undefined,
zIndex: 1,
- boxShadow: withBorder
- ? isLastLeftPinned
- ? "-4px 0 4px -4px var(--border) inset"
- : isFirstRightPinned
- ? "4px 0 4px -4px var(--border) inset"
- : undefined
- : undefined,
};
}
+
+// Mask for the scroll container: content emerging from under the frozen
+// columns fades in over `fade` px instead of appearing at a hard edge.
+//
+// The stops are anchored to the frozen block's width, never to the scroll
+// offset — a mask on a scroll container is positioned against its padding box,
+// which does not scroll, so the fade stays welded to the boundary. Anchoring
+// is also what keeps the frozen columns themselves at full opacity: the
+// generic "fade both ends of a scroller" treatment would dissolve exactly the
+// columns that have to stay solid.
+export function pinnedScrollMask(
+ pinnedWidth: number,
+ fade = 24,
+): React.CSSProperties | undefined {
+ if (pinnedWidth <= 0) return undefined;
+ const gradient =
+ `linear-gradient(to right, black 0, black ${pinnedWidth}px, ` +
+ `transparent ${pinnedWidth}px, black ${pinnedWidth + fade}px, black 100%)`;
+ return { maskImage: gradient, WebkitMaskImage: gradient };
+}
diff --git a/packages/views/issues/components/data-table-resize.test.tsx b/packages/views/issues/components/data-table-resize.test.tsx
new file mode 100644
index 0000000000..e9d3502e3d
--- /dev/null
+++ b/packages/views/issues/components/data-table-resize.test.tsx
@@ -0,0 +1,296 @@
+import { act, render, screen } from "@testing-library/react";
+import {
+ getCoreRowModel,
+ useReactTable,
+ type ColumnDef,
+ type ColumnSizingState,
+} from "@tanstack/react-table";
+import * as React from "react";
+import { describe, expect, it, vi } from "vitest";
+import { DataTable } from "@multica/ui/components/ui/data-table";
+
+type Row = { status: string; owner: string };
+
+const columns: ColumnDef<Row>[] = [
+ { accessorKey: "status", header: "Status", size: 150 },
+ { accessorKey: "owner", header: "Owner", size: 90 },
+];
+
+function ResizableTable({
+ onSizingChange,
+ pinFirstColumn = false,
+}: {
+ onSizingChange: (sizing: ColumnSizingState) => void;
+ pinFirstColumn?: boolean;
+}) {
+ const [columnSizing, setColumnSizing] = React.useState<ColumnSizingState>({});
+ const table = useReactTable({
+ data: [{ status: "In progress", owner: "Ada" }],
+ columns,
+ getCoreRowModel: getCoreRowModel(),
+ state: {
+ columnSizing,
+ columnPinning: { left: pinFirstColumn ? ["status"] : [], right: [] },
+ },
+ columnResizeMode: "onChange",
+ onColumnSizingChange: (updater) => {
+ const next =
+ typeof updater === "function" ? updater(columnSizing) : updater;
+ setColumnSizing(next);
+ onSizingChange(next);
+ },
+ });
+
+ return <DataTable table={table} />;
+}
+
+// jsdom has no layout, so every <th> would measure 0 and each committed width
+// would clamp to minSize. Pin them to the widths fixed table-layout would have
+// stretched the columns to — both sit well above their configured size.
+function stubRenderedWidth(element: Element, width: number) {
+ element.getBoundingClientRect = () =>
+ ({
+ width,
+ height: 32,
+ top: 0,
+ left: 0,
+ right: width,
+ bottom: 32,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ }) as DOMRect;
+}
+
+// jsdom's PointerEvent support is inconsistent; MouseEvent carries clientX and
+// React dispatches by event type, so the handlers receive what they need.
+// act() flushes the render that toggling the drag state schedules.
+function pointer(target: EventTarget, type: string, clientX: number) {
+ act(() => {
+ target.dispatchEvent(
+ new MouseEvent(type, { bubbles: true, cancelable: true, clientX }),
+ );
+ });
+}
+
+function setup() {
+ const onSizingChange = vi.fn();
+ render(<ResizableTable onSizingChange={onSizingChange} />);
+ const handle = screen.getByRole("separator", {
+ name: "Resize Status column",
+ });
+ stubRenderedWidth(
+ document.querySelector('th[data-column-id="status"]')!,
+ 200,
+ );
+ stubRenderedWidth(document.querySelector('th[data-column-id="owner"]')!, 120);
+ return { onSizingChange, handle };
+}
+
+describe("DataTable column resize", () => {
+ it("commits nothing when the handle is clicked without dragging", () => {
+ const { onSizingChange, handle } = setup();
+
+ pointer(handle, "pointerdown", 100);
+ pointer(window, "pointerup", 100);
+
+ // The pre-fix code wrote the stretched render width here, permanently
+ // pinning a column the user only brushed past.
+ expect(onSizingChange).not.toHaveBeenCalled();
+ });
+
+ it("ignores pointer travel below the drag threshold", () => {
+ const { onSizingChange, handle } = setup();
+
+ pointer(handle, "pointerdown", 100);
+ pointer(window, "pointermove", 103);
+ pointer(window, "pointerup", 103);
+
+ expect(onSizingChange).not.toHaveBeenCalled();
+ });
+
+ it("commits the rendered width plus the delta once dragging starts", () => {
+ const { onSizingChange, handle } = setup();
+
+ pointer(handle, "pointerdown", 100);
+ pointer(window, "pointermove", 110);
+ pointer(window, "pointerup", 110);
+
+ expect(onSizingChange).toHaveBeenCalledWith({ status: 210, owner: 120 });
+ });
+
+ it("pins every column to its rendered width on the first drag frame", () => {
+ const { onSizingChange, handle } = setup();
+
+ pointer(handle, "pointerdown", 100);
+ pointer(window, "pointermove", 110);
+
+ // Without this, committing `status` would change how much leftover space
+ // fixed table-layout has to share out, resizing `owner` mid-drag and
+ // pushing the dragged edge away from the pointer.
+ expect(onSizingChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({ owner: 120 }),
+ );
+
+ // Measured once: later frames must not re-read a width that has moved.
+ pointer(window, "pointermove", 300);
+ expect(onSizingChange).toHaveBeenLastCalledWith({ status: 400, owner: 120 });
+ });
+
+ it("ends the gesture when the window loses focus mid-drag", () => {
+ const { onSizingChange, handle } = setup();
+
+ pointer(handle, "pointerdown", 100);
+ pointer(window, "pointermove", 110);
+ expect(onSizingChange).toHaveBeenLastCalledWith({ status: 210, owner: 120 });
+
+ // Switching apps or releasing outside the window never delivers pointerup.
+ act(() => {
+ window.dispatchEvent(new Event("blur"));
+ });
+ pointer(window, "pointermove", 400);
+
+ expect(onSizingChange).toHaveBeenLastCalledWith({ status: 210, owner: 120 });
+ });
+
+ it("publishes column widths as custom properties the cells reference", () => {
+ setup();
+
+ const table = document.querySelector("table")!;
+ expect(table.style.getPropertyValue("--col-status-size")).toBe("150px");
+ expect(table.style.getPropertyValue("--col-owner-size")).toBe("90px");
+
+ // Cells must not carry a resolved number, or a resize would have to
+ // re-render each one to update it.
+ const cell = document.querySelector<HTMLElement>("tbody td")!;
+ expect(cell.style.width).toBe("var(--col-status-size)");
+ });
+
+ it("stops re-rendering body cells while a column is being dragged", () => {
+ const { handle } = setup();
+ const cellRenders = () =>
+ document.querySelectorAll('[data-slot="table-cell"]').length;
+
+ const before = cellRenders();
+ expect(before).toBeGreaterThan(0);
+
+ pointer(handle, "pointerdown", 100);
+ pointer(window, "pointermove", 200);
+
+ // The memoized body keeps the same cells mounted; only the <table>'s
+ // custom property changes, which the browser applies without React.
+ expect(cellRenders()).toBe(before);
+ expect(
+ document.querySelector("table")!.style.getPropertyValue("--col-status-size"),
+ ).toBe("300px");
+ });
+
+ it("sizes a column to its widest rendered cell on double-click", () => {
+ const { onSizingChange, handle } = setup();
+
+ // Fixed table-layout ignores content and the cells truncate their own
+ // text, so the measurement lifts both constraints before reading. Stand in
+ // for the layout jsdom will not perform.
+ for (const cell of document.querySelectorAll<HTMLElement>(
+ '[data-column-id="status"]',
+ )) {
+ cell.getBoundingClientRect = () =>
+ ({ width: cell.tagName === "TH" ? 96 : 268 }) as DOMRect;
+ }
+
+ act(() => {
+ handle.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
+ });
+
+ // The widest cell wins, not the header and not the current width.
+ expect(onSizingChange).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 268 }),
+ );
+ });
+
+ it("leaves the column alone when double-clicked with nothing rendered", () => {
+ const { onSizingChange, handle } = setup();
+
+ for (const cell of document.querySelectorAll<HTMLElement>(
+ '[data-column-id="status"]',
+ )) {
+ cell.getBoundingClientRect = () => ({ width: 0 }) as DOMRect;
+ }
+
+ act(() => {
+ handle.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
+ });
+
+ // A zero measurement means the column was never laid out; committing it
+ // would collapse the column to its minimum for no reason.
+ expect(onSizingChange).not.toHaveBeenCalled();
+ });
+
+ it("casts a shadow past the frozen columns only once scrolled sideways", () => {
+ render(<ResizableTable onSizingChange={vi.fn()} pinFirstColumn />);
+
+ const scroller = document.querySelector<HTMLElement>(".overflow-auto")!;
+ const shadow = () =>
+ document.querySelector<HTMLElement>(
+ '[data-slot="data-table-pinned-shadow"]',
+ );
+
+ // The border between frozen and scrolling columns is permanent and says
+ // where the boundary is. The shadow says something is passing underneath
+ // right now, so at rest there is nothing for it to report.
+ expect(shadow()).toBeNull();
+
+ scroller.scrollLeft = 120;
+ act(() => {
+ scroller.dispatchEvent(new Event("scroll"));
+ });
+ expect(shadow()).not.toBeNull();
+
+ scroller.scrollLeft = 0;
+ act(() => {
+ scroller.dispatchEvent(new Event("scroll"));
+ });
+ expect(shadow()).toBeNull();
+ });
+
+ it("places the shadow at the frozen block's measured edge", () => {
+ render(<ResizableTable onSizingChange={vi.fn()} pinFirstColumn />);
+
+ const scroller = document.querySelector<HTMLElement>(".overflow-auto")!;
+ // Rendered widths diverge from configured ones under fixed table-layout,
+ // so the boundary is read off the DOM rather than summed from column
+ // sizes — summing put the shadow in the middle of visible content.
+ const edge = document.querySelector<HTMLElement>(
+ "thead th[data-pinned-edge]",
+ )!;
+ edge.getBoundingClientRect = () =>
+ ({ right: 240, left: 0, width: 240 }) as DOMRect;
+ scroller.getBoundingClientRect = () =>
+ ({ left: 40, right: 900, width: 860 }) as DOMRect;
+
+ scroller.scrollLeft = 120;
+ act(() => {
+ scroller.dispatchEvent(new Event("scroll"));
+ });
+
+ expect(
+ document.querySelector<HTMLElement>(
+ '[data-slot="data-table-pinned-shadow"]',
+ )!.style.left,
+ ).toBe("200px");
+ });
+
+ it("covers the viewport with a cursor layer only while dragging", () => {
+ const { handle } = setup();
+ const overlay = () =>
+ document.querySelector('[data-slot="data-table-resize-overlay"]');
+
+ expect(overlay()).toBeNull();
+
+ pointer(handle, "pointerdown", 100);
+ expect(overlay()).toHaveClass("cursor-col-resize");
+
+ pointer(window, "pointerup", 100);
+ expect(overlay()).toBeNull();
+ });
+});
diff --git a/packages/views/issues/components/data-table-sticky.test.tsx b/packages/views/issues/components/data-table-sticky.test.tsx
index 7a98951e70..1a5a56a18a 100644
--- a/packages/views/issues/components/data-table-sticky.test.tsx
+++ b/packages/views/issues/components/data-table-sticky.test.tsx
@@ -4,9 +4,28 @@ import {
useReactTable,
type ColumnDef,
} from "@tanstack/react-table";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { DataTable } from "@multica/ui/components/ui/data-table";
+// jsdom has no layout, so the real virtualizer sees a zero-height viewport and
+// renders nothing. The stand-in keeps measureElement pointed at a spy, which is
+// the hook rows have to reach for their height to be corrected.
+const measured = vi.hoisted(() => [] as (HTMLElement | null)[]);
+vi.mock("@tanstack/react-virtual", () => ({
+ useVirtualizer: ({ count }: { count: number }) => ({
+ getVirtualItems: () =>
+ Array.from({ length: count }, (_, index) => ({
+ index,
+ key: index,
+ start: index * 41,
+ end: (index + 1) * 41,
+ size: 41,
+ })),
+ getTotalSize: () => count * 41,
+ measureElement: (element: HTMLElement | null) => measured.push(element),
+ }),
+}));
+
type Row = {
title: string;
status: string;
@@ -28,7 +47,66 @@ function PinnedTable() {
return <DataTable table={table} />;
}
+function VirtualizedTable() {
+ const table = useReactTable({
+ data: [
+ { title: "First", status: "todo" },
+ { title: "Second", status: "done" },
+ ],
+ columns,
+ getCoreRowModel: getCoreRowModel(),
+ });
+
+ return (
+ <DataTable
+ table={table}
+ virtualizeRows
+ // Exercises both paths: a standard row and one the caller builds.
+ renderRow={(row) =>
+ row.index === 1 ? (
+ <tr data-slot="custom-row">
+ <td colSpan={2}>Group header</td>
+ </tr>
+ ) : null
+ }
+ />
+ );
+}
+
describe("DataTable pinned columns", () => {
+ it("tags every virtualized row so it reports its own height", () => {
+ render(<VirtualizedTable />);
+
+ // Group headers and end-of-column footers are shorter than a data row, so
+ // one estimate for all of them drifts from the real layout as they
+ // accumulate. Both the standard rows and the ones renderRow builds have to
+ // carry data-index and the measuring ref for the virtualizer to correct it.
+ const rows = document.querySelectorAll("tbody tr[data-index]");
+ expect(rows.length).toBe(2);
+ expect([...rows].map((row) => row.getAttribute("data-index"))).toEqual([
+ "0",
+ "1",
+ ]);
+ expect(document.querySelector('tbody tr[data-slot="custom-row"]')).toHaveAttribute(
+ "data-index",
+ );
+ expect(measured.filter(Boolean).length).toBe(2);
+ });
+
+ it("keeps the header strip off the compositor's blur path", () => {
+ render(<PinnedTable />);
+
+ const strip = document.querySelector("thead")!;
+ // A backdrop-filter on a sticky element with content scrolling beneath it
+ // recomputes its backdrop every frame while virtualisation churns the rows
+ // under it, and the strip flickers black (electron#12906). The mix resolves
+ // to the same colour bg-muted/30 composited to.
+ expect(strip).toHaveClass(
+ "bg-[color-mix(in_oklab,var(--muted)_30%,var(--background))]",
+ );
+ expect(strip).not.toHaveClass("backdrop-blur");
+ });
+
it("uses opaque backgrounds so scrolled columns cannot show through", () => {
render(<PinnedTable />);
diff --git a/packages/views/issues/components/table-view-model.ts b/packages/views/issues/components/table-view-model.ts
index ca6bb5bbf2..3285ef9f06 100644
--- a/packages/views/issues/components/table-view-model.ts
+++ b/packages/views/issues/components/table-view-model.ts
@@ -34,12 +34,22 @@ export type IssueTableDisplayRow =
hasChildren: boolean;
collapsed: boolean;
}
+ // Stands in for a row that has not arrived yet. Cold loads render these in
+ // the table's own grid rather than swapping the surface for a generic
+ // placeholder: columns, widths and the header are known before any data is,
+ // so only the rows need standing in for, and the layout does not shift when
+ // they are replaced.
+ | { kind: "skeleton"; key: string }
+ // Carries the state rather than a finished label: the row renders through
+ // ListLoadMoreFooter, the same footer Board / List / Swimlane use, which owns
+ // the wording and the styling for each state.
| {
kind: "load_more";
key: string;
- label: string;
- loading: boolean;
- autoLoad?: boolean;
+ state: "loading" | "has_more" | "error" | "end";
+ // Rows past this many mean the branch actually paginated, which is what
+ // decides whether reaching the end is worth marking.
+ total: number;
onLoad?: () => void;
};
diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsx
index 2e84e548a0..bc98ed72da 100644
--- a/packages/views/issues/components/table-view.tsx
+++ b/packages/views/issues/components/table-view.tsx
@@ -3,6 +3,7 @@
import {
useCallback,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
useState,
@@ -12,17 +13,18 @@ import {
KeyboardSensor,
PointerSensor,
closestCenter,
+ useDndContext,
useSensor,
useSensors,
type DragEndEvent,
} from "@dnd-kit/core";
+import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";
import {
SortableContext,
horizontalListSortingStrategy,
sortableKeyboardCoordinates,
useSortable,
} from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
import {
getCoreRowModel,
useReactTable,
@@ -65,6 +67,7 @@ import {
TableCell,
TableRow,
} from "@multica/ui/components/ui/table";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { cn } from "@multica/ui/lib/utils";
import { ApiError } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
@@ -135,9 +138,13 @@ import {
type IssueTableDisplayRow,
} from "./table-view-model";
import type { ChildProgress } from "./list-row";
-import { InfiniteScrollSentinel } from "./infinite-scroll-sentinel";
+import { ListLoadMoreFooter } from "./list-load-more-footer";
import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";
+// Enough placeholder rows to cover a typical viewport; the virtualizer only
+// mounts what fits, so overshooting costs nothing.
+const SKELETON_ROW_COUNT = 12;
+
const SELECT_COLUMN_ID = "__select";
const ADD_COLUMN_ID = "__add";
@@ -366,21 +373,68 @@ function SortableColumnHeader({
const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
useSortable({ id: columnKey, disabled: !sortable });
const active = sortField === sortBy;
+ // Any column in flight, not only this one: the neighbours shift to open a
+ // gap, and each is clipped by its own cell just the same.
+ const isReordering = useDndContext().active != null;
+ const nodeRef = useRef<HTMLDivElement | null>(null);
+
+ // The cell clips its own content, which is what made a dragged column look
+ // like it vanished rather than travelled. The clip only earns its keep at
+ // rest, capping a label wider than its column, so it is lifted for the length
+ // of a reorder and the column in hand is raised over its neighbours.
+ //
+ // Only overflow and stacking are touched. Transforming the <th> itself would
+ // carry the header's full height along, but `transform` on a table cell is a
+ // corner of the spec browsers take liberties with — Chromium lifts the cell
+ // out of the table's box model and its geometry stops matching the row. The
+ // wrapper below is padded out to the cell's size instead.
+ useLayoutEffect(() => {
+ const cell = nodeRef.current?.closest("th");
+ if (!cell || !isReordering) return;
+ cell.style.overflow = "visible";
+ if (isDragging) cell.style.zIndex = "20";
+ return () => {
+ cell.style.removeProperty("overflow");
+ cell.style.removeProperty("z-index");
+ };
+ }, [isDragging, isReordering]);
return (
<div
- ref={setNodeRef}
- style={{ transform: CSS.Transform.toString(transform), transition }}
+ ref={(node) => {
+ nodeRef.current = node;
+ setNodeRef(node);
+ }}
+ // Horizontal travel only. dnd-kit's layout animation also hands back
+ // scaleX/scaleY — old rect over new rect — to tween an item into the
+ // shape of the slot it landed in. Between two tabs of equal width that
+ // ratio is 1 and never shows; between two columns it is not, so a 174px
+ // column swapping with a 96px one gets stretched to 1.8x on the way.
+ // Reordering columns changes no column's width, so there is nothing for
+ // a shape tween to say here. The move and the settle stay animated
+ // through `transition`.
+ style={{
+ transform: transform ? `translate3d(${transform.x}px, 0, 0)` : undefined,
+ transition,
+ }}
+ // The wrapper spans the cell's own box — the negative margins undo the
+ // <th>'s padding and put it back inside — so it renders exactly as at
+ // rest while being what travels: a header-sized block rather than the
+ // line of text in it. Height is derived rather than fixed at h-8: the
+ // strip is taller than the cell's nominal height once row borders are in.
className={cn(
- "group/header flex min-w-0 items-center",
- isDragging && "opacity-40",
+ "group/header -mx-4 -my-2 flex h-[calc(100%+1rem)] min-w-0 items-center px-4",
+ isDragging && "opacity-60",
)}
>
{sortable && (
<button
type="button"
aria-label={reorderLabel}
- className="-ml-2 mr-0.5 rounded p-0.5 text-muted-foreground/50 opacity-0 hover:bg-accent hover:text-muted-foreground group-hover/header:opacity-100 focus-visible:opacity-100"
+ className={cn(
+ "-ml-2 mr-0.5 rounded p-0.5 text-muted-foreground/50 opacity-0 hover:bg-accent hover:text-muted-foreground group-hover/header:opacity-100 focus-visible:opacity-100",
+ isDragging ? "cursor-grabbing opacity-100" : "cursor-grab",
+ )}
{...attributes}
{...listeners}
>
@@ -388,9 +442,7 @@ function SortableColumnHeader({
</button>
)}
<DropdownMenu>
- <DropdownMenuTrigger
- className="flex min-w-0 items-center gap-1 rounded px-1.5 py-1 hover:bg-accent"
- >
+ <DropdownMenuTrigger className="flex min-w-0 items-center gap-1 rounded px-1.5 py-1 hover:bg-accent">
<span className="truncate">{label}</span>
{active &&
(sortDirection === "asc" ? (
@@ -628,7 +680,7 @@ export function InlineTitle({
return (
<div
- className="flex min-w-0 items-center gap-1.5"
+ className="group/title relative flex min-w-0 items-center gap-1.5"
style={{ paddingLeft: row.depth * 18 }}
// Record whether the gesture began while editing (mousedown fires before
// the blur that commits), then swallow that click in the capture phase —
@@ -695,29 +747,48 @@ export function InlineTitle({
>
{row.issue.title}
</button>
- <button
- type="button"
- aria-label={createSubIssueLabel}
- className="shrink-0 rounded p-1 text-muted-foreground/60 opacity-0 hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100"
- onClick={(event) => {
- event.stopPropagation();
- onCreateSubIssue();
- }}
- >
- <Plus className="size-3" />
- </button>
- <button
- type="button"
- aria-label={renameLabel}
- className="shrink-0 rounded p-1 text-muted-foreground/60 opacity-0 hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100"
- onClick={(event) => {
- event.stopPropagation();
- setDraft(row.issue.title);
- onEditingChange(true);
- }}
- >
- <Pencil className="size-3" />
- </button>
+ {/* Lifted out of the flex flow, the way SidebarMenuAction is. Laid
+ * out inline these two reserved ~40px of the title column for
+ * buttons that are invisible until hovered — and title is the
+ * column with the least room to spare. The gradient fades the text
+ * running underneath rather than letting the icons sit on top of
+ * it; the sidebar has no need for one because its labels are short,
+ * but a title runs to the cell's edge. focus-within keeps them
+ * reachable by keyboard, where hover never fires. */}
+ {/* The fade has to be whatever the cell is painted with at the
+ * moment the actions show, and a hovered row is not the resting
+ * background — pinned cells switch to the muted mix on hover, so
+ * the gradient follows. */}
+ {/* Keyed to the title cell, not the row: these act on the title,
+ * and offering them from anywhere along a row puts them under the
+ * pointer while it is somewhere else entirely. The fade still
+ * follows the row's hover colour, since that is what the cell is
+ * painted with when they appear. */}
+ <span className="pointer-events-none absolute inset-y-0 right-0 flex items-center gap-0.5 bg-gradient-to-l from-background from-70% to-transparent pr-1 pl-8 opacity-0 transition-opacity group-hover:from-[color-mix(in_oklab,var(--muted)_50%,var(--background))] group-hover/title:pointer-events-auto group-hover/title:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100">
+ <button
+ type="button"
+ aria-label={createSubIssueLabel}
+ className="rounded p-1 text-muted-foreground/60 hover:bg-accent hover:text-foreground"
+ onClick={(event) => {
+ event.stopPropagation();
+ onCreateSubIssue();
+ }}
+ >
+ <Plus className="size-3" />
+ </button>
+ <button
+ type="button"
+ aria-label={renameLabel}
+ className="rounded p-1 text-muted-foreground/60 hover:bg-accent hover:text-foreground"
+ onClick={(event) => {
+ event.stopPropagation();
+ setDraft(row.issue.title);
+ onEditingChange(true);
+ }}
+ >
+ <Pencil className="size-3" />
+ </button>
+ </span>
</>
)}
</div>
@@ -774,7 +845,11 @@ function LazyLabelCell({
);
}
-type IssueTableGroupRowProps = {
+// Extends the <tr> props so the virtualizer's measuring ref and data-index,
+// which DataTable clones onto whatever renderRow returns, reach the element
+// instead of being absorbed here. A group header is shorter than a data row,
+// so it is exactly the kind of row the measurement exists for.
+type IssueTableGroupRowProps = React.ComponentProps<"tr"> & {
group: Extract<IssueTableDisplayRow, { kind: "group" }>;
colSpan: number;
onToggle: () => void;
@@ -784,9 +859,11 @@ export function IssueTableGroupRow({
group,
colSpan,
onToggle,
+ ...rowProps
}: IssueTableGroupRowProps) {
return (
<TableRow
+ {...rowProps}
className="bg-muted/40 hover:bg-muted/60"
onClick={onToggle}
>
@@ -1011,6 +1088,12 @@ function IssueTableBodyCell({
meta.editingCellKey,
meta.setEditingCellKey,
);
+ // Placeholder rows go through the ordinary cell renderer so they inherit the
+ // real column widths, pinning and borders — the grid is already correct
+ // before any data arrives, so the rows swap in without shifting anything.
+ if (row.original.kind === "skeleton") {
+ return <Skeleton className="h-3.5 w-full" />;
+ }
if (row.original.kind !== "issue") return null;
const issueRow = row.original;
const issue = issueRow.issue;
@@ -1711,9 +1794,8 @@ export function TableView({
result.push({
kind: "load_more",
key: `${registered ? "loading" : "activate"}:${key}`,
- label: t(($) => $.table.loading_branch),
- loading: registered,
- autoLoad: !registered,
+ state: registered ? "loading" : "has_more",
+ total: 0,
onLoad: registered
? undefined
: () => activateServerBranch(groupKey, parentId, ancestorIds),
@@ -1724,8 +1806,8 @@ export function TableView({
result.push({
kind: "load_more",
key: `loading:${key}`,
- label: t(($) => $.table.loading_branch),
- loading: true,
+ state: "loading",
+ total: 0,
});
}
for (const row of data.rows) {
@@ -1754,8 +1836,8 @@ export function TableView({
result.push({
kind: "load_more",
key: `retry:${key}`,
- label: t(($) => $.table.load_more_failed_retry),
- loading: false,
+ state: "error",
+ total: data.total,
onLoad: () => retryServerBranch(key),
});
} else if (data.nextCursor) {
@@ -1763,11 +1845,20 @@ export function TableView({
result.push({
kind: "load_more",
key: `more:${key}:${nextCursor}`,
- label: t(($) => $.table.load_more),
- loading: data.loading,
- autoLoad: true,
+ state: data.loading ? "loading" : "has_more",
+ total: data.total,
onLoad: () => loadNextServerBranchPage(key, nextCursor),
});
+ } else if (data.rows.length > 0) {
+ // Reaching the end is only worth marking on a branch that paginated;
+ // the footer applies that rule, so the row is pushed unconditionally
+ // and carries the total for it to judge by.
+ result.push({
+ kind: "load_more",
+ key: `end:${key}`,
+ state: "end",
+ total: data.total,
+ });
}
};
@@ -1794,27 +1885,40 @@ export function TableView({
result.push({
kind: "load_more",
key: "loading:groups",
- label: t(($) => $.table.loading_branch),
- loading: true,
+ state: "loading",
+ total: 0,
});
} else if (usesServerGrouping && serverGroupsError) {
result.push({
kind: "load_more",
key: "retry:groups",
- label: t(($) => $.table.load_failed_retry),
- loading: false,
+ state: "error",
+ total: 0,
onLoad: () => void refetchServerGroups(),
});
} else if (usesServerGrouping && hasNextServerGroupPage) {
result.push({
kind: "load_more",
key: "more:groups",
- label: t(($) => $.table.load_more),
- loading: fetchingNextServerGroupPage,
- autoLoad: true,
+ state: fetchingNextServerGroupPage ? "loading" : "has_more",
+ total: 0,
onLoad: () => void fetchNextServerGroupPage(),
});
}
+
+ // Nothing has landed yet and something is still in flight: show the grid
+ // filled with placeholders instead of one "Loading…" line, which reads as
+ // an empty table more than a loading one.
+ const isColdLoad =
+ !result.some((row) => row.kind === "issue") &&
+ result.some((row) => row.kind === "load_more" && row.state === "loading");
+ if (isColdLoad) {
+ return Array.from({ length: SKELETON_ROW_COUNT }, (_, index) => ({
+ kind: "skeleton" as const,
+ key: `skeleton:${index}`,
+ }));
+ }
+
return result;
}, [
collapsedGroupSet,
@@ -1832,7 +1936,6 @@ export function TableView({
fetchingNextServerGroupPage,
refetchServerGroups,
fetchNextServerGroupPage,
- t,
tableHierarchy,
usesServerGrouping,
]);
@@ -2287,6 +2390,18 @@ export function TableView({
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
+ // Columns only ever swap sideways, so the header should not follow the
+ // pointer up out of its own strip — same constraint the desktop tab bar
+ // puts on tab reordering.
+ modifiers={[restrictToHorizontalAxis]}
+ // Modifiers constrain the drag's movement but not its auto-scrolling,
+ // which reads raw pointer coordinates: drifting a few pixels vertically
+ // while dragging a header sent the rows scrolling underneath it. Zero
+ // on y removes an axis the gesture cannot act on. On x it stays, since
+ // a table wider than its viewport needs it to reach a distant slot, but
+ // the default 0.2 arms it a fifth of the way in from either edge, which
+ // is most of a wide header.
+ autoScroll={{ threshold: { x: 0.05, y: 0 } }}
onDragEnd={handleDragEnd}
>
<SortableContext
@@ -2318,32 +2433,27 @@ export function TableView({
<TableRow className="hover:bg-transparent">
<TableCell
colSpan={table.getVisibleLeafColumns().length}
- className="relative h-9 px-4 py-1"
+ className="p-0"
>
- {loadMoreRow.autoLoad &&
- loadMoreRow.onLoad &&
- !loadMoreRow.loading && (
- <InfiniteScrollSentinel
- onVisible={loadMoreRow.onLoad}
- loading={false}
- rootMargin="240px"
- className="absolute inset-y-0 left-0 w-px"
+ {/* The same footer Board / List / Swimlane end their
+ * columns with. Hand-rolling it here had left the table
+ * as the one surface where a failed page read as muted
+ * body text rather than an error, and where reaching the
+ * end of a paginated branch said nothing at all. The row
+ * only supplies the cell it lives in. */}
+ <div className="sticky left-0 w-full">
+ <ListLoadMoreFooter
+ hasMore={
+ loadMoreRow.state === "loading" ||
+ loadMoreRow.state === "has_more"
+ }
+ isLoading={loadMoreRow.state === "loading"}
+ total={loadMoreRow.total}
+ onLoadMore={() => loadMoreRow.onLoad?.()}
+ isError={loadMoreRow.state === "error"}
+ onRetry={loadMoreRow.onLoad}
/>
- )}
- <button
- type="button"
- disabled={loadMoreRow.loading || !loadMoreRow.onLoad}
- onClick={(event) => {
- event.stopPropagation();
- loadMoreRow.onLoad?.();
- }}
- className="sticky left-4 flex items-center gap-2 text-xs text-muted-foreground enabled:hover:text-foreground disabled:cursor-default"
- >
- {loadMoreRow.loading && (
- <Loader2 className="size-3.5 animate-spin" />
- )}
- {loadMoreRow.label}
- </button>
+ </div>
</TableCell>
</TableRow>
);
diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsx
index 36731f3ebb..18340abfa7 100644
--- a/packages/views/issues/surface/issue-surface.test.tsx
+++ b/packages/views/issues/surface/issue-surface.test.tsx
@@ -430,6 +430,33 @@ describe("IssueSurface — table pagination ownership", () => {
listSquads: vi.fn(() => Promise.resolve([])),
} as unknown as ApiClient);
+ // Continuation is driven by the shared footer's sentinel, the same one
+ // Board / List / Swimlane use — there is no manual button to press, so the
+ // observer has to actually report the footer as visible.
+ vi.stubGlobal(
+ "IntersectionObserver",
+ class {
+ private readonly callback: IntersectionObserverCallback;
+ constructor(callback: IntersectionObserverCallback) {
+ this.callback = callback;
+ }
+ observe(target: Element) {
+ this.callback(
+ [{ isIntersecting: true, target } as IntersectionObserverEntry],
+ this as unknown as IntersectionObserver,
+ );
+ }
+ unobserve() {}
+ disconnect() {}
+ takeRecords() {
+ return [];
+ }
+ root = null;
+ rootMargin = "0px";
+ thresholds = [0];
+ },
+ );
+
render(
<QueryClientProvider client={qc}>
<IssueSurface
@@ -442,12 +469,6 @@ describe("IssueSurface — table pagination ownership", () => {
);
await screen.findByText("First cursor row");
- const loadMoreButton = document.querySelector<HTMLButtonElement>(
- "tbody button.sticky",
- );
- expect(loadMoreButton).not.toBeNull();
- fireEvent.click(loadMoreButton!);
-
await screen.findByText("Second cursor row");
expect(listIssueTableRows).toHaveBeenCalledWith(
expect.objectContaining({ page: { limit: 50, cursor: "cursor-2" } }),
diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsx
index 7133ab015e..6f4ad9c077 100644
--- a/packages/views/issues/surface/issue-surface.tsx
+++ b/packages/views/issues/surface/issue-surface.tsx
@@ -327,19 +327,16 @@ function IssueSurfaceContent({
);
}
+// Table is deliberately absent. It owns its own placeholders, drawn as rows
+// inside its real grid so the header, column widths and toolbar are up before
+// any data is — a surface-level stand-in would replace all of that with bars
+// of a different shape and then jump when the rows arrived.
function IssueSurfaceSkeleton({ mode }: { mode: string }) {
- if (mode === "list" || mode === "table") {
+ if (mode === "list") {
return (
<div className="flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto p-2">
- {mode === "table" && <Skeleton className="mb-1 h-8 w-full" />}
- {Array.from({ length: mode === "table" ? 8 : 4 }).map((_, i) => (
- <Skeleton
- key={i}
- className={cn(
- "w-full",
- mode === "table" ? "h-9 rounded-sm" : "h-10 rounded-lg",
- )}
- />
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-10 w-full rounded-lg" />
))}
</div>
);
diff --git a/packages/views/package.json b/packages/views/package.json
index 566edee0f5..0478095716 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -58,6 +58,7 @@
"dependencies": {
"@base-ui/react": "^1.3.0",
"@dnd-kit/core": "^6.3.1",
+ "@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@floating-ui/dom": "^1.7.6",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a908a936ac..2cc450dac4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -968,6 +968,9 @@ importers:
'@dnd-kit/core':
specifier: ^6.3.1
+ '@dnd-kit/modifiers':
+ specifier: ^9.0.0
'@dnd-kit/sortable':
specifier: ^10.0.0