Files
openidea/src/features/database/DataView.tsx
T
Vadim LazukandInf1mum 329f0b1330 feat(database): boolean and enum cell editors with Set NULL / Set DEFAULT (#2415)
Refs #2331

Every grid cell edited in the same plain text box whatever its SQL type. Boolean columns (boolean, tinyint(1), bit) now show a checkbox on editable rows that writes the literal the driver renders, Space toggles it, and the editor offers true / false / NULL (NULL only for nullable columns). Enum columns with a known value list choose from it, keeping an unknown current value selectable. Set NULL and Set DEFAULT are cell actions (db.setCellNull / db.setCellDefault, ⌘⌫ / ⇧⌘⌫ on macOS) over the selected range; Set DEFAULT drops the pending value on added rows and writes literal defaults on existing ones, and is disabled for expression defaults. Works in the table editor and console results alongside the JSON value editor. Remaining in #2331: date/time editors, numeric/date validation, PostgreSQL enum introspection, FK lookup, DEFAULT keyword for expression defaults on existing rows.

Co-authored-by: Inf1mum <8135225+Inf1mum@users.noreply.github.com>
2026-11-10 06:11:49 +08:00

699 lines
25 KiB
TypeScript

/**
* A data grid with IDEA's result-view extras, shared by console results and
* the table editor: the header's local filter (values of the loaded rows),
* client-side sorting when the caller does not sort on the server, and the
* Record / Value / Aggregates side panel following the selection.
*/
import { writeClipboardText } from "@/platform/clipboard";
import { useMemo, useRef, useState, type KeyboardEvent, type RefObject } from "react";
import clsx from "clsx";
import { Button, Checkbox, Icon, IconButton, Input, Popup, SearchField, Select, Tabs, T, type MenuItem } from "@/ui";
import { EXPORT_FORMATS, exportData, type ExportData, type ExportFormat } from "./export";
import { Grid, type CopyFormat, type GridColumn, type GridProps, type GridRange } from "./Grid";
import type { Cell } from "./model";
import {
aggregates,
cellMatcher,
distinctValues,
findCells,
formatNumber,
rowMatches,
toggleFilterValue,
visibleRows,
type LocalFilter,
type LocalSort,
type SearchOptions,
} from "./resultView";
import { openDialog } from "./store";
import { hasLineBreak } from "./cellPreview";
import {
initialJsonText,
isJsonColumn,
isJsonValue,
jsonErrorOf,
JSON_INLINE_LIMIT,
type JsonError,
} from "./jsonValue";
import { JsonValueEditor, JsonValueWindow, type JsonEditorApi } from "./JsonValueEditor";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
export type DataPanel = "record" | "value" | "aggregates";
/** The Export button's menu: the Export Data dialog (with the toolbar's extractor), then IDEA's quick Copy as… extractors. */
export function exportMenu(data: ExportData, source: string, format?: ExportFormat): MenuItem[] {
return [
{ label: "Export Data…", icon: "export", run: () => openDialog({ kind: "export", data, source, format }) },
{ kind: "separator" },
...EXPORT_FORMATS.map((f): MenuItem => ({
label: tx`Copy as ${f.label}`,
icon: "copy",
run: () => void writeClipboardText(exportData(f.id, data)),
})),
];
}
/** IDEA's extractor drop-down at the right of a data toolbar ("CSV ▾"). */
export function ExtractorSelect({ value, onChange }: { value: ExportFormat; onChange: (f: ExportFormat) => void }) {
return (
<Select
aria-label="Data extractor"
value={value}
options={EXPORT_FORMATS.map((f) => ({ value: f.id, label: f.label }))}
onChange={(v) => onChange(v as ExportFormat)}
/>
);
}
/** The copy format plain ⌘C uses under a toolbar extractor (cell copies stay cell-shaped). */
export const copyFormatOf = (extractor: ExportFormat): CopyFormat =>
extractor === "csv" ? "csv" : extractor === "onerow" ? "onerow" : "tsv";
/** The Record / Value / Aggregates panel's toggle (IDEA's "Show Value Editor"). */
export function PanelToggle({ panel, onChange }: { panel: DataPanel | null; onChange: (p: DataPanel | null) => void }) {
return (
<IconButton
icon="split"
title={panel ? "Hide Record / Value / Aggregates" : "Show Record / Value / Aggregates"}
aria-pressed={!!panel}
onClick={() => onChange(panel ? null : "record")}
/>
);
}
/** Local filter and sort of the column set `key`. */
interface Shaping {
key: string;
filter: LocalFilter;
sort: LocalSort | null;
}
export interface DataViewProps extends Pick<
GridProps,
"rowState" | "isModified" | "editable" | "onEdit" | "onResetCell" | "driver" | "sort" | "onSort" | "rowMenu"
> {
columns: readonly GridColumn[];
rowCount: number;
value: (row: number, col: number) => Cell;
/** Rows from here on (the table editor's added rows) are never filtered or sorted. */
fixedRows?: number;
firstRowNumber?: number;
/** The side panel shown (`null`: hidden). */
panel: DataPanel | null;
onPanelChange: (panel: DataPanel | null) => void;
/** Plain ⌘C's copy format (the toolbar's extractor; TSV by default). */
copyFormat?: CopyFormat;
/** The search bar is shown (the toolbar's search button, ⌘F in the grid). */
searchOpen?: boolean;
onSearchOpenChange?: (open: boolean) => void;
revealColumn?: GridProps["revealColumn"];
"aria-label"?: string;
}
const NO_SEARCH: SearchOptions = { caseSensitive: false, wholeWord: false, regex: false };
interface SearchState {
query: string;
options: SearchOptions;
/** Show only the rows with a match (IDEA's Filter rows). */
filterRows: boolean;
/** Index of the current match. */
current: number;
}
export function DataView(props: DataViewProps) {
const { columns, rowCount, value, fixedRows = rowCount, panel, onPanelChange } = props;
const columnKey = columns.map((c) => c.name).join("\u0000");
// Filter and sort belong to a column set: another one (a re-run query) starts without them.
const [shaping, setShaping] = useState<Shaping>({ key: columnKey, filter: new Map(), sort: null });
const current: Shaping = shaping.key === columnKey ? shaping : { key: columnKey, filter: new Map(), sort: null };
const { filter, sort: localSort } = current;
const setFilter = (f: LocalFilter | ((prev: LocalFilter) => LocalFilter)) =>
setShaping({ ...current, filter: typeof f === "function" ? f(current.filter) : f });
const setLocalSort = (s: (prev: LocalSort | null) => LocalSort | null) =>
setShaping({ ...current, sort: s(current.sort) });
const [range, setRange] = useState<GridRange | null>(null);
const [filterAt, setFilterAt] = useState<{ col: number; anchor: HTMLElement } | null>(null);
const local = !props.onSort;
// Display row → loaded row; `null` keeps the identity (no filter, no local sort).
const shaped = useMemo(
() =>
filter.size || (local && localSort)
? visibleRows(rowCount, value, filter, local ? localSort : null, fixedRows)
: null,
[rowCount, value, filter, local, localSort, fixedRows],
);
// Search covers the loaded rows only (the page shown).
const { searchOpen = false, onSearchOpenChange } = props;
const [search, setSearch] = useState<SearchState>({ query: "", options: NO_SEARCH, filterRows: false, current: 0 });
const searchInput = useRef<HTMLInputElement>(null);
const matcher = useMemo(
() => (searchOpen ? cellMatcher(search.query, search.options) : null),
[searchOpen, search.query, search.options],
);
const test = typeof matcher === "function" ? matcher : null;
const order = useMemo(() => {
if (!test || !search.filterRows) return shaped;
const base = shaped ?? Array.from({ length: rowCount }, (_, i) => i);
return base.filter((r) => rowMatches(r, columns.length, value, test));
}, [shaped, test, search.filterRows, rowCount, columns.length, value]);
const at = (r: number) => (order ? order[r]! : r);
const shown = order ? order.length : rowCount;
const matches = useMemo(
() => (test ? findCells(order ?? Array.from({ length: rowCount }, (_, i) => i), columns.length, value, test) : []),
[test, order, rowCount, columns.length, value],
);
const matchSet = useMemo(() => new Set(matches.map((m) => `${m.row}:${m.col}`)), [matches]);
const currentMatch = matches.length ? matches[Math.min(search.current, matches.length - 1)]! : null;
const step = (by: number) =>
matches.length &&
setSearch((s) => ({
...s,
current: (Math.min(s.current, matches.length - 1) + by + matches.length) % matches.length,
}));
const openSearch = () => {
onSearchOpenChange?.(true);
requestAnimationFrame(() => {
searchInput.current?.focus();
searchInput.current?.select();
});
};
const onSort = local
? (column: string) => {
const col = columns.findIndex((c) => c.name === column);
// asc → desc → none, like the table editor's.
setLocalSort((s) =>
s?.column !== col ? { column: col, descending: false } : !s.descending ? { ...s, descending: true } : null,
);
}
: props.onSort;
const sort = local
? localSort
? [{ column: columns[localSort.column]?.name ?? "", descending: localSort.descending }]
: []
: props.sort;
return (
<div className={styles.dataView}>
<div className={styles.dataMain}>
{searchOpen && (
<GridSearchBar
inputRef={searchInput}
search={search}
onChange={(p) => setSearch((s) => ({ ...s, ...p, current: 0 }))}
count={matches.length}
active={currentMatch ? Math.min(search.current, matches.length - 1) : -1}
invalid={matcher === "invalid"}
onNext={() => step(1)}
onPrevious={() => step(-1)}
onClose={() => onSearchOpenChange?.(false)}
/>
)}
<div className={clsx(styles.fill, styles.gridHost)}>
<Grid
isMatch={test ? (r, c) => matchSet.has(`${r}:${c}`) : undefined}
currentMatch={currentMatch}
onFind={onSearchOpenChange && openSearch}
revealColumn={props.revealColumn}
aria-label={props["aria-label"]}
columns={columns}
rowCount={shown}
value={(r, c) => value(at(r), c)}
rowState={props.rowState && ((r) => props.rowState!(at(r)))}
isModified={props.isModified && ((r, c) => props.isModified!(at(r), c))}
editable={props.editable}
onResetCell={props.onResetCell && ((r, c) => props.onResetCell!(at(r), c))}
onEdit={props.onEdit && ((r, c, v) => props.onEdit!(at(r), c, v))}
driver={props.driver}
sort={sort}
onSort={onSort}
rowMenu={props.rowMenu && ((rows) => props.rowMenu!(rows.map(at)))}
rowNumber={(r) => (props.firstRowNumber ?? 1) + at(r)}
copyFormat={props.copyFormat}
onSelectionChange={setRange}
onFilter={(col, anchor) => setFilterAt({ col, anchor })}
filtered={(col) => filter.has(col)}
/>
{filter.size > 0 && (
<div className={styles.filterPill} role="status">
{tx`${shown} of ${rowCount} rows`}
<button type="button" className={styles.filterPillClear} onClick={() => setFilter(new Map())}>
<T>Clear local filter</T>
</button>
</div>
)}
</div>
</div>
{filterAt && (
<FilterPopup
anchor={filterAt.anchor}
column={columns[filterAt.col]?.name ?? ""}
values={distinctValues(Math.min(rowCount, fixedRows), value, filterAt.col)}
checked={filter.get(filterAt.col) ?? null}
onToggle={(all, v, on) => setFilter((f) => toggleFilterValue(f, filterAt.col, all, v, on))}
onClear={() =>
setFilter((f) => {
const next = new Map(f);
next.delete(filterAt.col);
return next;
})
}
onClearAll={() => setFilter(new Map())}
onClose={() => setFilterAt(null)}
/>
)}
{panel && (
<SidePanel
panel={panel}
onPanelChange={onPanelChange}
columns={columns}
range={range}
value={(r, c) => value(at(r), c)}
editable={!!props.editable && !!props.onEdit && !!range && props.rowState?.(at(range.lead.row)) !== "deleted"}
onEdit={(r, c, v) => props.onEdit?.(at(r), c, v)}
/>
)}
</div>
);
}
/** IDEA's search bar above the grid: Match Case / Words / Regex, n/m, previous / next, Filter rows. */
function GridSearchBar(props: {
inputRef: RefObject<HTMLInputElement | null>;
search: SearchState;
onChange: (patch: Partial<Omit<SearchState, "current">>) => void;
count: number;
/** Zero-based current match; -1 when there is none. */
active: number;
invalid: boolean;
onNext: () => void;
onPrevious: () => void;
onClose: () => void;
}) {
const { search, count, invalid, active, inputRef, onChange, onNext, onPrevious, onClose } = props;
const none = !!search.query && !invalid && count === 0;
const toggle = (key: keyof SearchOptions) =>
onChange({ options: { ...search.options, [key]: !search.options[key] } });
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
onClose();
} else if (e.key === "Enter" || e.key === "F3") {
e.preventDefault();
if (e.shiftKey) onPrevious();
else onNext();
} else if (e.altKey && !e.metaKey && !e.ctrlKey) {
const key =
e.code === "KeyC" ? "caseSensitive" : e.code === "KeyW" ? "wholeWord" : e.code === "KeyX" ? "regex" : null;
if (key) {
e.preventDefault();
toggle(key);
}
}
};
return (
<div className={styles.gridSearch} role="search" aria-label={tx("Search in results")} onKeyDown={onKeyDown}>
<SearchField
ref={inputRef}
autoFocus
className={styles.gridSearchField}
value={search.query}
onChange={(query) => onChange({ query })}
placeholder="Search in results"
aria-label="Search in results"
invalid={invalid || none}
toggles={[
{
id: "case",
icon: "case",
title: "Match Case",
shortcut: "⌥C",
pressed: search.options.caseSensitive,
onToggle: () => toggle("caseSensitive"),
},
{
id: "word",
icon: "word",
title: "Words",
shortcut: "⌥W",
pressed: search.options.wholeWord,
onToggle: () => toggle("wholeWord"),
},
{
id: "regex",
icon: "regex",
title: "Regex",
shortcut: "⌥X",
pressed: search.options.regex,
onToggle: () => toggle("regex"),
},
]}
/>
<span className={clsx(styles.gridSearchCount, (invalid || none) && styles.gridSearchNone)} aria-live="polite">
{invalid ? tx("Bad regex") : !search.query ? "" : count === 0 ? tx("0 results") : `${active + 1}/${count}`}
</span>
<IconButton
icon="arrow-up"
title="Previous Occurrence"
shortcut="⇧↵"
size="small"
disabled={count === 0}
onClick={onPrevious}
/>
<IconButton
icon="arrow-down"
title="Next Occurrence"
shortcut="↵"
size="small"
disabled={count === 0}
onClick={onNext}
/>
<Checkbox
checked={search.filterRows}
onChange={(filterRows) => onChange({ filterRows })}
label={tx("Filter rows")}
/>
<span className={styles.spacer} />
<IconButton icon="close" title="Close" shortcut="⎋" size="small" onClick={onClose} />
</div>
);
}
function FilterPopup(props: {
anchor: HTMLElement;
column: string;
values: Array<{ value: Cell; count: number }>;
checked: ReadonlySet<Cell> | null;
onToggle: (all: Cell[], v: Cell, on: boolean) => void;
onClear: () => void;
onClearAll: () => void;
onClose: () => void;
}) {
const [query, setQuery] = useState("");
const all = props.values.map((v) => v.value);
const q = query.trim().toLowerCase();
const list = q ? props.values.filter((v) => (v.value ?? "<null>").toLowerCase().includes(q)) : props.values;
return (
<Popup
open
anchor={props.anchor}
placement="bottom-start"
onClose={props.onClose}
aria-label={tx`Local filter of ${props.column}`}
className={styles.filterPopup}
trapFocus
>
<Input
autoFocus
aria-label="Search values"
placeholder={tx`Values of ${props.column}`}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<div className={styles.filterValues} role="group" aria-label={tx("Values")}>
{list.map(({ value: v, count }) => (
<div key={v ?? "\u0000null"} className={styles.filterValue}>
<Checkbox
checked={props.checked ? props.checked.has(v) : true}
onChange={(on) => props.onToggle(all, v, on)}
label={v === null ? <span className={styles.null}>&lt;null&gt;</span> : v}
/>
<span className={styles.filterCount}>{count}</span>
</div>
))}
{!list.length && (
<div className={styles.filterEmpty}>
<T>No matching values</T>
</div>
)}
</div>
<div className={styles.filterButtons}>
<Button size="small" disabled={!props.checked} onClick={props.onClear}>
<T>Clear Filter</T>
</Button>
<Button size="small" onClick={props.onClearAll}>
<T>Clear Local Filter For All Columns</T>
</Button>
</div>
</Popup>
);
}
const AGGREGATE_ROWS: ReadonlyArray<[label: string, key: keyof ReturnType<typeof aggregates>]> = [
["Count", "count"],
["Distinct", "distinct"],
["Nulls", "nulls"],
["Sum", "sum"],
["Avg", "avg"],
["Median", "median"],
["Min", "min"],
["Max", "max"],
];
function SidePanel(props: {
panel: DataPanel;
onPanelChange: (p: DataPanel | null) => void;
columns: readonly GridColumn[];
range: GridRange | null;
value: (row: number, col: number) => Cell;
editable: boolean;
onEdit: (row: number, col: number, v: Cell) => void;
}) {
const { range, value, columns } = props;
return (
<aside className={styles.sidePanel} aria-label={tx("Value panel")}>
<div className={styles.sidePanelHead}>
<Tabs
variant="compact"
aria-label="Value panel"
activeId={props.panel}
onSelect={(id) => props.onPanelChange(id as DataPanel)}
items={[
{ id: "record", label: "Record" },
{ id: "value", label: "Value" },
{ id: "aggregates", label: "Aggregates" },
]}
/>
<span className={styles.spacer} />
<IconButton icon="close" title="Hide" size="small" onClick={() => props.onPanelChange(null)} />
</div>
<div className={styles.sidePanelBody}>
{!range ? (
<div className={styles.filterEmpty}>
<T>Select a cell</T>
</div>
) : props.panel === "record" ? (
<RecordView key={range.lead.row} {...props} row={range.lead.row} />
) : props.panel === "value" ? (
<ValueView
// A committed value (here or in the grid) starts the editor over.
key={`${range.lead.row}:${range.lead.col}\u0000${value(range.lead.row, range.lead.col) ?? "\u0001"}`}
column={columns[range.lead.col] ?? { name: "", type: "" }}
cell={value(range.lead.row, range.lead.col)}
editable={props.editable}
onCommit={(v) => props.onEdit(range.lead.row, range.lead.col, v)}
/>
) : (
<AggregatesView range={range} value={value} />
)}
</div>
</aside>
);
}
/** One field per column of the lead row; edits apply on Enter / leaving the field. */
function RecordView(props: {
columns: readonly GridColumn[];
row: number;
value: (row: number, col: number) => Cell;
editable: boolean;
onEdit: (row: number, col: number, v: Cell) => void;
}) {
return (
<div className={styles.recordFields}>
{props.columns.map((c, i) => (
<RecordField
// A new value (another row, an edit elsewhere) starts the field over.
key={`${c.name}\u0000${props.value(props.row, i) ?? "\u0001"}`}
column={c}
cell={props.value(props.row, i)}
editable={props.editable}
onCommit={(v) => props.onEdit(props.row, i, v)}
/>
))}
</div>
);
}
function RecordField(props: { column: GridColumn; cell: Cell; editable: boolean; onCommit: (v: Cell) => void }) {
const [text, setText] = useState(props.cell ?? "");
const commit = () => {
if (text !== (props.cell ?? "") || (props.cell === null && text !== "")) props.onCommit(text);
};
const c = props.column;
return (
<label className={styles.recordField}>
<span className={styles.recordLabel}>
<Icon name={c.primaryKey ? "db-column-key" : c.foreignKey ? "db-column-fk" : "db-column"} size={16} />
{c.name}
{c.type && c.type !== "NULL" && <span className={styles.treeType}>{c.type}</span>}
</span>
{hasLineBreak(props.cell ?? "") ? (
// A single-line field would drop the line breaks on the first edit.
<textarea
className={styles.recordText}
rows={Math.min(8, (props.cell ?? "").split(/\r\n|\r|\n/).length)}
value={text}
readOnly={!props.editable}
spellCheck={false}
onChange={(e) => setText(e.target.value)}
onBlur={commit}
/>
) : (
<Input
mono
value={text}
readOnly={!props.editable}
placeholder={props.cell === null ? "<null>" : undefined}
onChange={(e) => setText(e.target.value)}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === "Enter") commit();
}}
/>
)}
</label>
);
}
/** The Value panel's editor: plain text, or the JSON code editor for JSON cells (#2333). */
function ValueView(props: { column: GridColumn; cell: Cell; editable: boolean; onCommit: (v: Cell) => void }) {
const name = props.column.name;
const [json] = useState(() => isJsonValue(props.column.type, props.cell));
const validate = isJsonColumn(props.column.type);
// JSON opens pretty-printed; the panel applies what the editor shows.
const [initial] = useState(() => (json ? initialJsonText(props.cell ?? "") : (props.cell ?? "")));
const [text, setText] = useState(initial);
const [error, setError] = useState<JsonError | null>(() =>
props.cell !== null && validate && initial.length <= JSON_INLINE_LIMIT ? jsonErrorOf(initial) : null,
);
const [pending, setPending] = useState(json && initial.length > JSON_INLINE_LIMIT);
const editor = useRef<JsonEditorApi | null>(null);
const dirty = text !== initial;
const commit = () => {
if (props.editable && dirty && !error && !pending) props.onCommit(text);
};
const [windowOpen, setWindowOpen] = useState(false);
return (
<div className={styles.valueView}>
{json ? (
<>
<JsonValueEditor
initial={initial}
validate={validate}
emptyIsNull={props.cell === null}
readOnly={!props.editable}
ariaLabel={tx`Value of ${name}`}
onChange={(t, e, busy) => {
setText(t);
setError(e);
setPending(busy);
}}
onReady={(api) => (editor.current = api)}
onSubmit={commit}
onOpenWindow={() => setWindowOpen(true)}
/>
{error && (
<div className={styles.valueError} role="status">
{error.message}
</div>
)}
<div className={styles.filterButtons}>
<Button
size="small"
disabled={!props.editable || !!error || pending}
onClick={() => editor.current?.reformat()}
>
<T>Reformat</T>
</Button>
<Button size="small" onClick={() => setWindowOpen(true)}>
<T>Open in Window</T>
</Button>
</div>
</>
) : (
<textarea
className={styles.valueText}
aria-label={tx`Value of ${name}`}
value={text}
readOnly={!props.editable}
placeholder={props.cell === null ? "<null>" : undefined}
spellCheck={false}
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && dirty) props.onCommit(text);
}}
/>
)}
{props.editable && (
<div className={styles.filterButtons}>
<Button size="small" disabled={!dirty || !!error || pending} onClick={commit}>
<T>Apply</T>
</Button>
<Button
size="small"
onClick={() => {
if (props.cell !== null) props.onCommit(null);
}}
>
<T>Set NULL</T>
</Button>
</div>
)}
{windowOpen && (
<JsonValueWindow
title={tx`Value of ${name}`}
initial={text}
baseline={initial}
validate={validate}
emptyIsNull={props.cell === null}
readOnly={!props.editable}
onClose={() => setWindowOpen(false)}
onApply={(t) => {
props.onCommit(t);
setWindowOpen(false);
}}
onSetNull={() => {
props.onCommit(null);
setWindowOpen(false);
}}
/>
)}
</div>
);
}
function AggregatesView({ range, value }: { range: GridRange; value: (row: number, col: number) => Cell }) {
const cells: Cell[] = [];
for (let r = range.top; r <= range.bottom; r++)
for (let c = range.left; c <= range.right; c++) cells.push(value(r, c));
const a = aggregates(cells);
const show = (v: number | string | null) => (v === null ? "—" : typeof v === "number" ? formatNumber(v) : v);
return (
<table className={styles.aggregates}>
<tbody>
{AGGREGATE_ROWS.map(([label, key]) => (
<tr key={key}>
<th scope="row">{label}</th>
<td>{show(a[key])}</td>
</tr>
))}
</tbody>
</table>
);
}