Файли
openidea/src/features/database/DataView.tsx
T
Waiting-Night 52e6a0f84b feat(database): honor selected cells in SQL extractor copy (#7177)
Plain Copy in database result grids uses the active SQL data extractor instead of TSV, as DataGrip does. The Where Clause extractor builds the clause from the selected cells (one value: a = v; several in one column: IN (…); several columns: AND; several rows: OR of ANDs; NULL as IS NULL); the Insert/Update/Delete extractors keep working on the selected rows.

Co-authored-by: wangyuewen-china <[email protected]>
2026-12-01 15:56:16 +08:00

847 рядки
30 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
/**
* 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 ReactNode, 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, SQL_FORMATS, exportData, selectionWhere, type ExportData, type ExportFormat } from "./export";
import { Grid, type CopyFormat, type GridColumn, type GridProps, type GridRange } from "./Grid";
import type { Cell } from "./model";
import {
AGGREGATE_ROWS,
aggregateText,
aggregates,
cellMatcher,
distinctValues,
findCells,
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, txPart } 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 ${txPart(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
variant="ghost"
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 toolbar's extractor; `table` is the whole table to export (`null`: nothing, already reported). */
export interface ExtractorMenu {
value: ExportFormat;
onChange: (f: ExportFormat) => void;
table: () => ExportData | null | Promise<ExportData | null>;
}
async function copyRowsAs(extractor: ExtractorMenu, rows: readonly number[], format: ExportFormat) {
const data = await Promise.resolve(extractor.table());
if (!data) return;
const picked = rows.flatMap((row) => (data.rows[row] ? [data.rows[row]] : []));
if (picked.length) await writeClipboardText(exportData(format, { ...data, rows: picked }));
}
async function copySelectionAs(
extractor: ExtractorMenu,
rows: readonly number[],
cols: readonly number[],
format: ExportFormat,
) {
const data = await Promise.resolve(extractor.table());
if (!data) return;
if (format === "where") {
const text = selectionWhere(data, rows, cols);
if (text) await writeClipboardText(text);
return;
}
const picked = rows.flatMap((row) => (data.rows[row] ? [data.rows[row]] : []));
if (picked.length) await writeClipboardText(exportData(format, { ...data, rows: picked }));
}
const PANEL_ENTRIES: ReadonlyArray<{ panel: DataPanel; label: string }> = [
{ panel: "record", label: "Show Record View" },
{ panel: "value", label: "Open in Value Editor" },
{ panel: "aggregates", label: "Show Aggregate View" },
];
/**
* The view's entries of the grid's context menu (DataGrip's): the side panels, checked while
* shown, then the toolbar's extractor and Export Table to Clipboard when the view has them.
*/
export function viewMenu(
panel: DataPanel | null,
onPanelChange: (panel: DataPanel | null) => void,
extractor?: ExtractorMenu,
): MenuItem[] {
const items: MenuItem[] = PANEL_ENTRIES.map(({ panel: p, label }) => ({
label,
checked: panel === p,
run: () => onPanelChange(panel === p ? null : p),
}));
if (!extractor) return items;
return [
...items,
{ kind: "separator" },
{
label: "Data Extractor",
submenu: EXPORT_FORMATS.map((f) => ({
label: f.label,
checked: f.id === extractor.value,
run: () => extractor.onChange(f.id),
})),
},
{
label: "Export Table to Clipboard",
icon: "copy",
run: () =>
void Promise.resolve(extractor.table()).then(
(data) => data && writeClipboardText(exportData(extractor.value, data)),
),
},
];
}
/** Copy as › SQL INSERT / UPDATE / DELETE of the whole selected rows, in the selected order. */
function sqlCopies(rows: readonly number[], extractor: ExtractorMenu): MenuItem[] {
const copy = (format: ExportFormat) => () => void copyRowsAs(extractor, rows, format);
return [
{ label: "SQL INSERT", run: copy("sql") },
{ label: "SQL UPDATE", run: copy("sqlUpdates") },
{ label: "SQL DELETE", run: copy("sqlDeletes") },
];
}
/** 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"
| "truncated"
| "loadFull"
| "initialScrollLeft"
| "onHorizontalScroll"
> {
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;
pager?: ReactNode;
/** 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 toolbar's extractor, also offered in the grid's context menu with the whole table to copy. */
extractor?: ExtractorMenu;
/** 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 extractor = props.extractor;
const copySelectedCells =
extractor && SQL_FORMATS.has(extractor.value)
? (rows: number[], cols: number[]) => void copySelectionAs(extractor, rows.map(at), cols, extractor.value)
: undefined;
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)}
truncated={props.truncated && ((r, c) => props.truncated!(at(r), c))}
loadFull={
props.loadFull && ((cells) => props.loadFull!(cells.map(({ row, col }) => ({ row: at(row), col }))))
}
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}
copySelectedCells={copySelectedCells}
copyAs={extractor && ((rows) => sqlCopies(rows.map(at), extractor))}
rowMenu={(rows) => {
const own = props.rowMenu?.(rows.map(at)) ?? [];
const view = viewMenu(panel, onPanelChange, props.extractor);
return own.length ? [...own, { kind: "separator" }, ...view] : view;
}}
rowNumber={(r) => (props.firstRowNumber ?? 1) + at(r)}
copyFormat={props.copyFormat}
onSelectionChange={setRange}
onFilter={(col, anchor) => setFilterAt({ col, anchor })}
filtered={(col) => filter.has(col)}
initialScrollLeft={props.initialScrollLeft}
onHorizontalScroll={props.onHorizontalScroll}
/>
{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>
{props.pager && <div className={styles.pagerDock}>{props.pager}</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={(v, on) => setFilter((f) => toggleFilterValue(f, filterAt.col, 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)}
truncated={props.truncated && ((r, c) => props.truncated!(at(r), c))}
loadFull={
props.loadFull && ((cells) => props.loadFull!(cells.map(({ row, col }) => ({ row: at(row), col }))))
}
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: (v: Cell, on: boolean) => void;
onClear: () => void;
onClearAll: () => void;
onClose: () => void;
}) {
const [query, setQuery] = useState("");
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?.has(v) ?? false}
onChange={(on) => props.onToggle(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>
);
}
function SidePanel(props: {
panel: DataPanel;
onPanelChange: (p: DataPanel | null) => void;
columns: readonly GridColumn[];
range: GridRange | null;
value: (row: number, col: number) => Cell;
truncated?: GridProps["truncated"];
loadFull?: GridProps["loadFull"];
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)}
cut={props.truncated?.(range.lead.row, range.lead.col) ?? null}
onLoad={() => void props.loadFull?.([{ row: range.lead.row, col: 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;
truncated?: GridProps["truncated"];
loadFull?: GridProps["loadFull"];
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)}
cut={props.truncated?.(props.row, i) ?? null}
onLoad={() => void props.loadFull?.([{ row: props.row, col: i }])}
editable={props.editable}
onCommit={(v) => props.onEdit(props.row, i, v)}
/>
))}
</div>
);
}
/** What a value that is shown cut short offers: the whole value is read on request (until then it is read-only). */
function CutNotice(props: { shown: number; total: number; onLoad: () => void }) {
const { shown, total } = props;
return (
<div className={styles.cutNotice} role="status">
<span>{tx`Only the first ${shown} of ${total} characters are shown.`}</span>
<Button size="small" onClick={props.onLoad}>
<T>Load whole value</T>
</Button>
</div>
);
}
function RecordField(props: {
column: GridColumn;
cell: Cell;
cut: number | null;
onLoad: () => void;
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;
const editable = props.editable && props.cut === null;
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={!editable}
spellCheck={false}
onChange={(e) => setText(e.target.value)}
onBlur={commit}
/>
) : (
<Input
mono
value={text}
readOnly={!editable}
placeholder={props.cell === null ? "<null>" : undefined}
onChange={(e) => setText(e.target.value)}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === "Enter") commit();
}}
/>
)}
</label>
{props.cut !== null && <CutNotice shown={props.cell?.length ?? 0} total={props.cut} onLoad={props.onLoad} />}
</>
);
}
/** The Value panel's editor: plain text, or the JSON code editor for JSON cells (#2333). */
function ValueView(props: {
column: GridColumn;
cell: Cell;
cut: number | null;
onLoad: () => void;
editable: boolean;
onCommit: (v: Cell) => void;
}) {
const name = props.column.name;
const editable = props.editable && props.cut === null;
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 (editable && dirty && !error && !pending) props.onCommit(text);
};
const [windowOpen, setWindowOpen] = useState(false);
return (
<div className={styles.valueView}>
{props.cut !== null && <CutNotice shown={props.cell?.length ?? 0} total={props.cut} onLoad={props.onLoad} />}
{json ? (
<>
<JsonValueEditor
initial={initial}
validate={validate}
emptyIsNull={props.cell === null}
readOnly={!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={!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={!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);
}}
/>
)}
{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={!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[] = [];
const rows = new Set(range.rows);
for (let r = range.top; r <= range.bottom; r++) rows.add(r);
for (const r of rows) for (let c = range.left; c <= range.right; c++) cells.push(value(r, c));
const a = aggregates(cells);
return (
<table className={styles.aggregates}>
<tbody>
{AGGREGATE_ROWS.map(([label, key]) => (
<tr key={key}>
<th scope="row">{label}</th>
<td>{aggregateText(a, key) ?? "—"}</td>
</tr>
))}
</tbody>
</table>
);
}