mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-17 23:53:41 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
975b910c34 |
No files matched your search
@@ -146,7 +146,8 @@ Closing a selected result activates its left neighbor, or its right neighbor if
|
||||
**Edit Data** (`F4`) opens a table in an editor tab with server-side paging (100 to 5,000 rows), a `WHERE` filter and an `ORDER BY` field (both with completion). Click a column header to sort; `Shift`-click to add more sort columns.
|
||||
|
||||
- Double-click, `Enter` or `F2` edits a cell; `Shift+Enter` opens a larger editor. Pasting tab-separated text fills several cells.
|
||||
- **Add Row**, **Delete Rows**, **Set NULL** (`⌘⌫` / `Ctrl+Backspace`), **Set DEFAULT** (`⌘⇧⌫` / `Ctrl+Shift+Backspace`). `Space` toggles booleans.
|
||||
- **Add Row** (`⌘N` / `Alt+Insert`), **Delete Rows** (`Ctrl+Y` on Windows and Linux), **Set NULL** (`⌘⌫` / `Ctrl+Backspace`), **Set DEFAULT** (`⌘⇧⌫` / `Ctrl+Shift+Backspace`). `Space` toggles booleans.
|
||||
- **Reload Page** (`⌘R` / `Ctrl+F5`), **Previous Page** and **Next Page** (`⌘⌥↑` / `⌘⌥↓`, `Ctrl+Alt+Up` / `Ctrl+Alt+Down`). These, the copy commands and **Export Data** are actions: find them with **Find Action** and assign shortcuts in **Settings › Keymap**.
|
||||
- **Submit** (`⌘Enter` / `Ctrl+Enter`) sends all pending changes in one transaction; **Revert** (`⌘⌥Z` / `Ctrl+Alt+Z`) discards them.
|
||||
|
||||
Console results are editable the same way when the query is a plain select from one table that includes the primary key. Tables without a primary key, joins, aggregates, `UNION` queries, read-only data sources and ClickHouse results are read-only.
|
||||
|
||||
@@ -145,7 +145,8 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外
|
||||
**编辑数据**(`F4`)在编辑器标签页中打开表,服务器端分页(每页 100 到 5,000 行),并提供 `WHERE` 过滤和 `ORDER BY` 字段(都支持补全)。点击列标题排序,按住 `Shift` 点击可以追加排序列。
|
||||
|
||||
- 双击、`Enter` 或 `F2` 编辑单元格;`Shift+Enter` 打开更大的编辑框。粘贴制表符分隔的文本可以一次填写多个单元格。
|
||||
- **添加行**、**删除行**、**设为 NULL**(`⌘⌫` / `Ctrl+Backspace`)、**设为默认值**(`⌘⇧⌫` / `Ctrl+Shift+Backspace`)。`Space` 切换布尔值。
|
||||
- **添加行**(`⌘N` / `Alt+Insert`)、**删除行**(Windows 和 Linux 上为 `Ctrl+Y`)、**设为 NULL**(`⌘⌫` / `Ctrl+Backspace`)、**设为默认值**(`⌘⇧⌫` / `Ctrl+Shift+Backspace`)。`Space` 切换布尔值。
|
||||
- **重新加载页面**(`⌘R` / `Ctrl+F5`)、**上一页** 和 **下一页**(`⌘⌥↑` / `⌘⌥↓`,`Ctrl+Alt+Up` / `Ctrl+Alt+Down`)。这些命令、各种复制命令和 **导出数据** 都是操作:可以在 **查找操作** 中找到,并在 **设置 › 按键映射** 中设置快捷键。
|
||||
- **提交**(`⌘Enter` / `Ctrl+Enter`)在一个事务中提交所有待定更改;**还原**(`⌘⌥Z` / `Ctrl+Alt+Z`)放弃更改。
|
||||
|
||||
如果控制台查询是对单表的简单 select 且包含主键,结果同样可以编辑。没有主键的表、连接查询、聚合、`UNION` 查询、只读数据源和 ClickHouse 的结果都是只读的。
|
||||
|
||||
@@ -409,6 +409,23 @@ export function Grid(props: GridProps) {
|
||||
const anchor = scrollRef.current?.querySelectorAll<HTMLElement>("[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);
|
||||
});
|
||||
@@ -529,20 +546,19 @@ export function Grid(props: GridProps) {
|
||||
{
|
||||
label: "Copy as",
|
||||
submenu: [
|
||||
{ label: "TSV", verbatim: true, run: () => copy("tsv", false) },
|
||||
{ label: "CSV", verbatim: true, run: () => copy("csv", false) },
|
||||
{ label: "One-Row", run: () => copy("onerow", false) },
|
||||
{ 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 },
|
||||
],
|
||||
},
|
||||
{ label: "Copy with Header", run: () => copy("tsv", true) },
|
||||
{ label: "Copy Rows as TSV", run: () => copy("tsv", true, true) },
|
||||
{ label: "Copy Rows as CSV", run: () => copy("csv", true, true) },
|
||||
{ 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) {
|
||||
const n = norm(sel);
|
||||
items.push(
|
||||
{ kind: "separator" },
|
||||
{ label: "Edit Cell", disabled: n.top !== n.bottom || n.left !== n.right, run: () => startEdit(n.top, n.left) },
|
||||
{ kind: "action", action: "db.editCell", arg: cellActions.current },
|
||||
{ kind: "action", action: "db.setCellNull", arg: cellActions.current },
|
||||
{ kind: "action", action: "db.setCellDefault", arg: cellActions.current },
|
||||
);
|
||||
|
||||
@@ -137,7 +137,8 @@ function readonlyNotice(reason: EditBlockReason): string {
|
||||
}
|
||||
|
||||
/** IDEA's pager at the bottom of a result: |< < 1-500 of 501+ > >| and the page size; paging runs the query again. */
|
||||
function Pager({ tab }: { tab: ResultTab }) {
|
||||
/** The result tab's page position and the page moves it allows, shared by the pager and the `db.*Page` actions. */
|
||||
function pagerOf(tab: ResultTab) {
|
||||
const r = tab.outcome.result!;
|
||||
const page = tab.page ?? 0;
|
||||
const pageSize = tab.pageSize ?? Math.max(r.rows.length, 1);
|
||||
@@ -154,6 +155,21 @@ function Pager({ tab }: { tab: ResultTab }) {
|
||||
}
|
||||
if (lastPage !== null && lastPage !== page) go(lastPage);
|
||||
};
|
||||
return {
|
||||
page,
|
||||
pageSize,
|
||||
w,
|
||||
canPage,
|
||||
go,
|
||||
goLast,
|
||||
canPrevious: canPage && page > 0,
|
||||
canNext: canPage && r.hasMore,
|
||||
canLast: canPage && !((!r.hasMore && w.total !== null) || (w.total === null && !countable(tab))),
|
||||
};
|
||||
}
|
||||
|
||||
function Pager({ tab }: { tab: ResultTab }) {
|
||||
const { page, pageSize, w, canPage, go, goLast, canPrevious, canNext, canLast } = pagerOf(tab);
|
||||
const { first, last } = w;
|
||||
const total = w.total === null ? `${w.last + 1}+` : String(w.total);
|
||||
const sizes = PAGE_SIZES.includes(pageSize) ? PAGE_SIZES : [...PAGE_SIZES, pageSize].sort((a, b) => a - b);
|
||||
@@ -162,15 +178,17 @@ function Pager({ tab }: { tab: ResultTab }) {
|
||||
<IconButton
|
||||
icon="page-first"
|
||||
title="First Page"
|
||||
shortcut={shortcutLabel("db.firstPage")}
|
||||
size="small"
|
||||
disabled={!canPage || page === 0}
|
||||
disabled={!canPrevious}
|
||||
onClick={() => go(0)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="chevron-left"
|
||||
title="Previous Page"
|
||||
shortcut={shortcutLabel("db.previousPage")}
|
||||
size="small"
|
||||
disabled={!canPage || page === 0}
|
||||
disabled={!canPrevious}
|
||||
onClick={() => go(page - 1)}
|
||||
/>
|
||||
<button
|
||||
@@ -185,15 +203,17 @@ function Pager({ tab }: { tab: ResultTab }) {
|
||||
<IconButton
|
||||
icon="chevron-right"
|
||||
title="Next Page"
|
||||
shortcut={shortcutLabel("db.nextPage")}
|
||||
size="small"
|
||||
disabled={!canPage || !r.hasMore}
|
||||
disabled={!canNext}
|
||||
onClick={() => go(page + 1)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="page-last"
|
||||
title="Last Page"
|
||||
shortcut={shortcutLabel("db.lastPage")}
|
||||
size="small"
|
||||
disabled={!canPage || (!r.hasMore && w.total !== null) || (w.total === null && !countable(tab))}
|
||||
disabled={!canLast}
|
||||
onClick={() => void goLast()}
|
||||
/>
|
||||
<Select
|
||||
@@ -365,6 +385,10 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
return { ...e, deletes, inserts: e.inserts.filter((_, i) => !insertsGone.has(i)) };
|
||||
});
|
||||
|
||||
const addRow = () => setEdits((e) => ({ ...e, inserts: [...e.inserts, new Map()] }));
|
||||
const restoreRows = (rows: number[]) =>
|
||||
setEdits((e) => ({ ...e, deletes: new Set([...e.deletes].filter((d) => !rows.includes(d))) }));
|
||||
|
||||
const dirty = hasEdits(edits);
|
||||
const submitting = useSyncExternalStore(subscribeResults, () => !!r && submittingResults.has(r));
|
||||
const busy = submitting || !!tab.busy;
|
||||
@@ -397,6 +421,17 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
}
|
||||
};
|
||||
|
||||
const showExport = (at: { x: number; y: number }) =>
|
||||
r &&
|
||||
showContextMenu(
|
||||
at,
|
||||
exportMenu(
|
||||
{ columns, rows: r.rows, driver, table: queryTable(text, { driver }) },
|
||||
queryTable(text, { driver }),
|
||||
extractor,
|
||||
),
|
||||
);
|
||||
|
||||
// Submit / Revert / Go to Column (⌘↩ / ⌥⌘Z / ⌘F12) reach the latest state through the handle, as in the table editor.
|
||||
const canSubmit = editable && dirty && !busy;
|
||||
const viewRef = useRef<HTMLDivElement>(null);
|
||||
@@ -421,6 +456,30 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
const rect = viewRef.current?.getBoundingClientRect();
|
||||
if (view === "table" && rect) setColumnsAt({ x: rect.left + rect.width / 2, y: rect.top + 48 });
|
||||
};
|
||||
const pager = r ? pagerOf(tab) : null;
|
||||
const rowsEditable = editable && !busy && view === "table";
|
||||
handle.commands = pager
|
||||
? {
|
||||
reload: { enabled: () => !busy, run: () => void rerunResult(tab.id) },
|
||||
firstPage: { enabled: () => pager.canPrevious, run: () => pager.go(0) },
|
||||
previousPage: { enabled: () => pager.canPrevious, run: () => pager.go(pager.page - 1) },
|
||||
nextPage: { enabled: () => pager.canNext, run: () => pager.go(pager.page + 1) },
|
||||
lastPage: { enabled: () => pager.canLast, run: () => void pager.goLast() },
|
||||
addRow: { enabled: () => editable && !busy, run: addRow },
|
||||
exportData: {
|
||||
enabled: () => true,
|
||||
run: () => {
|
||||
const rect = viewRef.current?.querySelector("[data-db-export]")?.getBoundingClientRect();
|
||||
if (rect) showExport({ x: rect.left, y: rect.bottom });
|
||||
},
|
||||
},
|
||||
deleteRows: { enabled: (rows) => rowsEditable && rows.length > 0, run: deleteRows },
|
||||
restoreRows: {
|
||||
enabled: (rows) => rowsEditable && rows.some((row) => edits.deletes.has(row)),
|
||||
run: restoreRows,
|
||||
},
|
||||
}
|
||||
: undefined;
|
||||
tableEditorChanged(handle);
|
||||
});
|
||||
const hasResult = !!r;
|
||||
@@ -430,12 +489,6 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
);
|
||||
|
||||
if (!r) return null;
|
||||
const data = (): ExportData => ({
|
||||
columns,
|
||||
rows: r.rows,
|
||||
driver,
|
||||
table: queryTable(text, { driver }),
|
||||
});
|
||||
const tableLabel = target ? `${target.schema ? `${target.schema}.` : ""}${target.table}` : "";
|
||||
const tablePkCount = detailsValue?.columns.filter((c) => c.primaryKey).length ?? 0;
|
||||
let notice: string | null = null;
|
||||
@@ -456,7 +509,13 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
<IconButton icon="database" title="Table" aria-pressed={view === "table"} onClick={() => setView("table")} />
|
||||
<IconButton icon="db-chart" title="Chart" aria-pressed={view === "chart"} onClick={() => setView("chart")} />
|
||||
<span className={styles.toolbarSeparator} />
|
||||
<IconButton icon="refresh" title="Rerun Query" disabled={busy} onClick={() => void rerunResult(tab.id)} />
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
title="Rerun Query"
|
||||
shortcut={shortcutLabel("db.reloadPage")}
|
||||
disabled={busy}
|
||||
onClick={() => void rerunResult(tab.id)}
|
||||
/>
|
||||
<PinButton tab={tab} />
|
||||
{view === "table" && (
|
||||
<IconButton
|
||||
@@ -472,8 +531,9 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
<IconButton
|
||||
icon="plus"
|
||||
title="Add Row"
|
||||
shortcut={shortcutLabel("db.addRow")}
|
||||
disabled={busy}
|
||||
onClick={() => setEdits((e) => ({ ...e, inserts: [...e.inserts, new Map()] }))}
|
||||
onClick={addRow}
|
||||
/>
|
||||
<Button
|
||||
size="small"
|
||||
@@ -503,7 +563,9 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
<IconButton
|
||||
icon="export"
|
||||
title="Export Data"
|
||||
onClick={(e) => showContextMenu(e, exportMenu(data(), queryTable(text, { driver }), extractor))}
|
||||
shortcut={shortcutLabel("db.exportData")}
|
||||
data-db-export=""
|
||||
onClick={(e) => showExport({ x: e.clientX, y: e.clientY })}
|
||||
/>
|
||||
{view === "table" && <PanelToggle panel={panel} onChange={setPanel} />}
|
||||
</Toolbar>
|
||||
@@ -541,15 +603,13 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
rowMenu={(rows) =>
|
||||
editable && !busy
|
||||
? [
|
||||
{ label: "Delete Rows", icon: "trash", run: () => deleteRows(rows) },
|
||||
{
|
||||
label: "Restore Rows",
|
||||
run: () =>
|
||||
setEdits((e) => ({
|
||||
...e,
|
||||
deletes: new Set([...e.deletes].filter((d) => !rows.includes(d))),
|
||||
})),
|
||||
kind: "action",
|
||||
action: "db.deleteRows",
|
||||
icon: "trash",
|
||||
arg: { rows, editor: handleRef.current },
|
||||
},
|
||||
{ kind: "action", action: "db.restoreRows", arg: { rows, editor: handleRef.current } },
|
||||
]
|
||||
: []
|
||||
}
|
||||
|
||||
@@ -215,18 +215,61 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
const r = viewRef.current?.getBoundingClientRect();
|
||||
if (page && r) setColumnsAt({ x: r.left + r.width / 2, y: r.top + 48 });
|
||||
};
|
||||
const addRow = () => setEdits((e) => ({ ...e, inserts: [...e.inserts, new Map()] }));
|
||||
const restoreRows = (rows: number[]) =>
|
||||
setEdits((e) => ({ ...e, deletes: new Set([...e.deletes].filter((d) => !rows.includes(d))) }));
|
||||
const showExport = (at: { x: number; y: number }) =>
|
||||
page &&
|
||||
showContextMenu(
|
||||
at,
|
||||
exportMenu(
|
||||
{
|
||||
columns: gridColumns,
|
||||
rows: page.result.rows,
|
||||
table: ref.table,
|
||||
driver: sourceById(ref.id)?.driver ?? "sqlite",
|
||||
},
|
||||
`${ref.schema}.${ref.table}`,
|
||||
extractor,
|
||||
),
|
||||
);
|
||||
const canPrevious = offset > 0 && !loading;
|
||||
const canNext = !!page?.result.hasMore && !loading;
|
||||
handle.commands = {
|
||||
reload: { enabled: () => !loading, run: reload },
|
||||
firstPage: { enabled: () => canPrevious, run: () => setOffset(0) },
|
||||
previousPage: { enabled: () => canPrevious, run: () => setOffset(Math.max(0, offset - limit)) },
|
||||
nextPage: { enabled: () => canNext, run: () => setOffset(offset + limit) },
|
||||
addRow: { enabled: () => editable, run: addRow },
|
||||
exportData: {
|
||||
enabled: () => !!page,
|
||||
run: () => {
|
||||
const r = viewRef.current?.querySelector("[data-db-export]")?.getBoundingClientRect();
|
||||
if (r) showExport({ x: r.left, y: r.bottom });
|
||||
},
|
||||
},
|
||||
deleteRows: { enabled: (rows) => editable && rows.length > 0, run: deleteRows },
|
||||
restoreRows: { enabled: (rows) => editable && rows.some((r) => edits.deletes.has(r)), run: restoreRows },
|
||||
};
|
||||
useEffect(() => registerTableEditor(viewRef.current!, handle), [handle]);
|
||||
useEffect(() => tableEditorChanged(handle), [handle, dirty, editable]);
|
||||
const orderInvalid = orderDraft !== null && !parseOrderBy(orderDraft, names);
|
||||
return (
|
||||
<div className={styles.view} ref={viewRef} data-db-table-editor="">
|
||||
<div className={styles.toolbar}>
|
||||
<IconButton icon="refresh" title="Reload Page" onClick={reload} disabled={loading} />
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
title="Reload Page"
|
||||
shortcut={shortcutLabel("db.reloadPage")}
|
||||
onClick={reload}
|
||||
disabled={loading}
|
||||
/>
|
||||
<div className={styles.pager}>
|
||||
<IconButton
|
||||
icon="chevron-left"
|
||||
title="Previous Page"
|
||||
disabled={offset === 0 || loading}
|
||||
shortcut={shortcutLabel("db.previousPage")}
|
||||
disabled={!canPrevious}
|
||||
onClick={() => setOffset(Math.max(0, offset - limit))}
|
||||
/>
|
||||
<span>
|
||||
@@ -236,7 +279,8 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
<IconButton
|
||||
icon="chevron-right"
|
||||
title="Next Page"
|
||||
disabled={!page?.result.hasMore || loading}
|
||||
shortcut={shortcutLabel("db.nextPage")}
|
||||
disabled={!canNext}
|
||||
onClick={() => setOffset(offset + limit)}
|
||||
/>
|
||||
<Select
|
||||
@@ -251,11 +295,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
</div>
|
||||
{editable && (
|
||||
<>
|
||||
<IconButton
|
||||
icon="plus"
|
||||
title="Add Row"
|
||||
onClick={() => setEdits((e) => ({ ...e, inserts: [...e.inserts, new Map()] }))}
|
||||
/>
|
||||
<IconButton icon="plus" title="Add Row" shortcut={shortcutLabel("db.addRow")} onClick={addRow} />
|
||||
<Button
|
||||
size="small"
|
||||
variant="primary"
|
||||
@@ -281,23 +321,10 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
<IconButton
|
||||
icon="export"
|
||||
title="Export Data"
|
||||
shortcut={shortcutLabel("db.exportData")}
|
||||
data-db-export=""
|
||||
disabled={!page}
|
||||
onClick={(e) =>
|
||||
page &&
|
||||
showContextMenu(
|
||||
e,
|
||||
exportMenu(
|
||||
{
|
||||
columns: gridColumns,
|
||||
rows: page.result.rows,
|
||||
table: ref.table,
|
||||
driver: sourceById(ref.id)?.driver ?? "sqlite",
|
||||
},
|
||||
`${ref.schema}.${ref.table}`,
|
||||
extractor,
|
||||
),
|
||||
)
|
||||
}
|
||||
onClick={(e) => showExport({ x: e.clientX, y: e.clientY })}
|
||||
/>
|
||||
<IconButton
|
||||
icon="import"
|
||||
@@ -396,12 +423,8 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
rowMenu={(rows) =>
|
||||
editable
|
||||
? [
|
||||
{ label: "Delete Rows", icon: "trash", run: () => deleteRows(rows) },
|
||||
{
|
||||
label: "Restore Rows",
|
||||
run: () =>
|
||||
setEdits((e) => ({ ...e, deletes: new Set([...e.deletes].filter((d) => !rows.includes(d))) })),
|
||||
},
|
||||
{ kind: "action", action: "db.deleteRows", icon: "trash", arg: { rows, editor: handle } },
|
||||
{ kind: "action", action: "db.restoreRows", arg: { rows, editor: handle } },
|
||||
]
|
||||
: []
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { registerActions, type ActionContext } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
|
||||
export type CellCopy = "tsv" | "csv" | "onerow" | "header" | "rowsTsv" | "rowsCsv";
|
||||
|
||||
export interface CellActions {
|
||||
canToggle(): boolean;
|
||||
canSetNull(): boolean;
|
||||
@@ -11,11 +13,31 @@ export interface CellActions {
|
||||
setDefault(): void;
|
||||
/** Opens the local filter of the selected cell's column. */
|
||||
filter(): void;
|
||||
canEditCell(): boolean;
|
||||
editCell(): void;
|
||||
hasSelection(): boolean;
|
||||
copy(kind: CellCopy): void;
|
||||
/** Rows of the selection, top to bottom. */
|
||||
selectedRows(): number[];
|
||||
}
|
||||
|
||||
const grids = new WeakMap<Element, CellActions>();
|
||||
let active: CellActions | null = null;
|
||||
|
||||
/** The focused grid (not while a text field in it has focus). */
|
||||
export function activeCellGrid(): CellActions | null {
|
||||
return active;
|
||||
}
|
||||
|
||||
const COPIES: Array<[CellCopy, string, string]> = [
|
||||
["tsv", "db.copyAsTsv", "Copy as TSV"],
|
||||
["csv", "db.copyAsCsv", "Copy as CSV"],
|
||||
["onerow", "db.copyAsOneRow", "Copy as One-Row"],
|
||||
["header", "db.copyWithHeader", "Copy with Header"],
|
||||
["rowsTsv", "db.copyRowsAsTsv", "Copy Rows as TSV"],
|
||||
["rowsCsv", "db.copyRowsAsCsv", "Copy Rows as CSV"],
|
||||
];
|
||||
|
||||
export function registerCellGrid(root: Element, actions: CellActions): () => void {
|
||||
grids.set(root, actions);
|
||||
return () => {
|
||||
@@ -70,6 +92,22 @@ export function installCellActions(): () => void {
|
||||
enabled: (c) => handle(c)?.canFilter() ?? false,
|
||||
run: (c) => handle(c)?.filter(),
|
||||
},
|
||||
{
|
||||
id: "db.editCell",
|
||||
title: "Edit Cell",
|
||||
category: "Database",
|
||||
keyWhen: "dbCellGridFocus",
|
||||
enabled: (c) => handle(c)?.canEditCell() ?? false,
|
||||
run: (c) => handle(c)?.editCell(),
|
||||
},
|
||||
...COPIES.map(([kind, id, title]) => ({
|
||||
id,
|
||||
title,
|
||||
category: "Database",
|
||||
keyWhen: "dbCellGridFocus",
|
||||
enabled: (c: ActionContext) => handle(c)?.hasSelection() ?? false,
|
||||
run: (c: ActionContext) => handle(c)?.copy(kind),
|
||||
})),
|
||||
]);
|
||||
return () => {
|
||||
dispose();
|
||||
|
||||
@@ -8,8 +8,15 @@ import { lazyComponent, lazyWhen, type MenuItem } from "@/ui";
|
||||
import { activeEditor, lazyEditorExtension, registerEditorContribution } from "@/editor/api";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
|
||||
import { registerActions, type ActionContext } from "@/platform/actions";
|
||||
import { activeCellGrid } from "./cellActions";
|
||||
import {
|
||||
activeTableEditor,
|
||||
focusedTableEditor,
|
||||
installTableEditorFocus,
|
||||
type TableCommand,
|
||||
type TableCommandTarget,
|
||||
} from "./tableEditorFocus";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
registerEditorKind,
|
||||
@@ -53,6 +60,25 @@ function useDatabaseHeaderMenu(): MenuItem[] {
|
||||
|
||||
const useDialogOpen = () => useDatabase((s) => !!s.dialog);
|
||||
|
||||
/** Table editor / result grid commands as actions (IDEA's data editor actions). */
|
||||
const TABLE_COMMANDS: Array<[TableCommand, string, string, string[]]> = [
|
||||
["reload", "db.reloadPage", "Reload Page", ["refresh", "rerun"]],
|
||||
["firstPage", "db.firstPage", "First Page", ["pagination"]],
|
||||
["previousPage", "db.previousPage", "Previous Page", ["pagination"]],
|
||||
["nextPage", "db.nextPage", "Next Page", ["pagination"]],
|
||||
["lastPage", "db.lastPage", "Last Page", ["pagination"]],
|
||||
["addRow", "db.addRow", "Add Row", ["insert row", "new row"]],
|
||||
["exportData", "db.exportData", "Export Data", ["export", "save as"]],
|
||||
["deleteRows", "db.deleteRows", "Delete Rows", ["remove rows"]],
|
||||
["restoreRows", "db.restoreRows", "Restore Rows", ["undelete rows"]],
|
||||
];
|
||||
|
||||
/** The editor and rows a menu passed (focus has moved to the menu), else the focused grid's. */
|
||||
function tableTarget(arg: unknown): TableCommandTarget {
|
||||
if (arg && typeof arg === "object" && "rows" in arg) return arg as TableCommandTarget;
|
||||
return { rows: activeCellGrid()?.selectedRows() ?? [], editor: null };
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
onIdeEvent("dbSourcesChanged", () => {
|
||||
@@ -280,6 +306,23 @@ export function activate(): () => void {
|
||||
when: "dbTableEditorFocus && dbTableEditorChanges",
|
||||
run: () => activeTableEditor()?.revert(),
|
||||
},
|
||||
...TABLE_COMMANDS.map(([command, id, title, keywords]) => ({
|
||||
id,
|
||||
title,
|
||||
category: "Tools",
|
||||
keywords: ["table editor", "data editor", ...keywords],
|
||||
keyWhen: "dbTableEditorFocus",
|
||||
enabled: ({ arg }: ActionContext) => {
|
||||
const { rows, editor } = tableTarget(arg);
|
||||
const handler = (editor ?? focusedTableEditor())?.commands?.[command];
|
||||
return !!handler && handler.enabled(rows);
|
||||
},
|
||||
run: ({ arg }: ActionContext) => {
|
||||
const { rows, editor } = tableTarget(arg);
|
||||
const handler = (editor ?? activeTableEditor())?.commands?.[command];
|
||||
if (handler?.enabled(rows)) handler.run(rows);
|
||||
},
|
||||
})),
|
||||
{
|
||||
id: "db.explainPlan",
|
||||
title: "Explain Plan",
|
||||
|
||||
@@ -2,7 +2,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DbDriver, DbTablePage } from "@/platform/ipc";
|
||||
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import { installCellActions } from "./cellActions";
|
||||
import { activeCellGrid, installCellActions } from "./cellActions";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { TableEditor } from "./TableEditor";
|
||||
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
|
||||
@@ -128,6 +128,38 @@ describe("table editor capabilities", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("runs the row and toolbar commands of the db.* actions on the focused grid's selection (#3506)", async () => {
|
||||
backend.driver = "postgres";
|
||||
const uninstallFocus = installTableEditorFocus();
|
||||
const uninstallCells = installCellActions();
|
||||
try {
|
||||
await act(async () => {
|
||||
render(<TableEditor input={tableInput("source", "public", "users")} />);
|
||||
});
|
||||
const cell = await screen.findByRole("gridcell", { name: "Ann" });
|
||||
fireEvent.mouseDown(cell, { button: 0 });
|
||||
act(() => screen.getByRole("grid").focus());
|
||||
const rows = activeCellGrid()!.selectedRows();
|
||||
expect(rows).toEqual([0]);
|
||||
const commands = activeTableEditor()!.commands!;
|
||||
expect(commands.nextPage!.enabled(rows)).toBe(false);
|
||||
expect(commands.previousPage!.enabled(rows)).toBe(false);
|
||||
expect(commands.exportData!.enabled(rows)).toBe(true);
|
||||
expect(commands.restoreRows!.enabled(rows)).toBe(false);
|
||||
act(() => commands.deleteRows!.run(rows));
|
||||
expect(getContext().dbTableEditorChanges).toBe(true);
|
||||
expect(activeTableEditor()!.commands!.restoreRows!.enabled(rows)).toBe(true);
|
||||
act(() => activeTableEditor()!.commands!.restoreRows!.run(rows));
|
||||
expect(getContext().dbTableEditorChanges).toBe(false);
|
||||
act(() => activeTableEditor()!.commands!.addRow!.run([]));
|
||||
expect(screen.getAllByRole("row").length).toBeGreaterThan(2);
|
||||
expect(getContext().dbTableEditorChanges).toBe(true);
|
||||
} finally {
|
||||
uninstallCells();
|
||||
uninstallFocus();
|
||||
}
|
||||
});
|
||||
|
||||
it("counts the editor-area host focusing the tab as table-editor focus (#2307)", async () => {
|
||||
backend.driver = "postgres";
|
||||
const uninstall = installTableEditorFocus();
|
||||
|
||||
@@ -6,11 +6,37 @@
|
||||
import { flushSync } from "react-dom";
|
||||
import { setContext } from "@/platform/context";
|
||||
|
||||
/** Toolbar and row commands of a table editor or result grid, run as `db.*` actions. */
|
||||
export type TableCommand =
|
||||
| "reload"
|
||||
| "firstPage"
|
||||
| "previousPage"
|
||||
| "nextPage"
|
||||
| "lastPage"
|
||||
| "addRow"
|
||||
| "exportData"
|
||||
| "deleteRows"
|
||||
| "restoreRows";
|
||||
|
||||
export interface TableCommandHandler {
|
||||
enabled(rows: number[]): boolean;
|
||||
/** `rows`: the grid's selected rows (row commands). */
|
||||
run(rows: number[]): void;
|
||||
}
|
||||
|
||||
/** What a row menu passes to a `db.*` row action: the menu holds focus, not the grid. */
|
||||
export interface TableCommandTarget {
|
||||
rows: number[];
|
||||
editor: TableEditorHandle | null;
|
||||
}
|
||||
|
||||
export interface TableEditorHandle {
|
||||
dirty: boolean;
|
||||
submit(): void;
|
||||
revert(): void;
|
||||
showColumns(): void;
|
||||
/** The commands this view has; one it lacks is disabled. */
|
||||
commands?: Partial<Record<TableCommand, TableCommandHandler>>;
|
||||
}
|
||||
|
||||
const handles = new WeakMap<Element, TableEditorHandle>();
|
||||
@@ -55,6 +81,11 @@ export function tableEditorChanged(handle: TableEditorHandle) {
|
||||
if (active === handle) update();
|
||||
}
|
||||
|
||||
/** The active editor as is, for enablement checks (no side effects). */
|
||||
export function focusedTableEditor(): TableEditorHandle | null {
|
||||
return active;
|
||||
}
|
||||
|
||||
/** The active editor, after confirming the cell being edited so its value counts. */
|
||||
export function activeTableEditor(): TableEditorHandle | null {
|
||||
const el = document.activeElement;
|
||||
|
||||
@@ -55,6 +55,8 @@ export const eclipseMacos: Record<string, string[]> = {
|
||||
"code.expandToLevel5": [],
|
||||
"refactor.extractMethod": ["Meta+Alt+M"],
|
||||
"navigate.fileStructure": ["Meta+O"],
|
||||
// ⌘R runs to the cursor: no Reload Page default on it.
|
||||
"db.reloadPage": [],
|
||||
"db.goToColumn": ["Meta+O"],
|
||||
"find.inFile": [],
|
||||
"find.inPath": ["Ctrl+H"],
|
||||
|
||||
@@ -57,6 +57,9 @@ export const eclipseWindows: Record<string, string[]> = {
|
||||
"code.expandToLevel5": [],
|
||||
"refactor.extractMethod": ["Shift+Alt+M"],
|
||||
"navigate.fileStructure": ["Ctrl+F3", "Ctrl+O"],
|
||||
// Ctrl+F5 steps into, Ctrl+Y redoes: no data editor defaults on them.
|
||||
"db.reloadPage": [],
|
||||
"db.deleteRows": ["Alt+Delete"],
|
||||
"db.goToColumn": ["Ctrl+F3", "Ctrl+O"],
|
||||
"find.inFile": [],
|
||||
"find.inPath": ["Ctrl+H"],
|
||||
|
||||
@@ -374,6 +374,17 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"db.goToColumn": ["Meta+F12"],
|
||||
"db.submitChanges": ["Meta+Enter"],
|
||||
"db.revertChanges": ["Meta+Alt+Z"],
|
||||
// Data editor (table editor / result grid), IDEA's Console.TableResult.* defaults.
|
||||
"db.reloadPage": ["Meta+R"],
|
||||
"db.firstPage": [],
|
||||
"db.previousPage": ["Meta+Alt+Up"],
|
||||
"db.nextPage": ["Meta+Alt+Down"],
|
||||
"db.lastPage": [],
|
||||
"db.addRow": ["Meta+N"],
|
||||
"db.deleteRows": [],
|
||||
"db.restoreRows": [],
|
||||
"db.exportData": [],
|
||||
"db.editCell": [],
|
||||
"db.showToolWindow": [],
|
||||
"agents.newTask": ["Meta+Shift+I"],
|
||||
"agents.focusInput": ["Meta+L"],
|
||||
|
||||
@@ -372,6 +372,17 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"db.goToColumn": ["Ctrl+F12"],
|
||||
"db.submitChanges": ["Ctrl+Enter"],
|
||||
"db.revertChanges": ["Ctrl+Alt+Z"],
|
||||
// Data editor (table editor / result grid), IDEA's Console.TableResult.* defaults.
|
||||
"db.reloadPage": ["Ctrl+F5"],
|
||||
"db.firstPage": [],
|
||||
"db.previousPage": ["Ctrl+Alt+Up"],
|
||||
"db.nextPage": ["Ctrl+Alt+Down"],
|
||||
"db.lastPage": [],
|
||||
"db.addRow": ["Alt+Insert"],
|
||||
"db.deleteRows": ["Ctrl+Y", "Alt+Delete"],
|
||||
"db.restoreRows": [],
|
||||
"db.exportData": [],
|
||||
"db.editCell": [],
|
||||
"db.showToolWindow": [],
|
||||
"agents.newTask": ["Ctrl+Alt+Shift+I"],
|
||||
"agents.focusInput": ["Ctrl+L"],
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"Copy as TSV": "Copy as TSV",
|
||||
"Copy as CSV": "Copy as CSV",
|
||||
"Copy as One-Row": "Copy as One-Row",
|
||||
"Show Diff in External Tool": "Show Diff in External Tool",
|
||||
"Show Diff for Lines": "Show Diff for Lines",
|
||||
"External Diff Tools": "External Diff Tools",
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"Copy as TSV": "复制为 TSV",
|
||||
"Copy as CSV": "复制为 CSV",
|
||||
"Copy as One-Row": "复制为单行",
|
||||
"Show Diff in External Tool": "在外部工具中显示差异",
|
||||
"Show Diff for Lines": "显示行差异",
|
||||
"External Diff Tools": "外部差异工具",
|
||||
|
||||
Reference in new issue
Block a user