fix(grid): smooth canvas column interactions

This commit is contained in:
t8y2 committed 2026-07-08 09:45:28 +08:00
1 parent 0747134dc2
commit d2874bf1bb
6 files changed
+424 -127

No files matched your search

+160 -19
View File
@@ -132,6 +132,7 @@ import { allNullColumnIndexes, filterColumnVisibilityOptions, hiddenColumnIndexe
import { columnOrderKeysForIndexes, isDefaultColumnOrder, moveVisibleColumnIndex, orderedColumnIndexes, uniqueDataGridColumnOrderKeys } from "@/lib/dataGrid/dataGridColumnOrder"; import { columnOrderKeysForIndexes, isDefaultColumnOrder, moveVisibleColumnIndex, orderedColumnIndexes, uniqueDataGridColumnOrderKeys } from "@/lib/dataGrid/dataGridColumnOrder";
import { dataGridColumnLayoutScopeKey, loadDataGridColumnOrder, removeDataGridColumnOrder, saveDataGridColumnOrder } from "@/lib/dataGrid/dataGridColumnLayoutStorage"; import { dataGridColumnLayoutScopeKey, loadDataGridColumnOrder, removeDataGridColumnOrder, saveDataGridColumnOrder } from "@/lib/dataGrid/dataGridColumnLayoutStorage";
import { parseClipboardTable, summarizeSelection } from "@/lib/dataGrid/gridSelection"; import { parseClipboardTable, summarizeSelection } from "@/lib/dataGrid/gridSelection";
import { columnHeaderCanvasPointerDisabled, columnHeaderClickShouldBeSuppressed, columnHeaderPreviewOffsetForColumn, columnHeaderTooltipDisabled } from "@/lib/dataGrid/dataGridColumnHeaderInteraction";
import { useToast } from "@/composables/useToast"; import { useToast } from "@/composables/useToast";
import { useDataGridExport } from "@/composables/useDataGridExport"; import { useDataGridExport } from "@/composables/useDataGridExport";
@@ -3019,7 +3020,78 @@ type ColumnHeaderDragState = {
dragging: boolean; dragging: boolean;
}; };
const columnHeaderDragState = ref<ColumnHeaderDragState | null>(null); const columnHeaderDragState = ref<ColumnHeaderDragState | null>(null);
const columnHeaderResizeActive = ref(false);
let columnHeaderDragClickGuardUntil = 0; let columnHeaderDragClickGuardUntil = 0;
let columnHeaderSuppressNextClick = false;
let columnHeaderSuppressClickTimer = 0;
let columnHeaderDragFrame = 0;
let columnHeaderPendingClientX = 0;
let columnHeaderResizeListenersCleanup: (() => void) | null = null;
const columnHeaderTooltipsDisabled = computed(() =>
columnHeaderTooltipDisabled({
columnDragActive: columnHeaderDragState.value !== null,
columnResizeActive: columnHeaderResizeActive.value,
}),
);
function columnHeaderPointerInteractionActive(): boolean {
return columnHeaderCanvasPointerDisabled({
columnDragActive: columnHeaderDragState.value !== null,
columnResizeActive: columnHeaderResizeActive.value,
});
}
function finishColumnHeaderResizeInteraction() {
clearColumnHeaderResizeListeners();
requestAnimationFrame(() => {
columnHeaderResizeActive.value = false;
});
}
function clearColumnHeaderResizeListeners() {
if (!columnHeaderResizeListenersCleanup) return;
columnHeaderResizeListenersCleanup();
columnHeaderResizeListenersCleanup = null;
}
function clearColumnHeaderClickGuard() {
columnHeaderSuppressNextClick = false;
columnHeaderDragClickGuardUntil = 0;
if (columnHeaderSuppressClickTimer) {
window.clearTimeout(columnHeaderSuppressClickTimer);
columnHeaderSuppressClickTimer = 0;
}
}
function armColumnHeaderClickGuard() {
clearColumnHeaderClickGuard();
columnHeaderSuppressNextClick = true;
columnHeaderDragClickGuardUntil = Date.now() + 800;
columnHeaderSuppressClickTimer = window.setTimeout(() => {
clearColumnHeaderClickGuard();
}, 800);
}
function startColumnHeaderResize(visibleColIdx: number, event: MouseEvent) {
// Browser hover state can stick to multiple header cells during pointer drags,
// so keep header tooltips closed until the resize gesture has fully settled.
clearColumnHeaderResizeListeners();
columnHeaderResizeActive.value = true;
armColumnHeaderClickGuard();
onCanvasMouseLeave();
const finishResize = () => {
armColumnHeaderClickGuard();
finishColumnHeaderResizeInteraction();
};
columnHeaderResizeListenersCleanup = () => {
window.removeEventListener("mouseup", finishResize, true);
window.removeEventListener("blur", finishResize, true);
};
window.addEventListener("mouseup", finishResize, true);
window.addEventListener("blur", finishResize, true);
onResizeStart(visibleColIdx, event);
}
function columnHeaderInteractiveTarget(target: EventTarget | null): boolean { function columnHeaderInteractiveTarget(target: EventTarget | null): boolean {
return target instanceof HTMLElement && !!target.closest("button, input, textarea, select, [contenteditable='true'], [role='button'], [data-column-resize-handle]"); return target instanceof HTMLElement && !!target.closest("button, input, textarea, select, [contenteditable='true'], [role='button'], [data-column-resize-handle]");
@@ -3036,6 +3108,32 @@ function columnHeaderDropTargetVisibleIndex(clientX: number): number {
return visibleColumnIndexes.value.length; return visibleColumnIndexes.value.length;
} }
function applyColumnHeaderDragPreview() {
columnHeaderDragFrame = 0;
const state = columnHeaderDragState.value;
if (!state?.dragging) return;
state.currentX = columnHeaderPendingClientX;
state.targetVisibleIndex = columnHeaderDropTargetVisibleIndex(columnHeaderPendingClientX);
if (useCanvasGridRows.value) scheduleCanvasDraw();
}
function scheduleColumnHeaderDragPreview(clientX: number) {
columnHeaderPendingClientX = clientX;
if (columnHeaderDragFrame) return;
columnHeaderDragFrame = requestAnimationFrame(applyColumnHeaderDragPreview);
}
function flushColumnHeaderDragPreview() {
if (columnHeaderDragFrame) cancelAnimationFrame(columnHeaderDragFrame);
applyColumnHeaderDragPreview();
}
function cancelColumnHeaderDragPreview() {
if (!columnHeaderDragFrame) return;
cancelAnimationFrame(columnHeaderDragFrame);
columnHeaderDragFrame = 0;
}
function columnHeaderLayoutRects(): { visibleIndex: number; left: number; width: number }[] { function columnHeaderLayoutRects(): { visibleIndex: number; left: number; width: number }[] {
const header = headerRef.value; const header = headerRef.value;
return Array.from(header?.querySelectorAll<HTMLElement>("[data-visible-col-index]") ?? []) return Array.from(header?.querySelectorAll<HTMLElement>("[data-visible-col-index]") ?? [])
@@ -3053,12 +3151,15 @@ function columnHeaderLayoutRects(): { visibleIndex: number; left: number; width:
function stopColumnHeaderDrag(commit: boolean) { function stopColumnHeaderDrag(commit: boolean) {
const state = columnHeaderDragState.value; const state = columnHeaderDragState.value;
if (!state) return; if (!state) return;
const hadCanvasPreview = useCanvasGridRows.value && state.dragging;
window.removeEventListener("pointermove", onColumnHeaderPointerMove, true); window.removeEventListener("pointermove", onColumnHeaderPointerMove, true);
window.removeEventListener("pointerup", onColumnHeaderPointerUp, true); window.removeEventListener("pointerup", onColumnHeaderPointerUp, true);
window.removeEventListener("pointercancel", onColumnHeaderPointerCancel, true); window.removeEventListener("pointercancel", onColumnHeaderPointerCancel, true);
cancelColumnHeaderDragPreview();
document.body.style.userSelect = ""; document.body.style.userSelect = "";
columnHeaderDragState.value = null; columnHeaderDragState.value = null;
if (state.dragging) columnHeaderDragClickGuardUntil = Date.now() + 250; if (hadCanvasPreview) scheduleCanvasDraw();
if (state.dragging) armColumnHeaderClickGuard();
if (!commit || !state.dragging || state.sourceVisibleIndex === state.targetVisibleIndex) return; if (!commit || !state.dragging || state.sourceVisibleIndex === state.targetVisibleIndex) return;
const next = moveVisibleColumnIndex({ const next = moveVisibleColumnIndex({
orderedIndexes: orderedDisplayableColumnIndexes.value, orderedIndexes: orderedDisplayableColumnIndexes.value,
@@ -3077,14 +3178,16 @@ function onColumnHeaderPointerMove(event: PointerEvent) {
if (!state.dragging && moved) { if (!state.dragging && moved) {
state.dragging = true; state.dragging = true;
document.body.style.userSelect = "none"; document.body.style.userSelect = "none";
onCanvasMouseLeave();
} }
if (!state.dragging) return; if (!state.dragging) return;
event.preventDefault(); event.preventDefault();
state.currentX = event.clientX; scheduleColumnHeaderDragPreview(event.clientX);
state.targetVisibleIndex = columnHeaderDropTargetVisibleIndex(event.clientX);
} }
function onColumnHeaderPointerUp() { function onColumnHeaderPointerUp(event: PointerEvent) {
columnHeaderPendingClientX = event.clientX;
flushColumnHeaderDragPreview();
stopColumnHeaderDrag(true); stopColumnHeaderDrag(true);
} }
@@ -3103,17 +3206,35 @@ function startColumnHeaderDrag(visibleColIdx: number, event: PointerEvent) {
columnRects: columnHeaderLayoutRects(), columnRects: columnHeaderLayoutRects(),
dragging: false, dragging: false,
}; };
columnHeaderPendingClientX = event.clientX;
window.addEventListener("pointermove", onColumnHeaderPointerMove, true); window.addEventListener("pointermove", onColumnHeaderPointerMove, true);
window.addEventListener("pointerup", onColumnHeaderPointerUp, true); window.addEventListener("pointerup", onColumnHeaderPointerUp, true);
window.addEventListener("pointercancel", onColumnHeaderPointerCancel, true); window.addEventListener("pointercancel", onColumnHeaderPointerCancel, true);
} }
function onHeaderClick(visibleColIdx: number, event: MouseEvent) { function suppressHeaderClickIfNeeded(event: MouseEvent): boolean {
if (Date.now() < columnHeaderDragClickGuardUntil) { if (
event.preventDefault(); !columnHeaderClickShouldBeSuppressed({
event.stopPropagation(); now: Date.now(),
return; guardUntil: columnHeaderDragClickGuardUntil,
suppressNextClick: columnHeaderSuppressNextClick,
})
) {
return false;
} }
clearColumnHeaderClickGuard();
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
return true;
}
function onHeaderClickCapture(event: MouseEvent) {
suppressHeaderClickIfNeeded(event);
}
function onHeaderClick(visibleColIdx: number, event: MouseEvent) {
if (suppressHeaderClickIfNeeded(event)) return;
selectColumn(visibleColIdx, event); selectColumn(visibleColIdx, event);
} }
@@ -3126,14 +3247,16 @@ function columnHeaderDragClass(visibleColIdx: number) {
function columnHeaderPreviewOffset(visibleColIdx: number): number { function columnHeaderPreviewOffset(visibleColIdx: number): number {
const state = columnHeaderDragState.value; const state = columnHeaderDragState.value;
if (!state?.dragging) return 0; if (!state) return 0;
const sourceIndex = state.sourceVisibleIndex; return columnHeaderPreviewOffsetForColumn({
if (visibleColIdx === sourceIndex) return state.currentX - state.startX; columnDragActive: state.dragging,
const targetIndex = state.targetVisibleIndex; visibleColIdx,
const sourceWidth = renderedColumnWidths.value[sourceIndex] ?? 0; sourceVisibleIndex: state.sourceVisibleIndex,
if (targetIndex < sourceIndex && visibleColIdx >= targetIndex && visibleColIdx < sourceIndex) return sourceWidth; targetVisibleIndex: state.targetVisibleIndex,
if (targetIndex > sourceIndex && visibleColIdx > sourceIndex && visibleColIdx <= targetIndex) return -sourceWidth; startX: state.startX,
return 0; currentX: state.currentX,
sourceWidth: renderedColumnWidths.value[state.sourceVisibleIndex] ?? 0,
});
} }
function columnHeaderStyle(visibleColIdx: number) { function columnHeaderStyle(visibleColIdx: number) {
@@ -3147,6 +3270,12 @@ function columnHeaderStyle(visibleColIdx: number) {
}; };
} }
const columnHeaderPreviewOffsets = computed(() => renderedColumnWidths.value.map((_, visibleColIdx) => columnHeaderPreviewOffset(visibleColIdx)));
const columnHeaderPreviewSourceVisibleIndex = computed(() => {
const state = columnHeaderDragState.value;
return state?.dragging ? state.sourceVisibleIndex : null;
});
function columnContentOffsetLeft(visibleColIdx: number): number { function columnContentOffsetLeft(visibleColIdx: number): number {
return DATA_GRID_ROW_NUM_WIDTH + (renderedColumnOffsets.value[visibleColIdx] ?? 0); return DATA_GRID_ROW_NUM_WIDTH + (renderedColumnOffsets.value[visibleColIdx] ?? 0);
} }
@@ -5462,6 +5591,11 @@ function onCanvasWheel(event: WheelEvent) {
} }
function onCanvasMouseMove(event: MouseEvent) { function onCanvasMouseMove(event: MouseEvent) {
if (columnHeaderPointerInteractionActive()) {
if (canvasRef.value) canvasRef.value.style.cursor = "default";
onCanvasMouseLeave();
return;
}
const hit = canvasHitTest(event); const hit = canvasHitTest(event);
const hitItem = hit ? displayItemAt(hit.rowIndex) : undefined; const hitItem = hit ? displayItemAt(hit.rowIndex) : undefined;
const next = hit && hitItem ? { rowIndex: hitItem.displayIndex, visibleColIdx: hit.rowNumber ? -1 : hit.visibleColIdx } : null; const next = hit && hitItem ? { rowIndex: hitItem.displayIndex, visibleColIdx: hit.rowNumber ? -1 : hit.visibleColIdx } : null;
@@ -5698,6 +5832,8 @@ function drawCanvasGrid() {
rowAt: displayItemAt, rowAt: displayItemAt,
renderedColumnWidths: renderedColumnWidths.value, renderedColumnWidths: renderedColumnWidths.value,
renderedColumnOffsets: renderedColumnOffsets.value, renderedColumnOffsets: renderedColumnOffsets.value,
columnPreviewOffsets: columnHeaderPreviewOffsets.value,
columnPreviewSourceVisibleIndex: columnHeaderPreviewSourceVisibleIndex.value,
visibleColumnIndexes: visibleColumnIndexes.value, visibleColumnIndexes: visibleColumnIndexes.value,
rowNumberWidth: DATA_GRID_ROW_NUM_WIDTH, rowNumberWidth: DATA_GRID_ROW_NUM_WIDTH,
hoverCell: canvasHoverCell.value, hoverCell: canvasHoverCell.value,
@@ -7795,6 +7931,10 @@ onDeactivated(() => {
onUnmounted(() => { onUnmounted(() => {
cleanupFrames(); cleanupFrames();
stopAutoRefreshTimer(); stopAutoRefreshTimer();
cancelColumnHeaderDragPreview();
clearColumnHeaderResizeListeners();
clearColumnHeaderClickGuard();
columnHeaderResizeActive.value = false;
onSearchSplitResizeEnd(); onSearchSplitResizeEnd();
onDdlResizeEnd(); onDdlResizeEnd();
onDetailResizeEnd(); onDetailResizeEnd();
@@ -9016,7 +9156,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
# #
</div> </div>
<div class="shrink-0" :style="{ width: `${horizontalColumnWindow.beforeWidth}px` }" /> <div class="shrink-0" :style="{ width: `${horizontalColumnWindow.beforeWidth}px` }" />
<LightTooltip v-for="col in renderedGridColumns" :key="`${col.name}-${col.actualColIdx}`" :text="col.name" side="bottom" :side-offset="4"> <LightTooltip v-for="col in renderedGridColumns" :key="`${col.name}-${col.actualColIdx}`" :text="col.name" side="bottom" :side-offset="4" :disabled="columnHeaderTooltipsDisabled">
<div <div
class="shrink-0 px-2 py-1.5 border-r border-border whitespace-nowrap hover:bg-gray-200 dark:hover:bg-gray-800 select-none relative overflow-hidden" class="shrink-0 px-2 py-1.5 border-r border-border whitespace-nowrap hover:bg-gray-200 dark:hover:bg-gray-800 select-none relative overflow-hidden"
:class="{ :class="{
@@ -9028,6 +9168,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
:data-grid-column-index="col.actualColIdx" :data-grid-column-index="col.actualColIdx"
:data-visible-col-index="col.visibleColIdx" :data-visible-col-index="col.visibleColIdx"
@pointerdown="startColumnHeaderDrag(col.visibleColIdx, $event)" @pointerdown="startColumnHeaderDrag(col.visibleColIdx, $event)"
@click.capture="onHeaderClickCapture"
@click="onHeaderClick(col.visibleColIdx, $event)" @click="onHeaderClick(col.visibleColIdx, $event)"
@contextmenu="onHeaderContext(col.name, col.actualColIdx)" @contextmenu="onHeaderContext(col.name, col.actualColIdx)"
> >
@@ -9352,7 +9493,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<Database class="h-3.5 w-3.5" /> <Database class="h-3.5 w-3.5" />
</button> </button>
</span> </span>
<div data-column-resize-handle class="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/30" @mousedown.stop="onResizeStart(col.visibleColIdx, $event)" @dblclick.stop="autoFitColumn(col.visibleColIdx)" /> <div data-column-resize-handle class="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/30" @mousedown.stop="startColumnHeaderResize(col.visibleColIdx, $event)" @click.stop.prevent @dblclick.stop="autoFitColumn(col.visibleColIdx)" />
</div> </div>
<template #content> <template #content>
<div class="grid min-w-56 grid-cols-[auto_minmax(0,1fr)] gap-x-2 gap-y-1 px-3 py-2"> <div class="grid min-w-56 grid-cols-[auto_minmax(0,1fr)] gap-x-2 gap-y-1 px-3 py-2">
@@ -47,4 +47,19 @@ describe("useDataGridColumnResize", () => {
expect(resizeDataGridColumnWidth(120, -200)).toBe(DATA_GRID_COL_MIN_WIDTH); expect(resizeDataGridColumnWidth(120, -200)).toBe(DATA_GRID_COL_MIN_WIDTH);
expect(resizeDataGridColumnWidth(120, 30)).toBe(150); expect(resizeDataGridColumnWidth(120, 30)).toBe(150);
}); });
it("publishes a fresh rendered width array when a column is resized", () => {
const state = createResizeState({
columns: ["id", "name"],
rows: [[1, "Alice"]],
});
state.initColumnWidths();
const before = state.renderedColumnWidths.value;
state.columnWidths.value[1] = before[1] + 40;
expect(state.renderedColumnWidths.value).not.toBe(before);
expect(state.renderedColumnWidths.value[1]).toBe(before[1] + 40);
});
}); });
@@ -57,13 +57,36 @@ export function useDataGridColumnResize(options: UseDataGridColumnResizeOptions)
event.preventDefault(); event.preventDefault();
isResizing = true; isResizing = true;
const startX = event.clientX; const startX = event.clientX;
const startWidth = columnWidths.value[colIdx]; const startWidth = columnWidths.value[colIdx] ?? DATA_GRID_COL_MIN_WIDTH;
const onMove = (e: MouseEvent) => { let pendingClientX = startX;
columnWidths.value[colIdx] = resizeDataGridColumnWidth(startWidth, e.clientX - startX); let resizeFrame = 0;
const applyPendingWidth = () => {
resizeFrame = 0;
columnWidths.value[colIdx] = resizeDataGridColumnWidth(startWidth, pendingClientX - startX);
}; };
const onUp = () => {
const scheduleWidthUpdate = (clientX: number) => {
pendingClientX = clientX;
if (resizeFrame) return;
resizeFrame = requestAnimationFrame(applyPendingWidth);
};
const cancelPendingFrame = () => {
if (!resizeFrame) return;
cancelAnimationFrame(resizeFrame);
resizeFrame = 0;
};
const onMove = (e: MouseEvent) => {
scheduleWidthUpdate(e.clientX);
};
const onUp = (e: MouseEvent) => {
document.removeEventListener("mousemove", onMove); document.removeEventListener("mousemove", onMove);
document.removeEventListener("mouseup", onUp); document.removeEventListener("mouseup", onUp);
cancelPendingFrame();
pendingClientX = e.clientX;
applyPendingWidth();
requestAnimationFrame(() => { requestAnimationFrame(() => {
isResizing = false; isResizing = false;
}); });
@@ -83,7 +106,7 @@ export function useDataGridColumnResize(options: UseDataGridColumnResizeOptions)
}); });
} }
const renderedColumnWidths = computed(() => columnWidths.value); const renderedColumnWidths = computed(() => columnWidths.value.slice());
const totalWidth = computed(() => renderedColumnWidths.value.reduce((a, b) => a + b, 0) + DATA_GRID_ROW_NUM_WIDTH); const totalWidth = computed(() => renderedColumnWidths.value.reduce((a, b) => a + b, 0) + DATA_GRID_ROW_NUM_WIDTH);
@@ -43,6 +43,8 @@ export interface DrawCanvasDataGridOptions {
rowAt: (rowIndex: number) => CanvasDataGridRow | undefined; rowAt: (rowIndex: number) => CanvasDataGridRow | undefined;
renderedColumnWidths: number[]; renderedColumnWidths: number[];
renderedColumnOffsets?: number[]; renderedColumnOffsets?: number[];
columnPreviewOffsets?: readonly number[];
columnPreviewSourceVisibleIndex?: number | null;
visibleColumnIndexes: number[]; visibleColumnIndexes: number[];
rowNumberWidth: number; rowNumberWidth: number;
hoverCell: CanvasHoverCell | null; hoverCell: CanvasHoverCell | null;
@@ -216,6 +218,8 @@ export function drawCanvasDataGrid(options: DrawCanvasDataGridOptions) {
rowAt, rowAt,
renderedColumnWidths, renderedColumnWidths,
renderedColumnOffsets, renderedColumnOffsets,
columnPreviewOffsets = [],
columnPreviewSourceVisibleIndex,
visibleColumnIndexes, visibleColumnIndexes,
rowNumberWidth, rowNumberWidth,
hoverCell, hoverCell,
@@ -264,8 +268,14 @@ export function drawCanvasDataGrid(options: DrawCanvasDataGridOptions) {
ctx.textBaseline = "middle"; ctx.textBaseline = "middle";
const offsets = renderedColumnOffsets ?? columnOffsets(renderedColumnWidths); const offsets = renderedColumnOffsets ?? columnOffsets(renderedColumnWidths);
let maxPreviewRightShift = 0;
let maxPreviewLeftShift = 0;
for (const offset of columnPreviewOffsets) {
if (offset > maxPreviewRightShift) maxPreviewRightShift = offset;
else if (-offset > maxPreviewLeftShift) maxPreviewLeftShift = -offset;
}
const contentStart = Math.max(0, scrollLeft - rowNumberWidth); const contentStart = Math.max(0, scrollLeft - rowNumberWidth);
const firstCol = firstVisibleColumn(offsets, contentStart); const firstCol = firstVisibleColumn(offsets, Math.max(0, contentStart - maxPreviewRightShift));
const columnOffset = offsets[firstCol] ?? 0; const columnOffset = offsets[firstCol] ?? 0;
const paintSearchMatches = !isScrolling && searchMatchKeys.size > 0; const paintSearchMatches = !isScrolling && searchMatchKeys.size > 0;
const rowNumberBorderX = crispCanvasLine(rowNumberWidth - 1, dpr); const rowNumberBorderX = crispCanvasLine(rowNumberWidth - 1, dpr);
@@ -312,122 +322,129 @@ export function drawCanvasDataGrid(options: DrawCanvasDataGridOptions) {
ctx.moveTo(0, rowBorderY); ctx.moveTo(0, rowBorderY);
ctx.lineTo(width, rowBorderY); ctx.lineTo(width, rowBorderY);
ctx.stroke(); ctx.stroke();
let x = rowNumberWidth + columnOffset - scrollLeft; const drawCell = (visibleColIdx: number, baseX: number) => {
for (let visibleColIdx = firstCol; visibleColIdx < renderedColumnWidths.length && x < width; visibleColIdx++) {
const colWidth = renderedColumnWidths[visibleColIdx] ?? 0; const colWidth = renderedColumnWidths[visibleColIdx] ?? 0;
const actualColIdx = visibleColumnIndexes[visibleColIdx]; const actualColIdx = visibleColumnIndexes[visibleColIdx];
if (actualColIdx === undefined) { if (actualColIdx === undefined) return;
x += colWidth; const drawX = baseX + (columnPreviewOffsets[visibleColIdx] ?? 0);
continue; if (drawX + colWidth < rowNumberWidth || drawX >= width) return;
const selectedCell = cellIsSelected(item.displayIndex, visibleColIdx);
const rowSelectionVisual = rowCellsUseSelectionVisual(item.id);
const isDirtyCell = item.isDirtyCol[actualColIdx];
const selectedFillVisual = rowSelectionVisual || selectedCell;
const selectedBorderVisual = rowSelectionVisual || selectedCell;
const isSearchMatch = paintSearchMatches && searchMatchKeys.has(`cell:${item.displayIndex}:${actualColIdx}`);
const isCurrentSearchMatch = paintSearchMatches && currentSearchMatch?.displayRow === item.displayIndex && currentSearchMatch.col === actualColIdx;
const clippedX = Math.max(drawX, rowNumberWidth);
const cellPaintWidth = Math.min(width, drawX + colWidth) - clippedX;
if (cellPaintWidth <= 0) return;
if (isDirtyCell && !selectedFillVisual) {
ctx.fillStyle = theme.cellDirty;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
if (hoverCell?.rowIndex === item.displayIndex && hoverCell.visibleColIdx === visibleColIdx && !isScrolling && !isSearchMatch && !isCurrentSearchMatch && !isDirtyCell && cellCanHover(item, actualColIdx)) {
ctx.fillStyle = theme.cellHover;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
if ((rowIsActive || selectedCell) && !item.isDeleted && !isDirtyCell) {
ctx.fillStyle = theme.cellSelectedSingle;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
if (selectedFillVisual && isDirtyCell) {
ctx.fillStyle = theme.cellSelectedDirty;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
if (isSearchMatch) {
ctx.fillStyle = searchFill;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
if (isCurrentSearchMatch) {
ctx.fillStyle = currentSearchFill;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
} }
if (x + colWidth >= rowNumberWidth) {
const selectedCell = cellIsSelected(item.displayIndex, visibleColIdx);
const rowSelectionVisual = rowCellsUseSelectionVisual(item.id);
const isDirtyCell = item.isDirtyCol[actualColIdx];
const selectedFillVisual = rowSelectionVisual || selectedCell;
const selectedBorderVisual = rowSelectionVisual || selectedCell;
const isSearchMatch = paintSearchMatches && searchMatchKeys.has(`cell:${item.displayIndex}:${actualColIdx}`);
const isCurrentSearchMatch = paintSearchMatches && currentSearchMatch?.displayRow === item.displayIndex && currentSearchMatch.col === actualColIdx;
const clippedX = Math.max(x, rowNumberWidth);
const cellPaintWidth = colWidth - Math.max(0, clippedX - x);
if (isDirtyCell && !selectedFillVisual) { ctx.strokeStyle = theme.border;
ctx.fillStyle = theme.cellDirty; ctx.beginPath();
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT); ctx.moveTo(clippedX, rowBorderY);
} ctx.lineTo(Math.min(width, clippedX + cellPaintWidth), rowBorderY);
if (hoverCell?.rowIndex === item.displayIndex && hoverCell.visibleColIdx === visibleColIdx && !isScrolling && !isSearchMatch && !isCurrentSearchMatch && !isDirtyCell && cellCanHover(item, actualColIdx)) { ctx.stroke();
ctx.fillStyle = theme.cellHover;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
if ((rowIsActive || selectedCell) && !item.isDeleted && !isDirtyCell) {
ctx.fillStyle = theme.cellSelectedSingle;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
if (selectedFillVisual && isDirtyCell) {
ctx.fillStyle = theme.cellSelectedDirty;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
if (isSearchMatch) {
ctx.fillStyle = searchFill;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
if (isCurrentSearchMatch) {
ctx.fillStyle = currentSearchFill;
ctx.fillRect(clippedX, y, cellPaintWidth, CANVAS_DATA_GRID_ROW_HEIGHT);
}
ctx.strokeStyle = theme.border; ctx.save();
ctx.beginPath();
ctx.rect(clippedX, y, Math.min(cellPaintWidth, width - clippedX), CANVAS_DATA_GRID_ROW_HEIGHT);
ctx.clip();
const value = item.data[actualColIdx];
ctx.textAlign = "left";
ctx.fillStyle = value === null ? theme.mutedForeground : theme.foreground;
ctx.font = value === null ? italicFont : tabularFont;
setCanvasNumericVariant(ctx, value === null ? "normal" : "tabular-nums");
const textLeft = alignCanvasPixel(drawX + 12, dpr);
const paddedMaxWidth = Math.max(0, drawX + colWidth - textLeft - 12);
const isEditingThisCell = editingCell?.rowId === item.id && editingCell.col === actualColIdx;
const rawDisplayText = item.isDraft && value === null ? (draftCellPlaceholder ?? "") : formatCell(value, actualColIdx);
const displayText = isEditingThisCell ? "" : firstLineCellDisplayValue(rawDisplayText);
const needsTruncation = ctx.measureText(displayText).width > paddedMaxWidth;
const textMaxWidth = needsTruncation ? Math.max(0, drawX + colWidth - textLeft) : paddedMaxWidth;
const text = isEditingThisCell ? displayText : fitCanvasText(ctx, displayText, textMaxWidth - 12);
ctx.fillText(text, textLeft, textY);
if (item.isDeleted && text) {
const textWidth = Math.min(ctx.measureText(text).width, textMaxWidth);
ctx.strokeStyle = theme.foreground;
ctx.beginPath(); ctx.beginPath();
ctx.moveTo(clippedX, rowBorderY); ctx.moveTo(textLeft, textY);
ctx.lineTo(Math.min(width, clippedX + cellPaintWidth), rowBorderY); ctx.lineTo(alignCanvasPixel(textLeft + textWidth, dpr), textY);
ctx.stroke(); ctx.stroke();
}
ctx.restore();
setCanvasNumericVariant(ctx, "normal");
ctx.font = normalFont;
ctx.save(); ctx.strokeStyle = theme.border;
ctx.beginPath();
const columnBorderX = crispCanvasLine(drawX + colWidth - 1, dpr);
ctx.moveTo(columnBorderX, y);
ctx.lineTo(columnBorderX, y + CANVAS_DATA_GRID_ROW_HEIGHT);
ctx.stroke();
if (selectedBorderVisual && cellPaintWidth >= 2) {
const selectedLeftX = clippedX + 0.5;
const selectedRightX = clippedX + cellPaintWidth - 1.5;
const selectedTopY = Math.max(y + 0.5, 1);
const drawSelectedLeftBorder = selectedLeftX >= rowNumberWidth + 0.5;
ctx.strokeStyle = selectedCell && !isDirtyCell ? theme.cellSelectedSingleBorder : theme.cellSelectedBorder;
ctx.beginPath(); ctx.beginPath();
ctx.rect(clippedX, y, Math.min(cellPaintWidth, width - clippedX), CANVAS_DATA_GRID_ROW_HEIGHT); ctx.moveTo(selectedLeftX, selectedTopY);
ctx.clip(); ctx.lineTo(selectedRightX, selectedTopY);
const value = item.data[actualColIdx]; ctx.moveTo(selectedLeftX, rowBorderY);
ctx.textAlign = "left"; ctx.lineTo(selectedRightX, rowBorderY);
ctx.fillStyle = value === null ? theme.mutedForeground : theme.foreground; if (drawSelectedLeftBorder) {
ctx.font = value === null ? italicFont : tabularFont;
setCanvasNumericVariant(ctx, value === null ? "normal" : "tabular-nums");
const textLeft = alignCanvasPixel(x + 12, dpr);
const paddedMaxWidth = Math.max(0, x + colWidth - textLeft - 12);
const isEditingThisCell = editingCell?.rowId === item.id && editingCell.col === actualColIdx;
const rawDisplayText = item.isDraft && value === null ? (draftCellPlaceholder ?? "") : formatCell(value, actualColIdx);
const displayText = isEditingThisCell ? "" : firstLineCellDisplayValue(rawDisplayText);
const needsTruncation = ctx.measureText(displayText).width > paddedMaxWidth;
const textMaxWidth = needsTruncation ? Math.max(0, x + colWidth - textLeft) : paddedMaxWidth;
const text = isEditingThisCell ? displayText : fitCanvasText(ctx, displayText, textMaxWidth - 12);
ctx.fillText(text, textLeft, textY);
if (item.isDeleted && text) {
const textWidth = Math.min(ctx.measureText(text).width, textMaxWidth);
ctx.strokeStyle = theme.foreground;
ctx.beginPath();
ctx.moveTo(textLeft, textY);
ctx.lineTo(alignCanvasPixel(textLeft + textWidth, dpr), textY);
ctx.stroke();
}
ctx.restore();
setCanvasNumericVariant(ctx, "normal");
ctx.font = normalFont;
ctx.strokeStyle = theme.border;
ctx.beginPath();
const columnBorderX = crispCanvasLine(x + colWidth - 1, dpr);
ctx.moveTo(columnBorderX, y);
ctx.lineTo(columnBorderX, y + CANVAS_DATA_GRID_ROW_HEIGHT);
ctx.stroke();
if (selectedBorderVisual && cellPaintWidth >= 2) {
const selectedLeftX = clippedX + 0.5;
const selectedRightX = clippedX + cellPaintWidth - 1.5;
const selectedTopY = Math.max(y + 0.5, 1);
const drawSelectedLeftBorder = selectedLeftX >= rowNumberWidth + 0.5;
ctx.strokeStyle = selectedCell && !isDirtyCell ? theme.cellSelectedSingleBorder : theme.cellSelectedBorder;
ctx.beginPath();
ctx.moveTo(selectedLeftX, selectedTopY); ctx.moveTo(selectedLeftX, selectedTopY);
ctx.lineTo(selectedRightX, selectedTopY); ctx.lineTo(selectedLeftX, rowBorderY);
ctx.moveTo(selectedLeftX, rowBorderY);
ctx.lineTo(selectedRightX, rowBorderY);
if (drawSelectedLeftBorder) {
ctx.moveTo(selectedLeftX, selectedTopY);
ctx.lineTo(selectedLeftX, rowBorderY);
}
ctx.moveTo(selectedRightX, selectedTopY);
ctx.lineTo(selectedRightX, rowBorderY);
ctx.stroke();
}
if (isCurrentSearchMatch) {
ctx.strokeStyle = currentSearchBorder;
ctx.lineWidth = 2;
ctx.strokeRect(clippedX + 1, y + 1, Math.max(0, cellPaintWidth - 2), CANVAS_DATA_GRID_ROW_HEIGHT - 2);
ctx.lineWidth = 1;
} }
ctx.moveTo(selectedRightX, selectedTopY);
ctx.lineTo(selectedRightX, rowBorderY);
ctx.stroke();
} }
if (isCurrentSearchMatch) {
ctx.strokeStyle = currentSearchBorder;
ctx.lineWidth = 2;
ctx.strokeRect(clippedX + 1, y + 1, Math.max(0, cellPaintWidth - 2), CANVAS_DATA_GRID_ROW_HEIGHT - 2);
ctx.lineWidth = 1;
}
};
let x = rowNumberWidth + columnOffset - scrollLeft;
for (let visibleColIdx = firstCol; visibleColIdx < renderedColumnWidths.length && x - maxPreviewLeftShift < width; visibleColIdx++) {
const colWidth = renderedColumnWidths[visibleColIdx] ?? 0;
drawCell(visibleColIdx, x);
x += colWidth; x += colWidth;
} }
if (columnPreviewSourceVisibleIndex !== null && columnPreviewSourceVisibleIndex !== undefined && (columnPreviewOffsets[columnPreviewSourceVisibleIndex] ?? 0) !== 0) {
drawCell(columnPreviewSourceVisibleIndex, rowNumberWidth + (offsets[columnPreviewSourceVisibleIndex] ?? 0) - scrollLeft);
}
ctx.globalAlpha = 1; ctx.globalAlpha = 1;
} }
} }
@@ -0,0 +1,57 @@
export interface ColumnHeaderTooltipState {
columnDragActive: boolean;
columnResizeActive: boolean;
}
export function columnHeaderTooltipDisabled(state: ColumnHeaderTooltipState): boolean {
return state.columnDragActive || state.columnResizeActive;
}
export interface ColumnHeaderCanvasPointerState {
columnDragActive: boolean;
columnResizeActive: boolean;
}
export function columnHeaderCanvasPointerDisabled(state: ColumnHeaderCanvasPointerState): boolean {
return state.columnDragActive || state.columnResizeActive;
}
export interface ColumnHeaderClickGuardState {
now: number;
guardUntil: number;
suppressNextClick: boolean;
}
export function columnHeaderClickShouldBeSuppressed(state: ColumnHeaderClickGuardState): boolean {
return state.suppressNextClick || state.now < state.guardUntil;
}
export interface ColumnHeaderPreviewState {
columnDragActive: boolean;
}
export function columnHeaderPreviewEnabled(state: ColumnHeaderPreviewState): boolean {
return state.columnDragActive;
}
export interface ColumnHeaderPreviewOffsetState {
columnDragActive: boolean;
visibleColIdx: number;
sourceVisibleIndex: number;
targetVisibleIndex: number;
startX: number;
currentX: number;
sourceWidth: number;
}
export function columnHeaderPreviewOffsetForColumn(state: ColumnHeaderPreviewOffsetState): number {
if (!columnHeaderPreviewEnabled(state)) return 0;
if (state.visibleColIdx === state.sourceVisibleIndex) return state.currentX - state.startX;
if (state.targetVisibleIndex < state.sourceVisibleIndex && state.visibleColIdx >= state.targetVisibleIndex && state.visibleColIdx < state.sourceVisibleIndex) {
return state.sourceWidth;
}
if (state.targetVisibleIndex > state.sourceVisibleIndex && state.visibleColIdx > state.sourceVisibleIndex && state.visibleColIdx <= state.targetVisibleIndex) {
return -state.sourceWidth;
}
return 0;
}
@@ -0,0 +1,44 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
import { columnHeaderCanvasPointerDisabled, columnHeaderClickShouldBeSuppressed, columnHeaderPreviewEnabled, columnHeaderPreviewOffsetForColumn, columnHeaderTooltipDisabled } from "../../apps/desktop/src/lib/dataGrid/dataGridColumnHeaderInteraction";
test("keeps column header tooltips closed during column pointer interactions", () => {
assert.equal(columnHeaderTooltipDisabled({ columnDragActive: false, columnResizeActive: false }), false);
assert.equal(columnHeaderTooltipDisabled({ columnDragActive: true, columnResizeActive: false }), true);
assert.equal(columnHeaderTooltipDisabled({ columnDragActive: false, columnResizeActive: true }), true);
assert.equal(columnHeaderTooltipDisabled({ columnDragActive: true, columnResizeActive: true }), true);
});
test("enables live column header reorder preview while dragging", () => {
assert.equal(columnHeaderPreviewEnabled({ columnDragActive: false }), false);
assert.equal(columnHeaderPreviewEnabled({ columnDragActive: true }), true);
});
test("ignores canvas pointer hit testing during column header interactions", () => {
assert.equal(columnHeaderCanvasPointerDisabled({ columnDragActive: false, columnResizeActive: false }), false);
assert.equal(columnHeaderCanvasPointerDisabled({ columnDragActive: true, columnResizeActive: false }), true);
assert.equal(columnHeaderCanvasPointerDisabled({ columnDragActive: false, columnResizeActive: true }), true);
});
test("suppresses the synthetic click that follows a column header drag", () => {
assert.equal(columnHeaderClickShouldBeSuppressed({ now: 1000, guardUntil: 0, suppressNextClick: false }), false);
assert.equal(columnHeaderClickShouldBeSuppressed({ now: 1000, guardUntil: 900, suppressNextClick: false }), false);
assert.equal(columnHeaderClickShouldBeSuppressed({ now: 1000, guardUntil: 1200, suppressNextClick: false }), true);
assert.equal(columnHeaderClickShouldBeSuppressed({ now: 1000, guardUntil: 0, suppressNextClick: true }), true);
});
test("calculates live reorder preview offsets for dragged and displaced columns", () => {
const base = {
columnDragActive: true,
sourceVisibleIndex: 1,
targetVisibleIndex: 3,
startX: 100,
currentX: 175,
sourceWidth: 240,
};
assert.equal(columnHeaderPreviewOffsetForColumn({ ...base, visibleColIdx: 1 }), 75);
assert.equal(columnHeaderPreviewOffsetForColumn({ ...base, visibleColIdx: 2 }), -240);
assert.equal(columnHeaderPreviewOffsetForColumn({ ...base, visibleColIdx: 3 }), -240);
assert.equal(columnHeaderPreviewOffsetForColumn({ ...base, visibleColIdx: 4 }), 0);
});