Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 51 additions & 9 deletions packages/web-ui/src/components/ui/DataGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ import {
CaseSensitive,
Table,
ChartColumn,
Pin,
PinOff,
} from 'lucide-react';
import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities';
import {getJsonViewerSessionHost} from '@/platform/secondaryWindowSessions';
Expand Down Expand Up @@ -88,6 +90,8 @@ import {
type LockedColumnWidths,
createDataGridResultCommands,
type RangeExtendKey,
getFrozenFirstColumnLayout,
FROZEN_HEADER_CELL_CLASS,
} from '@/utils/dataGrid';
import {isTypingTarget} from '@/utils/keyboardEvents';
import {getSortButtonAction} from '@/utils/tableToolbar';
Expand Down Expand Up @@ -426,6 +430,9 @@ export const DataGrid = React.memo(function DataGrid({
colName: string;
colIndex: number;
} | null>(null);
// Keeps the first data column next to the gutter on wide results (#1152).
// Grid-local and not persisted.
const [isFirstColumnFrozen, setIsFirstColumnFrozen] = useState(false);
const [columnStatsTarget, setColumnStatsTarget] = useState<{
x: number;
y: number;
Expand Down Expand Up @@ -850,9 +857,13 @@ export const DataGrid = React.memo(function DataGrid({

useEffect(() => {
if (editingCell && editInputRef.current) {
editInputRef.current.focus();
// A frozen cell's editor is already in view, and a scrolling focus
// would honor the scroll padding and jump back to the start (#1152).
editInputRef.current.focus({
preventScroll: isFirstColumnFrozen && editingCell.colIndex === 0,
});
}
}, [editingCell]);
}, [editingCell, isFirstColumnFrozen]);

const buildRowDataWithPending = useCallback(
(rowArray: unknown[], isInsertion: boolean): Record<string, unknown> => {
Expand Down Expand Up @@ -1584,6 +1595,8 @@ export const DataGrid = React.memo(function DataGrid({
columnLayoutKey,
tableColumns.length + 1,
);
const frozenLayout = isFirstColumnFrozen ? getFrozenFirstColumnLayout(columnWidths) : null;
const frozenFirstColumnLeft = frozenLayout?.left ?? null;
useLayoutEffect(() => {
if (columnWidths) return;
// Wait until the grid is visible and its rows are rendered: a hidden
Expand Down Expand Up @@ -2803,14 +2816,19 @@ export const DataGrid = React.memo(function DataGrid({
// outside the window is mounted on the next frame, so look the cell up
// then rather than synchronously (a multi-row PageDown would miss it).
const frame = requestAnimationFrame(() => {
parent
.querySelector<HTMLTableCellElement>(
`tr[data-row-index="${focusedCell.rowIndex}"] td[data-col-index="${focusedCell.colIndex}"]`,
)
?.scrollIntoView({block: 'nearest', inline: 'nearest'});
const cell = parent.querySelector<HTMLTableCellElement>(
`tr[data-row-index="${focusedCell.rowIndex}"] td[data-col-index="${focusedCell.colIndex}"]`,
);
if (!cell) return;
// A frozen cell is always in view horizontally (#1152), but the scroll
// padding would make the browser scroll it back to the start.
const keepScrollLeft =
isFirstColumnFrozen && focusedCell.colIndex === 0 ? parent.scrollLeft : null;
cell.scrollIntoView({block: 'nearest', inline: 'nearest'});
if (keepScrollLeft !== null) parent.scrollLeft = keepScrollLeft;
});
return () => cancelAnimationFrame(frame);
}, [focusedCell, rowVirtualizer]);
}, [focusedCell, rowVirtualizer, isFirstColumnFrozen]);

// Handle keyboard shortcuts
useEffect(() => {
Expand Down Expand Up @@ -2973,6 +2991,7 @@ export const DataGrid = React.memo(function DataGrid({
openJsonViewerWindow,
editInputRef,
zebraStripes,
frozenFirstColumnLeft,
}),
[
columns,
Expand Down Expand Up @@ -3018,6 +3037,7 @@ export const DataGrid = React.memo(function DataGrid({
openJsonViewerWindow,
editInputRef,
zebraStripes,
frozenFirstColumnLeft,
],
);

Expand Down Expand Up @@ -3068,6 +3088,9 @@ export const DataGrid = React.memo(function DataGrid({
onKeyDown={handleGridKeyDown}
onScroll={handleScroll}
className="h-full overflow-auto border border-default rounded bg-elevated relative focus:outline-none focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus"
style={
frozenLayout ? {scrollPaddingLeft: frozenLayout.scrollPaddingLeft} : undefined
}
>
<table
ref={tableRef}
Expand Down Expand Up @@ -3103,7 +3126,16 @@ export const DataGrid = React.memo(function DataGrid({
<th
key={header.id}
data-col-index={headerColIndex}
className={`relative px-4 py-2 text-xs font-semibold tracking-wider border-b border-r border-default last:border-r-0 whitespace-nowrap ${
style={
frozenFirstColumnLeft !== null && headerColIndex === 0
? {left: frozenFirstColumnLeft}
: undefined
}
className={`${
frozenFirstColumnLeft !== null && headerColIndex === 0
? FROZEN_HEADER_CELL_CLASS
: 'relative'
} px-4 py-2 text-xs font-semibold tracking-wider border-b border-r border-default last:border-r-0 whitespace-nowrap ${
selectedColIndices.has(headerColIndex)
? 'text-primary bg-accent-primary/20'
: 'text-secondary'
Expand Down Expand Up @@ -3767,6 +3799,16 @@ export const DataGrid = React.memo(function DataGrid({
} as ContextMenuItem,
]
: []),
{
label: isFirstColumnFrozen
? t('dataGrid.unfreezeFirstColumn')
: t('dataGrid.freezeFirstColumn'),
icon: isFirstColumnFrozen ? PinOff : Pin,
action: () => {
setIsFirstColumnFrozen((frozen) => !frozen);
setHeaderContextMenu(null);
},
},
{separator: true} as ContextMenuItem,
{
label: t('dataGrid.copyColumnName'),
Expand Down
29 changes: 28 additions & 1 deletion packages/web-ui/src/components/ui/DataGridRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
buildPkMap,
serializePkKey,
isZebraStripedRow,
getFrozenCellBackdropClass,
DATA_GRID_ROW_HEIGHT,
type ColumnDisplayInfo,
type MergedRow,
Expand Down Expand Up @@ -66,6 +67,11 @@ export interface RowCtx {
readonly: boolean | undefined;
/** Optional alternating row background (Settings > Appearance > Data Grid). */
zebraStripes: boolean;
/**
* Sticky `left` offset of the first data column while it is frozen (#1152),
* or null when it scrolls with the rest.
*/
frozenFirstColumnLeft: number | null;
updateSelection: (s: Set<number>) => void;
/** Sensitive-column masking (#485): columns rendered masked until revealed. */
maskedColIndices: Set<number>;
Expand Down Expand Up @@ -185,6 +191,7 @@ export const MemoRow = React.memo(function MemoRow(rowCtx: MemoRowProps) {
parentViewportWidth,
readonly: readonlyProp,
zebraStripes,
frozenFirstColumnLeft,
maskedColIndices,
revealedColIndices,
revealedCells,
Expand Down Expand Up @@ -352,6 +359,25 @@ export const MemoRow = React.memo(function MemoRow(rowCtx: MemoRowProps) {
const isFocused =
focusedCell?.rowIndex === rowIndex && focusedCell?.colIndex === colIndex;

// Frozen first column (#1152): sticky after the gutter, on an opaque
// backdrop. Sticky already anchors the inline editor, so the cell
// must not switch to `relative` while editing, and its focus mark is
// an outline because an inset ring would sit under the backdrop.
const isFrozen = frozenFirstColumnLeft !== null && colIndex === 0;
const frozenClass = isFrozen
? `sticky z-[5] ${getFrozenCellBackdropClass({
isSelected,
isInsertion,
isPendingDelete,
isZebra: isZebraStripedRow(rowIndex, zebraStripes),
})}`
: '';
const focusClass = !isFocused
? ''
: isFrozen
? 'outline outline-2 -outline-offset-2 outline-accent-primary'
: 'ring-2 ring-inset ring-accent-primary';

// Sensitive-column masking (#485): the real value stays in `data`
// (copy/export unaffected); only the render is replaced.
const isCellRevealed = revealedCells.has(`${rowIndex}:${colIndex}`);
Expand Down Expand Up @@ -424,7 +450,8 @@ export const MemoRow = React.memo(function MemoRow(rowCtx: MemoRowProps) {
onContextMenu={(e) =>
handleContextMenu(e, rowOriginal, rowIndex, colIndex, colName)
}
className={`px-4 py-1.5 text-sm border-b border-r border-default last:border-r-0 font-result ${isEditing ? 'relative' : 'whitespace-nowrap truncate max-w-[300px]'} ${fkForPreview ? 'cursor-pointer' : 'cursor-text'} ${stateClass} ${selectedColIndices.has(colIndex) || (rangeColBounds !== null && colIndex >= rangeColBounds.minCol && colIndex <= rangeColBounds.maxCol) ? 'bg-accent-primary/15' : ''} ${isFocused ? 'ring-2 ring-inset ring-accent-primary' : ''}`}
style={isFrozen ? {left: frozenFirstColumnLeft} : undefined}
className={`px-4 py-1.5 text-sm border-b border-r border-default last:border-r-0 font-result ${isEditing ? (isFrozen ? '' : 'relative') : 'whitespace-nowrap truncate max-w-[300px]'} ${frozenClass} ${fkForPreview ? 'cursor-pointer' : 'cursor-text'} ${stateClass} ${selectedColIndices.has(colIndex) || (rangeColBounds !== null && colIndex >= rangeColBounds.minCol && colIndex <= rangeColBounds.maxCol) ? 'bg-accent-primary/15' : ''} ${focusClass}`}
title={
// The hover tooltip would leak the real value of a masked cell.
!isEditing && !isMasked
Expand Down
2 changes: 2 additions & 0 deletions packages/web-ui/src/i18n/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -1404,6 +1404,8 @@
"copyAsHtmlTable": "Als HTML-Tabelle kopieren",
"selectColumn": "Spalte auswählen",
"deselectColumn": "Spalte abwählen",
"freezeFirstColumn": "Erste Spalte fixieren",
"unfreezeFirstColumn": "Erste Spalte lösen",
"copySelectedColumns": "Ausgewählte Spalten kopieren ({{count}})",
"copyRangeN": "Bereich kopieren ({{rows}}×{{cols}})",
"copyAllRows": "Alle kopieren ({{count}})",
Expand Down
2 changes: 2 additions & 0 deletions packages/web-ui/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1473,6 +1473,8 @@
"copyAsHtmlTable": "Copy as HTML table",
"selectColumn": "Select Column",
"deselectColumn": "Deselect Column",
"freezeFirstColumn": "Freeze first column",
"unfreezeFirstColumn": "Unfreeze first column",
"copySelectedColumns": "Copy Selected Columns ({{count}})",
"copyRangeN": "Copy Range ({{rows}}×{{cols}})",
"copyAllRows": "Copy All ({{count}})",
Expand Down
2 changes: 2 additions & 0 deletions packages/web-ui/src/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -1432,6 +1432,8 @@
"copyAsHtmlTable": "Copiar como tabla HTML",
"selectColumn": "Seleccionar Columna",
"deselectColumn": "Deseleccionar Columna",
"freezeFirstColumn": "Fijar la primera columna",
"unfreezeFirstColumn": "Liberar la primera columna",
"copySelectedColumns": "Copiar Columnas Seleccionadas ({{count}})",
"copyRangeN": "Copiar Rango ({{rows}}×{{cols}})",
"copyAllRows": "Copiar Todo ({{count}})",
Expand Down
2 changes: 2 additions & 0 deletions packages/web-ui/src/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -1443,6 +1443,8 @@
"copyAsHtmlTable": "Copier en tableau HTML",
"selectColumn": "Sélectionner la colonne",
"deselectColumn": "Désélectionner la colonne",
"freezeFirstColumn": "Figer la première colonne",
"unfreezeFirstColumn": "Libérer la première colonne",
"copySelectedColumns": "Copier les colonnes sélectionnées ({{count}})",
"copyRangeN": "Copier la plage ({{rows}}×{{cols}})",
"copyAllRows": "Tout Copier ({{count}})",
Expand Down
2 changes: 2 additions & 0 deletions packages/web-ui/src/i18n/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -1467,6 +1467,8 @@
"copyAsHtmlTable": "Copia come tabella HTML",
"selectColumn": "Seleziona Colonna",
"deselectColumn": "Deseleziona Colonna",
"freezeFirstColumn": "Blocca la prima colonna",
"unfreezeFirstColumn": "Sblocca la prima colonna",
"copySelectedColumns": "Copia Colonne Selezionate ({{count}})",
"copyRangeN": "Copia Intervallo ({{rows}}×{{cols}})",
"copyAllRows": "Copia Tutto ({{count}})",
Expand Down
2 changes: 2 additions & 0 deletions packages/web-ui/src/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -1416,6 +1416,8 @@
"copyAsHtmlTable": "HTMLテーブルとしてコピー",
"selectColumn": "列を選択",
"deselectColumn": "列の選択を解除",
"freezeFirstColumn": "最初の列を固定",
"unfreezeFirstColumn": "最初の列の固定を解除",
"copySelectedColumns": "選択した列をコピー({{count}})",
"copyRangeN": "範囲をコピー({{rows}}×{{cols}})",
"copyAllRows": "すべてコピー({{count}})",
Expand Down
2 changes: 2 additions & 0 deletions packages/web-ui/src/i18n/locales/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -1379,6 +1379,8 @@
"copyAsHtmlTable": "HTML 표로 복사",
"selectColumn": "열 선택",
"deselectColumn": "열 선택 해제",
"freezeFirstColumn": "첫 번째 열 고정",
"unfreezeFirstColumn": "첫 번째 열 고정 해제",
"copySelectedColumns": "선택한 열 복사 ({{count}})",
"copyRangeN": "범위 복사 ({{rows}}×{{cols}})",
"copyAllRows": "모두 복사 ({{count}})",
Expand Down
2 changes: 2 additions & 0 deletions packages/web-ui/src/i18n/locales/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -1422,6 +1422,8 @@
"copyAsHtmlTable": "Copiar como tabela HTML",
"selectColumn": "Selecionar Coluna",
"deselectColumn": "Desmarcar Coluna",
"freezeFirstColumn": "Congelar a primeira coluna",
"unfreezeFirstColumn": "Descongelar a primeira coluna",
"copySelectedColumns": "Copiar Colunas Selecionadas ({{count}})",
"copyRangeN": "Copiar Intervalo ({{rows}}×{{cols}})",
"copyAllRows": "Copiar Tudo ({{count}})",
Expand Down
2 changes: 2 additions & 0 deletions packages/web-ui/src/i18n/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -1405,6 +1405,8 @@
"copyAsHtmlTable": "Скопировать как HTML-таблицу",
"selectColumn": "Выбрать столбец",
"deselectColumn": "Снять выбор столбца",
"freezeFirstColumn": "Закрепить первый столбец",
"unfreezeFirstColumn": "Открепить первый столбец",
"copySelectedColumns": "Копировать выбранные столбцы ({{count}})",
"copyRangeN": "Копировать диапазон ({{rows}}×{{cols}})",
"copyAllRows": "Скопировать все ({{count}})",
Expand Down
2 changes: 2 additions & 0 deletions packages/web-ui/src/i18n/locales/tl.json
Original file line number Diff line number Diff line change
Expand Up @@ -1435,6 +1435,8 @@
"copyAsHtmlTable": "Kopyahin bilang HTML table",
"selectColumn": "Piliin ang Column",
"deselectColumn": "Alisin ang Pagpili ng Column",
"freezeFirstColumn": "I-freeze ang unang column",
"unfreezeFirstColumn": "I-unfreeze ang unang column",
"copySelectedColumns": "Kopyahin ang Napiling Columns ({{count}})",
"copyRangeN": "Kopyahin ang Range ({{rows}}×{{cols}})",
"copyAllRows": "Kopyahin Lahat ({{count}})",
Expand Down
2 changes: 2 additions & 0 deletions packages/web-ui/src/i18n/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -1379,6 +1379,8 @@
"copyAsHtmlTable": "复制为 HTML 表格",
"selectColumn": "选择列",
"deselectColumn": "取消选择列",
"freezeFirstColumn": "冻结首列",
"unfreezeFirstColumn": "取消冻结首列",
"copySelectedColumns": "复制选中列({{count}})",
"copyRangeN": "复制范围({{rows}}×{{cols}})",
"copyAllRows": "复制全部({{count}})",
Expand Down
83 changes: 83 additions & 0 deletions packages/web-ui/src/utils/dataGrid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -863,3 +863,86 @@ export function getResizedTableWidth(
if (!locked?.resized || !widths) return undefined;
return widths.reduce((sum, w) => sum + w, 0);
}

/** Row-number gutter width before the grid has measured its columns. */
export const DATA_GRID_GUTTER_FALLBACK_WIDTH = 50;

/**
* Width of the collapsed border between the gutter and the first column. The
* table paints it where the column started, inside the column's box, so a
* sticky cell at the full gutter width leaves a 1px strip of scrolled content
* showing at the gutter edge.
*/
const DATA_GRID_GUTTER_BORDER_WIDTH = 1;

export interface FrozenFirstColumnLayout {
/**
* Sticky `left` offset of the frozen column: right after the gutter, pulled
* under its shared border so the border strip is covered too.
*/
left: number;
/**
* Scroll padding that keeps `scrollIntoView` from parking the active cell
* under the gutter and the frozen column.
*/
scrollPaddingLeft: number;
}

/**
* Offsets for the frozen first data column (#1152). `columnWidths` are the
* locked widths (gutter first); before they are measured the gutter falls back
* to its CSS width and the frozen column adds no scroll padding.
*/
export function getFrozenFirstColumnLayout(
columnWidths: readonly number[] | null,
): FrozenFirstColumnLayout {
const gutter = columnWidths?.[0] ?? DATA_GRID_GUTTER_FALLBACK_WIDTH;
return {
left: gutter - DATA_GRID_GUTTER_BORDER_WIDTH,
scrollPaddingLeft: gutter + (columnWidths?.[1] ?? 0),
};
}

export interface FrozenCellRowState {
isSelected: boolean;
isInsertion: boolean;
isPendingDelete: boolean;
isZebra: boolean;
}

// Both layers sit under the cell content. `::before` is the opaque row
// background, `::after` repaints the cell's own tint (selection, edits) on top.
// Collapsed table borders stay where the column started, so `::before` also
// draws the frozen column's right border.
const FROZEN_CELL_LAYERS =
'before:absolute before:inset-0 before:-z-10 before:pointer-events-none before:transition-colors before:border-r before:border-default after:absolute after:inset-0 after:-z-10 after:pointer-events-none after:bg-inherit';

/**
* Frozen header cell: the header background under its own tint, stacked below
* the gutter header (z-20).
*/
export const FROZEN_HEADER_CELL_CLASS = `sticky z-[15] ${FROZEN_CELL_LAYERS} before:bg-base`;

/**
* Backdrop for a frozen (sticky) body cell. The row tints are translucent, so
* a sticky cell would show the cells scrolling under it; this paints the same
* tint pre-mixed over the grid background instead. Mirrors the row classes in
* DataGridRow, in the same precedence.
*/
export function getFrozenCellBackdropClass(row: FrozenCellRowState): string {
let backdrop: string;
if (row.isSelected) {
backdrop = 'before:bg-[color-mix(in_srgb,var(--accent-primary)_10%,var(--bg-elevated))]';
} else if (row.isInsertion) {
backdrop = 'before:bg-[color-mix(in_srgb,var(--semantic-new)_8%,var(--bg-elevated))]';
} else if (row.isPendingDelete) {
backdrop = 'before:bg-[color-mix(in_srgb,var(--semantic-deleted)_10%,var(--bg-elevated))]';
} else if (row.isZebra) {
backdrop =
'before:bg-[color-mix(in_srgb,var(--surface-secondary)_40%,var(--bg-elevated))] group-hover:before:bg-[color-mix(in_srgb,var(--surface-secondary)_90%,var(--bg-elevated))]';
} else {
backdrop =
'before:bg-elevated group-hover:before:bg-[color-mix(in_srgb,var(--surface-secondary)_50%,var(--bg-elevated))]';
}
return `${FROZEN_CELL_LAYERS} ${backdrop}`;
}
Loading