/** * Result / table data grid: virtualised rows, resizable columns, rectangular * cell selection (click, ⇧-click, arrows, ⌘A), copy as TSV / CSV / One-Row, * `` rendering, sortable headers and type-aware in-place editing * (booleans toggle, enums pick from their values, Set NULL / Set DEFAULT). */ import { writeClipboardText } from "@/platform/clipboard"; import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ClipboardEvent, type FocusEvent, type KeyboardEvent, type MouseEvent, } from "react"; import { useVirtualizer } from "@tanstack/react-virtual"; import clsx from "clsx"; import { Checkbox, Dialog, Icon, lockDragCursor, Popup, SelectListbox, showContextMenu, T, type MenuItem } from "@/ui"; import { parseDelimited, toCsv, toOneRow, toTsv, type Cell } from "./model"; import { initialJsonText, isJsonColumn, isJsonValue } from "./jsonValue"; import { JsonValueWindow } from "./JsonValueEditor"; import styles from "./Database.module.css"; import { tx } from "@/platform/i18n"; import { hasPrimaryModifier } from "@/platform/keymap"; import { CELL_PREVIEW_LIMIT, cellPreview, hasLineBreak } from "./cellPreview"; import { booleanLiterals, defaultLiteralOf, enumValuesOfType, isBooleanType, NULL_INPUT, type BooleanLiterals, } from "./cellEditors"; import { registerCellGrid, type CellActions } from "./cellActions"; import type { DbDriver } from "@/platform/ipc"; export interface GridColumn { name: string; type: string; primaryKey?: boolean; foreignKey?: boolean; /** Whether the column accepts SQL NULL (`undefined`: unknown — the editor assumes it does). */ nullable?: boolean; /** The column's introspected default expression (Set DEFAULT); `null` when it has none. */ default?: string | null; /** The column's allowed values (a caller that knows them; else parsed from the type string). */ enumValues?: readonly string[]; } const NUMERIC_TYPE = /int|num|dec|real|float|double|money|serial|^bit$|^fixed\b/i; const NUMBER = /^-?\d+(\.\d+)?(e[+-]?\d+)?$/i; /** Numbers are right-aligned (IDEA): by type, else when every sampled value is one. */ export function isNumericColumn(type: string, sample: readonly Cell[]): boolean { if (type && !/^(null|unknown)?$/i.test(type)) return NUMERIC_TYPE.test(type) && !/point|interval/i.test(type); const values = sample.filter((v): v is string => v !== null); return values.length > 0 && values.every((v) => NUMBER.test(v)); } /** The grid's own copy formats (the extractor drop-down chooses one for plain ⌘C). */ export type CopyFormat = "tsv" | "csv" | "onerow"; export interface GridProps { columns: readonly GridColumn[]; rowCount: number; /** Displayed value (pending edits applied). */ value: (row: number, col: number) => Cell; /** The whole length (UTF-16 units) of a cell shown cut short (a page carries only the start of a large value); `null` when it is whole. */ truncated?: (row: number, col: number) => number | null; /** Reads the whole values of cut cells (the resolved values follow `cells`); `null` when they could not be read. */ loadFull?: (cells: ReadonlyArray<{ row: number; col: number }>) => Promise; /** The format plain ⌘C copies in (the toolbar's extractor; TSV by default). */ copyFormat?: CopyFormat; rowState?: (row: number) => "deleted" | "inserted" | null; isModified?: (row: number, col: number) => boolean; editable?: boolean; onEdit?: (row: number, col: number, value: Cell) => void; /** The data source's driver: which literals boolean editors write (`t`/`f`, `1`/`0`…). */ driver?: DbDriver; /** Omit an inserted cell from the INSERT, so its database default applies. */ onResetCell?: (row: number, col: number) => void; sort?: ReadonlyArray<{ column: string; descending: boolean }>; onSort?: (column: string, add: boolean) => void; /** Extra context menu items for the selected rows. */ rowMenu?: (rows: number[]) => MenuItem[]; /** More Copy as entries for the selected rows (SQL statements of the whole rows). */ copyAs?: (rows: number[]) => MenuItem[]; /** Row number shown for row 0 (paging). */ firstRowNumber?: number; /** Row number shown for a row (local sort / filter reorder them); `firstRowNumber + row` otherwise. */ rowNumber?: (row: number) => number; /** The selected range changed (the Record / Value / Aggregates panel follows it). */ onSelectionChange?: (range: GridRange | null) => void; /** The header's filter button (IDEA's local filter); `filtered` marks the columns with one. */ onFilter?: (col: number, anchor: HTMLElement) => void; filtered?: (col: number) => boolean; /** Cells matching the search bar's query. */ isMatch?: (row: number, col: number) => boolean; /** The search bar's current match: selected and scrolled into view when it changes. */ currentMatch?: { row: number; col: number } | null; /** ⌘F / Ctrl+F in the grid (opens the search bar). */ onFind?: () => void; /** Go to Column: a new object selects that column's cell in the current row, scrolls to it and focuses the grid. */ revealColumn?: { col: number } | null; /** Horizontal scroll offset to restore on mount, when a caller keeps view state across mounts. */ initialScrollLeft?: number; /** Reports horizontal scroll changes to a caller that keeps view state across mounts. */ onHorizontalScroll?: (left: number) => void; "aria-label"?: string; } /** A selected block of cells, inclusive; `lead` is the cell last moved to. */ export interface GridRange { top: number; bottom: number; left: number; right: number; lead: { row: number; col: number }; /** Further whole rows selected with ⌘/Ctrl-click, besides `top`..`bottom`. */ rows?: number[]; } interface Sel { r0: number; c0: number; r1: number; c1: number; /** Whole rows added with ⌘/Ctrl-click on their numbers, besides the block above. */ rows?: number[]; } const ROW_H = 24; /** Wide enough for the whole header (icon, name, filter, sort) and the longest sampled value. */ function initialWidth(c: GridColumn, sample: Cell[], decorations: number): number { const header = c.name.length * 8 + 32 + decorations; const longest = Math.max(...sample.map((v) => Math.min((v ?? "").length, 60)), 0) * 7.5 + 20; return Math.max(64, Math.min(360, Math.max(header, longest))); } /** SQLite renders whole REALs as `3108.0`; IDEA shows `3108`. */ const displayed = (v: string, numeric: boolean) => (numeric && /^-?\d+\.0$/.test(v) ? v.slice(0, -2) : v); /** A cell's text on one line: each line break shows as a muted `↵`. */ function cellText(value: string) { const parts = cellPreview(value).split(/\r\n|\r|\n/); if (parts.length === 1) return parts[0]; return parts.flatMap((part, i) => i === 0 ? [part] : [ // oxlint-disable-next-line react/no-array-index-key -- repeated blank lines produce identical markers; position is the identity ↵ , part, ], ); } /** * The selection after a click on row `r`'s number: the whole row, a range of whole rows with * Shift, or (⌘/Ctrl) that row added to or removed from the selected rows. */ export function rowNumberClick( sel: Sel | null, r: number, last: number, mods: { shift: boolean; add: boolean }, ): Sel | null { if (mods.shift && sel) return { ...sel, r1: r, c1: last }; if (!mods.add || !sel) return { r0: r, c0: 0, r1: r, c1: last }; const n = norm(sel); const block = Array.from({ length: n.bottom - n.top + 1 }, (_, i) => n.top + i); const rows = [...new Set([...(sel.rows ?? []), ...block])]; if (!rows.includes(r)) return { r0: r, c0: 0, r1: r, c1: last, rows }; // ⌘-click on a selected row deselects it; the last remaining row leads. const rest = rows.filter((x) => x !== r); const lead = rest.at(-1); if (lead === undefined) return null; return { r0: lead, c0: 0, r1: lead, c1: last, rows: rest.slice(0, -1) }; } function norm(s: Sel) { return { top: Math.min(s.r0, s.r1), bottom: Math.max(s.r0, s.r1), left: Math.min(s.c0, s.c1), right: Math.max(s.c0, s.c1), }; } export function Grid(props: GridProps) { const { columns, rowCount, value, editable, onEdit, sort, onSort, rowMenu, firstRowNumber = 1, copyFormat = "tsv", } = props; const scrollRef = useRef(null); const numberWidth = Math.max(40, String(firstRowNumber + rowCount - 1).length * 8 + 8); const [sel, setSel] = useState(null); /** A drag that started on a cell extends the block; one on a row number extends whole rows. */ const dragging = useRef<"cells" | "rows" | false>(false); useEffect(() => { const stop = () => { dragging.current = false; }; window.addEventListener("mouseup", stop); return () => window.removeEventListener("mouseup", stop); }, []); const [editing, setEditing] = useState<{ row: number; col: number; text: string; json: boolean; dialog: boolean; } | null>(null); /** The inline editor is being replaced or closed: its blur must not commit again. */ const skipBlurCommit = useRef(false); useEffect(() => { if (!editing?.dialog) skipBlurCommit.current = false; }, [editing?.dialog]); const columnKey = columns.map((c) => c.name).join("\u0000"); const [widths, setWidths] = useState([]); const [numeric, setNumeric] = useState([]); /** Boolean columns edit as a checkbox; enum columns offer their allowed values. */ const bools = columns.map((c) => isBooleanType(c.type, props.driver)); const enums = columns.map((c) => c.enumValues ?? enumValuesOfType(c.type)); useEffect(() => { const sampleRows = Math.min(rowCount, 50); const samples = columns.map((_, ci) => Array.from({ length: sampleRows }, (_, r) => value(r, ci))); const decorations = (props.onFilter ? 20 : 0) + (onSort ? 20 : 0); setWidths(columns.map((c, ci) => initialWidth(c, samples[ci]!, decorations))); setNumeric(columns.map((c, ci) => isNumericColumn(c.type, samples[ci]!))); setSel(null); setEditing(null); // Re-measure only when the column set changes. // eslint-disable-next-line react-hooks/exhaustive-deps }, [columnKey]); const { onSelectionChange } = props; useEffect(() => { onSelectionChange?.( sel && rowCount ? { ...norm(sel), lead: { row: Math.min(sel.r1, rowCount - 1), col: sel.c1 }, rows: sel.rows } : null, ); }, [sel, rowCount, onSelectionChange]); const virtualizer = useVirtualizer({ count: rowCount, getScrollElement: () => scrollRef.current, estimateSize: () => ROW_H, overscan: 12, }); /** Scrolls sideways so column `c` is visible (the first one with the row numbers). */ const scrollColumnIntoView = (c: number) => { const el = scrollRef.current; if (!el || c < 0 || c >= widths.length) return; const left = c ? numberWidth + widths.slice(0, c).reduce((a, b) => a + b, 0) : 0; const right = numberWidth + widths.slice(0, c + 1).reduce((a, b) => a + b, 0); if (left < el.scrollLeft) el.scrollLeft = left; else if (right > el.scrollLeft + el.clientWidth) el.scrollLeft = Math.min(left, right - el.clientWidth); }; const { currentMatch } = props; useEffect(() => { if (!currentMatch) return; const { row, col } = currentMatch; setSel({ r0: row, c0: col, r1: row, c1: col }); virtualizer.scrollToIndex(row, { align: "auto" }); scrollColumnIntoView(col); // Follows the match only, not the virtualizer's identity. // eslint-disable-next-line react-hooks/exhaustive-deps }, [currentMatch?.row, currentMatch?.col]); const { revealColumn } = props; useEffect(() => { if (!revealColumn || !rowCount) return; const { col } = revealColumn; const row = sel ? Math.min(sel.r1, rowCount - 1) : 0; setSel({ r0: row, c0: col, r1: row, c1: col }); virtualizer.scrollToIndex(row, { align: "auto" }); scrollColumnIntoView(col); scrollRef.current?.focus({ preventScroll: true }); // Runs once per request. // eslint-disable-next-line react-hooks/exhaustive-deps }, [revealColumn]); const totalWidth = useMemo(() => numberWidth + widths.reduce((a, b) => a + b, 0), [numberWidth, widths]); const template = `${numberWidth}px ${widths.map((w) => `${w}px`).join(" ")}`; // Retried as columns are measured, until the content is wide enough to reach the offset. const pendingScrollLeft = useRef(props.initialScrollLeft); useLayoutEffect(() => { const el = scrollRef.current; const left = pendingScrollLeft.current; if (!el || !left) return; el.scrollLeft = left; if (el.scrollLeft >= left - 1) pendingScrollLeft.current = undefined; }, [totalWidth]); const selected = (r: number, c: number) => { if (!sel) return false; const n = norm(sel); return (r >= n.top && r <= n.bottom && c >= n.left && c <= n.right) || !!sel.rows?.includes(r); }; const selectedRows = (): number[] => { if (!sel) return []; const n = norm(sel); const block = Array.from({ length: n.bottom - n.top + 1 }, (_, i) => n.top + i); if (!sel.rows?.length) return block; return [...new Set([...sel.rows, ...block])].sort((a, b) => a - b); }; const rowSelected = (() => { const rows = new Set(selectedRows()); return (r: number) => rows.has(r); })(); const copy = async (format: CopyFormat, header: boolean, wholeRows = false) => { if (!sel) return; const n = norm(sel); const cols = wholeRows || sel.rows?.length ? columns.map((_, i) => i) : Array.from({ length: n.right - n.left + 1 }, (_, i) => n.left + i); const picked = selectedRows(); const rows = picked.map((r) => cols.map((c) => value(r, c))); // A cut cell copies as its whole value. const cut = picked.flatMap((row, i) => cols.flatMap((col, j) => (props.truncated?.(row, col) != null ? [{ row, col, i, j }] : [])), ); if (cut.length) { const full = await props.loadFull?.(cut); if (!full) return; cut.forEach(({ i, j }, k) => (rows[i]![j] = full[k]!)); } const head = header ? cols.map((c) => columns[c]!.name) : null; const text = format === "onerow" ? toOneRow(rows, (c) => !!numeric[cols[c]!]) : format === "tsv" ? toTsv(head, rows) : toCsv(head, rows); void writeClipboardText(text); }; const commit = () => { if (!editing) return; skipBlurCommit.current = true; const prev = value(editing.row, editing.col); // A textarea turns CRLF into LF; a value that used CRLF throughout keeps it. const text = prev && prev.includes("\r\n") && !/(^|[^\r])\n/.test(prev) ? editing.text.replace(/\r?\n/g, "\r\n") : editing.text; if (text !== (prev ?? "") || prev === null) { if (!(prev === null && text === "")) onEdit?.(editing.row, editing.col, text); } setEditing(null); scrollRef.current?.focus(); }; /** The JSON value window's Apply / Set NULL: the same pending-edit pipeline as the inline editor. */ const commitJsonWindow = (text: string | null) => { if (!editing) return; if (text !== value(editing.row, editing.col)) onEdit?.(editing.row, editing.col, text); setEditing(null); scrollRef.current?.focus(); }; /** `maximized` (⇧Enter): the multi-line editor, which multi-line and long values always use. */ const startEdit = (row: number, col: number, maximized = false) => { if (!editable || props.rowState?.(row) === "deleted") return; // A cut value is read whole first: editing its start would write that back. if (props.truncated?.(row, col) != null) { void props.loadFull?.([{ row, col }]).then((full) => full && openEditor(row, col, full[0]!, maximized)); return; } openEditor(row, col, value(row, col), maximized); }; const openEditor = (row: number, col: number, cell: Cell, maximized: boolean) => { const text = cell ?? ""; // JSON cells (type or content) edit in the JSON value editor when the dialog opens (#2333). const json = isJsonValue(columns[col]?.type ?? "", cell); setEditing({ row, col, text, json, dialog: maximized || text.length > CELL_PREVIEW_LIMIT || hasLineBreak(text) }); }; /** The select editor's pick: values are final, so it commits at once (Escape still cancels). */ const pickSelect = (v: string) => { if (!editing) return; onEdit?.(editing.row, editing.col, v === NULL_INPUT ? null : v); setEditing(null); scrollRef.current?.focus(); }; const toggleBoolean = (r: number, c: number, lit: BooleanLiterals) => { if (!onEdit || props.rowState?.(r) === "deleted") return; onEdit(r, c, value(r, c) === lit.t ? lit.f : lit.t); }; /** Set NULL over a range, unless a column is known to reject it. */ const nullOk = (n: { left: number; right: number }) => Array.from({ length: n.right - n.left + 1 }, (_, i) => columns[n.left + i]!).every((c) => c.nullable !== false); /** Set DEFAULT over a range: added rows drop the cell's value (the DB default applies); */ /** otherwise the column's default is used, when introspected as a plain literal. */ const defaultable = (n: { top: number; bottom: number; left: number; right: number }): boolean => { let usable = false; for (let r = n.top; r <= n.bottom; r++) { if (props.rowState?.(r) === "deleted") continue; usable = true; if (props.rowState?.(r) === "inserted") { if (!props.onResetCell) return false; continue; } for (let c = n.left; c <= n.right; c++) { const d = columns[c]!.default; if (d == null || defaultLiteralOf(d) === null) return false; } } return usable; }; const setNulls = (n: { top: number; bottom: number; left: number; right: number }) => { if (!onEdit || !nullOk(n)) return; for (let r = n.top; r <= n.bottom; r++) for (let c = n.left; c <= n.right; c++) if (props.rowState?.(r) !== "deleted") onEdit(r, c, null); }; const setDefaults = (n: { top: number; bottom: number; left: number; right: number }) => { if (!onEdit || !defaultable(n)) return; for (let r = n.top; r <= n.bottom; r++) { if (props.rowState?.(r) === "deleted") continue; for (let c = n.left; c <= n.right; c++) { if (props.rowState?.(r) === "inserted") { // An added row's untouched cells are omitted from the INSERT: the DB default applies. props.onResetCell?.(r, c); continue; } const d = columns[c]!.default; const literal = d != null ? defaultLiteralOf(d) : null; if (literal !== null) { const lit = booleanLiterals(props.driver); const text = bools[c] && /^(true|false|t|f|1|0)$/i.test(literal) ? /^(true|t|1)$/i.test(literal) ? lit.t : lit.f : literal; onEdit(r, c, text); } } } }; const jsonWindowChanged = editing?.dialog && editing.json && editing.text !== (value(editing.row, editing.col) ?? ""); const cellActions = useRef(null!); useLayoutEffect(() => { const canEdit = () => !!editable && !!onEdit && !!sel && !editing && selectedRows().some((r) => props.rowState?.(r) !== "deleted"); const actions: CellActions = { canToggle: () => canEdit() && !!bools[sel!.c1] && props.rowState?.(sel!.r1) !== "deleted", canSetNull: () => canEdit() && nullOk(norm(sel!)), canSetDefault: () => canEdit() && defaultable(norm(sel!)), canFilter: () => !!props.onFilter && !!sel && !editing, toggle: () => { if (actions.canToggle()) toggleBoolean(sel!.r1, sel!.c1, booleanLiterals(props.driver)); }, setNull: () => { if (actions.canSetNull()) setNulls(norm(sel!)); }, setDefault: () => { if (actions.canSetDefault()) setDefaults(norm(sel!)); }, filter: () => { if (!actions.canFilter()) return; scrollColumnIntoView(sel!.c1); const anchor = scrollRef.current?.querySelectorAll("[data-column-filter]")[sel!.c1]; if (anchor) props.onFilter!(sel!.c1, anchor); }, canEditCell: () => { if (!canEdit()) return false; const n = norm(sel!); return n.top === n.bottom && n.left === n.right && props.rowState?.(n.top) !== "deleted"; }, editCell: () => { if (actions.canEditCell()) startEdit(sel!.r1, sel!.c1); }, hasSelection: () => !!sel && !editing, copy: (kind) => { if (!actions.hasSelection()) return; if (kind === "header") copy("tsv", true); else if (kind === "rowsTsv") copy("tsv", true, true); else if (kind === "rowsCsv") copy("csv", true, true); else copy(kind, false); }, selectedRows, }; Object.assign((cellActions.current ??= {} as CellActions), actions); }); useEffect(() => registerCellGrid(scrollRef.current!, cellActions.current), []); const onKeyDown = (e: KeyboardEvent) => { if (editing) return; const mod = e.metaKey || e.ctrlKey; if (mod && e.key.toLowerCase() === "c") { e.preventDefault(); copy(copyFormat, false); return; } if (mod && e.key.toLowerCase() === "f" && props.onFind) { e.preventDefault(); props.onFind(); return; } if (mod && e.key.toLowerCase() === "a") { e.preventDefault(); if (rowCount && columns.length) setSel({ r0: 0, c0: 0, r1: rowCount - 1, c1: columns.length - 1 }); return; } if (!sel) return; if ((e.key === "Enter" || e.key === "F2") && editable) { e.preventDefault(); startEdit(sel.r1, sel.c1, e.key === "Enter" && e.shiftKey); return; } if (e.key === "Tab") { // IDEA's tables: Tab moves between cells, leaving the grid after the last one. const next = mod || e.altKey ? null : nextCell(sel.r1, sel.c1, e.shiftKey ? -1 : 1); if (!next) return; e.preventDefault(); moveTo(next[0], next[1], false); return; } const moves: Record = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1], }; const m = moves[e.key]; if (!m) return; e.preventDefault(); moveTo( Math.max(0, Math.min(rowCount - 1, sel.r1 + m[0])), Math.max(0, Math.min(columns.length - 1, sel.c1 + m[1])), e.shiftKey, ); }; /** The cell Tab (`step` 1) or Shift+Tab (-1) goes to, row by row; null past either end. */ const nextCell = (r: number, c: number, step: 1 | -1): [number, number] | null => { const i = Math.min(r, rowCount - 1) * columns.length + c + step; return i < 0 || i >= rowCount * columns.length ? null : [Math.floor(i / columns.length), i % columns.length]; }; const moveTo = (r: number, c: number, extend: boolean) => { setSel(extend && sel ? { ...sel, r1: r, c1: c } : { r0: r, c0: c, r1: r, c1: c }); virtualizer.scrollToIndex(r, { align: "auto" }); scrollColumnIntoView(c); }; /** Focus from a click lands on the clicked cell; from the keyboard, on the first cell. */ const pointerFocus = useRef(false); const onFocus = (e: FocusEvent) => { if (e.target !== e.currentTarget || pointerFocus.current || sel || editing) return; if (rowCount && columns.length) moveTo(0, 0, false); }; const onCellMouseDown = (e: MouseEvent, r: number, c: number) => { if (e.button !== 0) { if (!selected(r, c)) setSel({ r0: r, c0: c, r1: r, c1: c }); return; } if (editing) commit(); e.preventDefault(); scrollRef.current?.focus(); dragging.current = "cells"; setSel(e.shiftKey && sel ? { ...sel, r1: r, c1: c } : { r0: r, c0: c, r1: r, c1: c }); }; const onPaste = (e: ClipboardEvent) => { if (editing || !editable || !onEdit || !sel) return; const text = e.clipboardData.getData("text/plain"); if (!text) return; e.preventDefault(); const rows = parseDelimited(text, "\t"); const { top, left } = norm(sel); let bottom = top; let right = left; rows.forEach((cells, dr) => cells.forEach((cell, dc) => { const row = top + dr, col = left + dc; if (row >= rowCount || col >= columns.length || props.rowState?.(row) === "deleted") return; onEdit(row, col, cell); bottom = Math.max(bottom, row); right = Math.max(right, col); }), ); setSel({ r0: top, c0: left, r1: bottom, c1: right }); }; const onRowNumberMouseDown = (e: MouseEvent, r: number) => { if (e.button !== 0) { if (!sel || !selected(r, 0)) setSel({ r0: r, c0: 0, r1: r, c1: columns.length - 1 }); return; } if (editing) commit(); e.preventDefault(); scrollRef.current?.focus(); dragging.current = "rows"; setSel(rowNumberClick(sel, r, columns.length - 1, { shift: e.shiftKey, add: hasPrimaryModifier(e) })); }; const onContextMenu = (e: MouseEvent) => { e.preventDefault(); if (!sel) return; const items: MenuItem[] = [ { label: "Copy", shortcut: "⌘C", run: () => copy(copyFormat, false) }, { label: "Copy as", submenu: [ { kind: "action", action: "db.copyAsTsv", label: "TSV", arg: cellActions.current }, { kind: "action", action: "db.copyAsCsv", label: "CSV", arg: cellActions.current }, { kind: "action", action: "db.copyAsOneRow", label: "One-Row", arg: cellActions.current }, ...(() => { const more = props.copyAs?.(selectedRows()) ?? []; return more.length ? [{ kind: "separator" } as const, ...more] : []; })(), ], }, { kind: "action", action: "db.copyWithHeader", arg: cellActions.current }, { kind: "action", action: "db.copyRowsAsTsv", arg: cellActions.current }, { kind: "action", action: "db.copyRowsAsCsv", arg: cellActions.current }, ]; if (editable && onEdit) { items.push( { kind: "separator" }, { kind: "action", action: "db.editCell", arg: cellActions.current }, { kind: "action", action: "db.setCellNull", arg: cellActions.current }, { kind: "action", action: "db.setCellDefault", arg: cellActions.current }, ); } if (props.onFilter) { items.push({ kind: "separator" }, { kind: "action", action: "db.localFilter", arg: cellActions.current }); } const extra = rowMenu?.(selectedRows()) ?? []; if (extra.length) items.push({ kind: "separator" }, ...extra); showContextMenu(e, items); }; const startResize = (e: MouseEvent, col: number) => { e.preventDefault(); e.stopPropagation(); const releaseCursor = lockDragCursor("col-resize"); const startX = e.clientX; const start = widths[col] ?? 100; const move = (ev: globalThis.MouseEvent) => { if (!(ev.buttons & 1)) return up(); setWidths((w) => w.map((x, i) => (i === col ? Math.max(40, start + ev.clientX - startX) : x))); }; const up = () => { window.removeEventListener("mousemove", move); window.removeEventListener("mouseup", up); releaseCursor(); }; window.addEventListener("mousemove", move); window.addEventListener("mouseup", up); }; return (
{ pointerFocus.current = true; setTimeout(() => (pointerFocus.current = false)); }} onScroll={(e) => props.onHorizontalScroll?.(e.currentTarget.scrollLeft)} onPaste={onPaste} onContextMenu={onContextMenu} > {editing?.dialog && editing.json && ( { setEditing(null); scrollRef.current?.focus(); }} onApply={(text) => commitJsonWindow(text)} onSetNull={() => commitJsonWindow(null)} /> )} {editing?.dialog && !editing.json && ( setEditing(null)} buttons={[ { label: "Cancel", role: "cancel", onClick: () => setEditing(null) }, { label: "Apply", role: "default", onClick: commit }, ]} >