feat(database): Revert Selected and Copy Aggregation Result in the data grid (#6418)

Revert Selected drops the pending edits, deletes and added rows of the selected rows only, from the row menu of the table editor and editable results; it takes Cmd+Alt+Z / Ctrl+Alt+Z while the selection has changes, and Revert keeps the shortcut otherwise. Copy Aggregation Result copies one aggregate of the selected cells as the Aggregates panel shows it: Cmd+Shift+C / Ctrl+Shift+C copies the Sum of numbers or the Count otherwise, and the grid context menu lists every aggregate the selection has. Fixes #6308.
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-11-27 16:40:46 +08:00
1 джерело 217693a56f
коміт 807c447792
18 files changed
+292 -17

No files matched your search

+65
Переглянути файл
@@ -0,0 +1,65 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("Copy Aggregation Result copies the selection's Sum, or the aggregate picked in the context menu", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
window.__ipc.handlers.clipboard_write_text = () => null;
const storePath = "/src/features/database/store.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { useDatabase, RESULTS_VIEW } = await import(storePath);
const { showServiceView } = await import(contributionsPath);
const text = "SELECT city, amount FROM orders";
useDatabase.setState({
loaded: true,
sources: [{ id: "shop", name: "Shop", driver: "postgres", readOnly: true }],
consoles: { "shop-console.sql": "shop" },
results: [
{
id: 1,
title: "Result 1",
path: "shop-console.sql",
sourceId: "shop",
outcome: {
statement: { text, from: 0, to: text.length },
error: null,
result: {
statement: text,
columns: [
{ name: "city", typeName: "TEXT" },
{ name: "amount", typeName: "NUMERIC" },
],
rows: [
["Oslo", "10"],
["Lima", "2.5"],
["Kyiv", null],
],
affected: null,
hasMore: false,
elapsedMs: 1,
executionMs: 1,
},
},
page: 0,
pageSize: 500,
},
],
activeResult: 1,
});
showServiceView(RESULTS_VIEW);
});
const grid = page.getByRole("grid", { name: "Result 1", exact: true });
const amounts = grid.getByRole("gridcell").filter({ hasText: /^(10|2\.5)$/ });
await expect(amounts).toHaveCount(2);
await amounts.first().click();
await amounts.last().click({ modifiers: ["Shift"] });
await page.keyboard.press("ControlOrMeta+Shift+C");
await expect.poll(() => ipcCalls(page, "clipboard_write_text")).toEqual([{ text: "12.5" }]);
await amounts.last().click({ button: "right", modifiers: ["Shift"] });
await page.getByRole("menuitem", { name: "Copy Aggregation Result" }).click();
await page.getByRole("menuitem", { name: /^Avg: 6\.25/ }).click();
await expect.poll(() => ipcCalls(page, "clipboard_write_text")).toEqual([{ text: "12.5" }, { text: "6.25" }]);
});
+3 -14
Переглянути файл
@@ -12,11 +12,12 @@ import { EXPORT_FORMATS, exportData, type ExportData, type ExportFormat } from "
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,
formatNumber,
rowMatches,
toggleFilterValue,
visibleRows,
@@ -538,17 +539,6 @@ function FilterPopup(props: {
);
}
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;
@@ -815,14 +805,13 @@ function AggregatesView({ range, value }: { range: GridRange; value: (row: numbe
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);
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>
<td>{aggregateText(a, key) ?? "—"}</td>
</tr>
))}
</tbody>
+64
Переглянути файл
@@ -862,6 +862,70 @@ describe("Set NULL / Set DEFAULT (issue #2331, phase 1)", () => {
});
});
describe("Copy Aggregation Result", () => {
const amounts = [["10"], ["2.5"], [null]];
const renderAmounts = () =>
render(
<>
<Grid columns={[{ name: "amount", type: "numeric" }]} rowCount={3} value={(r, c) => amounts[r]![c]!} />
<ContextMenuHost />
</>,
);
const selectAll = () => {
const cells = screen.getAllByRole("gridcell");
fireEvent.mouseDown(cells[0]!, { button: 0 });
fireEvent.mouseEnter(cells[2]!);
fireEvent.mouseUp(window);
};
it.each([
["intellij-macos", { metaKey: true }],
["intellij-windows", { ctrlKey: true }],
] as const)("copies the selection's Sum with %s's Copy Paths shortcut", (preset, modifiers) => {
useKeymap.setState({ preset, overrides: {} });
const writeText = vi.fn();
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
renderAmounts();
selectAll();
fireEvent.keyDown(screen.getByRole("grid"), { key: "C", code: "KeyC", shiftKey: true, ...modifiers });
expect(writeText).toHaveBeenCalledWith("12.5");
});
it("copies the Count of text, and offers only the aggregates the selection has", async () => {
const writeText = vi.fn();
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
render(
<>
<Grid columns={[{ name: "city", type: "text" }]} rowCount={2} value={(r) => ["Oslo", "Lima"][r]!} />
<ContextMenuHost />
</>,
);
const cells = screen.getAllByRole("gridcell");
fireEvent.mouseDown(cells[0]!, { button: 0 });
fireEvent.mouseEnter(cells[1]!);
fireEvent.mouseUp(window);
fireEvent.keyDown(screen.getByRole("grid"), { key: "C", code: "KeyC", shiftKey: true, metaKey: true });
expect(writeText).toHaveBeenLastCalledWith("2");
fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 });
await act(async () => void fireEvent.click(screen.getByRole("menuitem", { name: /Copy Aggregation Result/ })));
const names = screen.getAllByRole("menuitem").map((m) => m.textContent ?? "");
expect(names.some((n) => n.startsWith("Min: Lima"))).toBe(true);
expect(names.some((n) => n.startsWith("Sum"))).toBe(false);
});
it("copies the aggregate picked in the context menu as the Aggregates panel shows it", async () => {
const writeText = vi.fn();
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
renderAmounts();
selectAll();
fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 });
await act(async () => void fireEvent.click(screen.getByRole("menuitem", { name: /Copy Aggregation Result/ })));
await act(async () => void fireEvent.click(screen.getByRole("menuitem", { name: /^Avg: / })));
expect(writeText).toHaveBeenCalledWith("6.25");
});
});
describe("cell action routing", () => {
it.each(["intellij-macos", "vscode-macos", "intellij-windows"] as const)(
"uses %s bindings and leaves text editing alone",
+24 -1
Переглянути файл
@@ -34,7 +34,8 @@ import {
NULL_INPUT,
type BooleanLiterals,
} from "./cellEditors";
import { registerCellGrid, type CellActions } from "./cellActions";
import { copyAggregate, registerCellGrid, type CellActions } from "./cellActions";
import { AGGREGATE_ROWS, aggregateText, aggregates } from "./resultView";
import type { DbDriver } from "@/platform/ipc";
export interface GridColumn {
@@ -319,6 +320,12 @@ export function Grid(props: GridProps) {
if (!sel.rows?.length) return block;
return [...new Set([...sel.rows, ...block])].sort((a, b) => a - b);
};
/** The selected cells, row by row: the block's columns of every selected row (as the Aggregates panel). */
const selectedCells = (): Cell[] => {
if (!sel) return [];
const n = norm(sel);
return selectedRows().flatMap((r) => Array.from({ length: n.right - n.left + 1 }, (_, i) => value(r, n.left + i)));
};
const rowSelected = (() => {
const rows = new Set(selectedRows());
return (r: number) => rows.has(r);
@@ -502,6 +509,7 @@ export function Grid(props: GridProps) {
else copy(kind, false);
},
selectedRows,
aggregates: () => (sel && !editing ? aggregates(selectedCells()) : null),
};
Object.assign((cellActions.current ??= {} as CellActions), actions);
});
@@ -640,6 +648,7 @@ export function Grid(props: GridProps) {
{ kind: "action", action: "db.copyWithHeader", arg: cellActions.current },
{ kind: "action", action: "db.copyRowsAsTsv", arg: cellActions.current },
{ kind: "action", action: "db.copyRowsAsCsv", arg: cellActions.current },
aggregateMenu(cellActions.current),
];
if (editable && onEdit) {
items.push(
@@ -993,3 +1002,17 @@ function CellSelect({
</div>
);
}
/** Copy Aggregation Result › each aggregate the selection has (Sum of text has none), with its value. */
function aggregateMenu(grid: CellActions): MenuItem {
const a = grid.aggregates();
const submenu: MenuItem[] = a
? AGGREGATE_ROWS.flatMap(([label, key]) => {
const text = aggregateText(a, key);
return text === null
? []
: [{ label: `${tx(label)}: ${text}`, verbatim: true, run: () => copyAggregate(grid, key) }];
})
: [];
return { label: "Copy Aggregation Result", disabled: !submenu.length, submenu };
}
+20 -1
Переглянути файл
@@ -29,7 +29,16 @@ import { ColumnsPopup } from "./ColumnsPopup";
import { cellOf, cutLength, hasCutCells, loadCells, loadPage, rowsOf, useCutCells } from "./cutCells";
import { DataView, ExtractorSelect, PanelToggle, copyFormatOf, exportMenu, type DataPanel } from "./DataView";
import type { ExportData, ExportFormat } from "./export";
import { buildRowEdits, emptyEdits, hasEdits, splitTarget, type Cell, type PendingEdits } from "./model";
import {
buildRowEdits,
emptyEdits,
hasEdits,
revertRows,
rowsHaveEdits,
splitTarget,
type Cell,
type PendingEdits,
} from "./model";
import {
editStatements,
pkResultColumns,
@@ -527,6 +536,10 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
enabled: (rows) => rowsEditable && rows.some((row) => edits.deletes.has(row)),
run: restoreRows,
},
revertRows: {
enabled: (rows) => rowsEditable && rowsHaveEdits(edits, rows, loaded),
run: (rows) => setEdits((e) => revertRows(e, rows, loaded)),
},
}
: undefined;
tableEditorChanged(handle);
@@ -659,6 +672,12 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
arg: { rows, editor: handleRef.current },
},
{ kind: "action", action: "db.restoreRows", arg: { rows, editor: handleRef.current } },
{
kind: "action",
action: "db.revertSelected",
icon: "revert",
arg: { rows, editor: handleRef.current },
},
]
: []
}
+7
Переглянути файл
@@ -26,6 +26,8 @@ import {
formatOrderBy,
hasEdits,
parseOrderBy,
revertRows,
rowsHaveEdits,
type Cell,
type PendingEdits,
} from "./model";
@@ -299,6 +301,10 @@ export function TableEditor({ input }: { input: EditorInput }) {
},
deleteRows: { enabled: (rows) => editable && rows.length > 0, run: deleteRows },
restoreRows: { enabled: (rows) => editable && rows.some((r) => edits.deletes.has(r)), run: restoreRows },
revertRows: {
enabled: (rows) => editable && rowsHaveEdits(edits, rows, loaded),
run: (rows) => setEdits((e) => revertRows(e, rows, loaded)),
},
};
useEffect(() => registerTableEditor(viewRef.current!, handle), [handle]);
useEffect(() => tableEditorChanged(handle), [handle, dirty, editable]);
@@ -506,6 +512,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
? [
{ kind: "action", action: "db.deleteRows", icon: "trash", arg: { rows, editor: handle } },
{ kind: "action", action: "db.restoreRows", arg: { rows, editor: handle } },
{ kind: "action", action: "db.revertSelected", icon: "revert", arg: { rows, editor: handle } },
]
: []
}
+23
Переглянути файл
@@ -1,5 +1,7 @@
import { registerActions, type ActionContext } from "@/platform/actions";
import { getContext, setContext } from "@/platform/context";
import { writeClipboardText } from "@/platform/clipboard";
import { aggregateText, defaultAggregate, type Aggregates } from "./resultView";
export type CellCopy = "tsv" | "csv" | "onerow" | "header" | "rowsTsv" | "rowsCsv";
@@ -19,6 +21,15 @@ export interface CellActions {
copy(kind: CellCopy): void;
/** Rows of the selection, top to bottom. */
selectedRows(): number[];
/** The Aggregates panel's figures for the selected cells; null without a selection. */
aggregates(): Aggregates | null;
}
/** Copy Aggregation Result: one aggregate of the selection, as the Aggregates panel shows it. */
export function copyAggregate(grid: CellActions, key?: keyof Aggregates): void {
const a = grid.aggregates();
const text = a && aggregateText(a, key ?? defaultAggregate(a));
if (text !== null && text !== undefined) void writeClipboardText(text);
}
const grids = new WeakMap<Element, CellActions>();
@@ -106,6 +117,18 @@ export function installCellActions(): () => void {
enabled: (c) => handle(c)?.canEditCell() ?? false,
run: (c) => handle(c)?.editCell(),
},
{
id: "db.copyAggregationResult",
title: "Copy Aggregation Result",
category: "Database",
keywords: ["sum", "count", "aggregate", "total"],
keyWhen: "dbCellGridFocus",
enabled: (c) => handle(c)?.hasSelection() ?? false,
run: (c) => {
const grid = handle(c);
if (grid?.hasSelection()) copyAggregate(grid);
},
},
...COPIES.map(([kind, id, title]) => ({
id,
title,
+1
Переглянути файл
@@ -87,6 +87,7 @@ const TABLE_COMMANDS: Array<[TableCommand, string, string, string[]]> = [
["exportData", "db.exportData", "Export Data", ["export", "save as"]],
["deleteRows", "db.deleteRows", "Delete Rows", ["remove rows"]],
["restoreRows", "db.restoreRows", "Restore Rows", ["undelete rows"]],
["revertRows", "db.revertSelected", "Revert Selected", ["revert rows", "discard row changes", "undo"]],
];
/** The editor and rows a menu passed (focus has moved to the menu), else the focused grid's. */
+16
Переглянути файл
@@ -138,6 +138,22 @@ export function hasEdits(e: PendingEdits): boolean {
return e.updates.size > 0 || e.deletes.size > 0 || e.inserts.length > 0;
}
/** Whether any of `rows` has a pending change. Rows from `loaded` on are the inserted ones. */
export function rowsHaveEdits(e: PendingEdits, rows: readonly number[], loaded: number): boolean {
return rows.some((r) => (r >= loaded ? r - loaded < e.inserts.length : e.deletes.has(r) || !!e.updates.get(r)?.size));
}
/** `e` without the pending changes of `rows` (Revert Selected): their edits and deletes, and the inserted rows among them. */
export function revertRows(e: PendingEdits, rows: readonly number[], loaded: number): PendingEdits {
const picked = new Set(rows);
const insertsGone = new Set(rows.filter((r) => r >= loaded).map((r) => r - loaded));
return {
updates: new Map([...e.updates].filter(([r]) => !picked.has(r))),
deletes: new Set([...e.deletes].filter((r) => !picked.has(r))),
inserts: e.inserts.filter((_, i) => !insertsGone.has(i)),
};
}
/** The DML requests for `edits` of a page with `columns` / `rows`, keyed by `primaryKey`. */
export function buildRowEdits(
columns: readonly string[],
+31
Переглянути файл
@@ -7,7 +7,10 @@ import {
parseDelimited,
parseOrderBy,
passesObjectFilter,
revertRows,
rowsHaveEdits,
type Cell,
type PendingEdits,
} from "./model";
import { dropSql } from "./objects";
import {
@@ -468,3 +471,31 @@ describe("result pages", () => {
expect(pageFetch(2, 100)).toEqual({ maxRows: 100, skip: 200 });
});
});
describe("Revert Selected", () => {
// Rows 0–2 are loaded; rows 3 and 4 are the two added ones.
const edits = (): PendingEdits => ({
updates: new Map([
[0, new Map([["name", "a"]])],
[2, new Map([["name", "c"]])],
]),
deletes: new Set([1, 2]),
inserts: [new Map([["name", "new 1"]]), new Map([["name", "new 2"]])],
});
it("drops exactly the selected rows' edits, deletes and added rows", () => {
const left = revertRows(edits(), [2, 3], 3);
expect([...left.updates.keys()]).toEqual([0]);
expect([...left.deletes]).toEqual([1]);
expect(left.inserts.map((i) => i.get("name"))).toEqual(["new 2"]);
});
it("is enabled only for rows with a pending change", () => {
expect(rowsHaveEdits(edits(), [0], 3)).toBe(true);
expect(rowsHaveEdits(edits(), [1], 3)).toBe(true);
expect(rowsHaveEdits(edits(), [4], 3)).toBe(true);
const none: PendingEdits = { updates: new Map([[0, new Map()]]), deletes: new Set(), inserts: [] };
expect(rowsHaveEdits(none, [0, 1], 3)).toBe(false);
expect(rowsHaveEdits(none, [3], 3)).toBe(false);
});
});
+23
Переглянути файл
@@ -268,6 +268,29 @@ export function aggregates(cells: readonly Cell[]): Aggregates {
};
}
/** The Aggregates panel's rows, in its order. */
export const AGGREGATE_ROWS: ReadonlyArray<[label: string, key: keyof Aggregates]> = [
["Count", "count"],
["Distinct", "distinct"],
["Nulls", "nulls"],
["Sum", "sum"],
["Avg", "avg"],
["Median", "median"],
["Min", "min"],
["Max", "max"],
];
/** An aggregate as the Aggregates panel shows it; null when the selection has none (Sum of text). */
export function aggregateText(a: Aggregates, key: keyof Aggregates): string | null {
const v = a[key];
return v === null ? null : typeof v === "number" ? formatNumber(v) : v;
}
/** What Copy Aggregation Result copies by default: the Sum of numbers, else the Count. */
export function defaultAggregate(a: Aggregates): keyof Aggregates {
return a.sum !== null ? "sum" : "count";
}
/** A number for display: integers as is, others to at most 6 significant decimals. */
export function formatNumber(n: number): string {
if (Number.isInteger(n)) return String(n);
+2 -1
Переглянути файл
@@ -16,7 +16,8 @@ export type TableCommand =
| "addRow"
| "exportData"
| "deleteRows"
| "restoreRows";
| "restoreRows"
| "revertRows";
export interface TableCommandHandler {
enabled(rows: number[]): boolean;
+1
Переглянути файл
@@ -143,6 +143,7 @@ export const eclipseMacos: Record<string, string[]> = {
"code.surroundWith": ["Meta+Alt+Z"],
// ⌥⌘Z is Surround With here, not the table editor's Revert.
"db.revertChanges": [],
"db.revertSelected": [],
"file.reloadFromDisk": [],
"project.reloadFromDisk": [],
"navigate.toggleBookmark": [],
+3
Переглянути файл
@@ -470,6 +470,9 @@ export const intellijMacos: Record<string, string[]> = {
"db.addRow": ["Meta+N"],
"db.deleteRows": [],
"db.restoreRows": [],
// Revert Selected takes ⌥⌘Z while the selected rows have changes; Revert (everything) otherwise.
"db.revertSelected": ["Meta+Alt+Z"],
"db.copyAggregationResult": ["Meta+Shift+C"],
"db.exportData": [],
"db.editCell": [],
"db.showToolWindow": [],
+3
Переглянути файл
@@ -468,6 +468,9 @@ export const intellijWindows: Record<string, string[]> = {
"db.addRow": ["Alt+Insert"],
"db.deleteRows": ["Ctrl+Y", "Alt+Delete"],
"db.restoreRows": [],
// Revert Selected takes ⌥⌘Z while the selected rows have changes; Revert (everything) otherwise.
"db.revertSelected": ["Ctrl+Alt+Z"],
"db.copyAggregationResult": ["Ctrl+Shift+C"],
"db.exportData": [],
"db.editCell": [],
"db.showToolWindow": [],
+2
Переглянути файл
@@ -36,6 +36,8 @@ export const vscodeMacos: Record<string, string[]> = {
"db.addRow": [],
"db.deleteRows": [],
"db.restoreRows": [],
"db.revertSelected": ["Meta+Alt+Z"],
"db.copyAggregationResult": [],
"db.exportData": [],
"db.editCell": [],
"navigate.relatedSymbol": [],
+2
Переглянути файл
@@ -2651,6 +2651,8 @@
"Restores the active saved layout, or the default layout when none is active.": "還原目前選中的已儲存佈局;沒有選中的佈局時還原預設佈局。",
"Restore Defaults": "還原預設值",
"Restore Rows": "還原列",
"Revert Selected": "還原所選",
"Copy Aggregation Result": "複製彙總結果",
"Restore Size": "還原大小",
"Maximize Editor": "最大化編輯器",
"Restore detected roots": "還原檢測到的根",
+2
Переглянути файл
@@ -3193,6 +3193,8 @@
"Restores the active saved layout, or the default layout when none is active.": "恢复当前选中的已保存布局;没有选中的布局时恢复默认布局。",
"Restore Defaults": "恢复默认值",
"Restore Rows": "恢复行",
"Revert Selected": "还原所选",
"Copy Aggregation Result": "复制聚合结果",
"Restore Size": "恢复大小",
"Maximize Editor": "最大化编辑器",
"Restore detected roots": "恢复检测到的根",