feat(database): preview the console's execution range with a border (#5694)

A console now borders the SQL an Execute would submit: the caret's statement, or the selected statements, using the same db_statements split the run makes, so what is shown and what is submitted cannot differ. While a run is in progress its submitted range stays bordered as the caret moves. The selection is never changed.

The border is one box around each statement's text, drawn on an editor layer, in the accent colour with a soft fill (light and dark themes). Typing waits for a 150 ms pause before splitting again; caret moves update at once.

Closes #5524

Co-authored-by: Inf1mum <[email protected]>
Цей коміт міститься в:
Vadim LazukтаInf1mum authored and GitHub committed 2026-11-25 06:32:30 +08:00
1 джерело fedd5ffd4f
коміт 5567aff80a
3 files changed
+374

No files matched your search

+7
Переглянути файл
@@ -752,6 +752,13 @@
:global(.cm-openidea-db-executing) {
background: var(--accent-soft);
}
/* The range the console's next run would submit (DataGrip's current-statement border). */
:global(.cm-openidea-db-preview) {
box-sizing: border-box;
background: color-mix(in srgb, var(--accent) 8%, transparent);
border: 1px solid var(--accent);
border-radius: 3px;
}
:global(.cm-openidea-db-elapsed) {
font-variant-numeric: tabular-nums;
}
+138
Переглянути файл
@@ -19,6 +19,7 @@ import {
} from "@codemirror/autocomplete";
import {
Compartment,
EditorSelection,
EditorState,
Facet,
Prec,
@@ -32,9 +33,11 @@ import {
Decoration,
EditorView,
GutterMarker,
RectangleMarker,
ViewPlugin,
WidgetType,
gutter,
layer,
showPanel,
showTooltip,
type Panel,
@@ -375,6 +378,138 @@ export async function explainInView(view: EditorView, path: string) {
const consolePath = Facet.define<string, string>({ combine: (v) => v[0] ?? "" });
const setPreview = StateEffect.define<readonly { from: number; to: number }[]>();
/**
* The range the console's next Execute would submit, bordered on the text (DataGrip's current
* statement border): the caret's statement, or the selection's — the statements `db_statements`
* splits that range into, the very call the run itself makes.
*/
const previewField = StateField.define<readonly { from: number; to: number }[]>({
create: () => [],
update(value, tr) {
for (const e of tr.effects) if (e.is(setPreview)) return e.value;
if (!tr.docChanged) return value;
// The preview is of the text it was computed for; edits only move where that is.
const next: { from: number; to: number }[] = [];
for (const r of value) {
const from = tr.changes.mapPos(r.from, 1);
const to = tr.changes.mapPos(r.to, -1);
if (from < to) next.push({ from, to });
}
return next;
},
});
/** The bordered ranges: a run in progress keeps its submitted range, whatever the caret does. */
export function previewRanges(state: EditorState): readonly { from: number; to: number }[] {
const ex = state.field(runField, false)?.executing;
const ranges = ex?.spans.length
? [{ from: ex.spans[0]!.from, to: ex.spans[ex.spans.length - 1]!.to }]
: (state.field(previewField, false) ?? []);
return ranges.filter((r) => r.from < r.to);
}
const PREVIEW_CLASS = "cm-openidea-db-preview";
/**
* One box around each statement's text: the union of its lines' text (indentation and trailing
* blanks left out), as tall as the statement even where it runs out of view.
*/
function previewBoxes(view: EditorView): RectangleMarker[] {
const { doc } = view.state;
const boxes: RectangleMarker[] = [];
for (const r of previewRanges(view.state)) {
let left = Infinity;
let right = -Infinity;
let offset: number | null = null;
for (const visible of view.visibleRanges) {
const from = Math.max(r.from, visible.from);
const to = Math.min(r.to, visible.to);
if (from >= to) continue;
for (let pos = from; pos <= to;) {
const line = doc.lineAt(pos);
const text = line.text;
let start = Math.max(from, line.from) - line.from;
let end = Math.min(to, line.to) - line.from;
while (start < end && /\s/.test(text[start]!)) start++;
while (end > start && /\s/.test(text[end - 1]!)) end--;
if (start < end)
for (const m of RectangleMarker.forRange(
view,
PREVIEW_CLASS,
EditorSelection.range(line.from + start, line.from + end),
)) {
left = Math.min(left, m.left);
right = Math.max(right, m.left + (m.width ?? 0));
offset ??= m.top - view.lineBlockAt(line.from).top;
}
pos = line.to + 1;
}
}
if (offset == null || right <= left) continue;
const top = view.lineBlockAt(r.from).top + offset;
const bottom = view.lineBlockAt(r.to).bottom + offset;
boxes.push(new RectangleMarker(PREVIEW_CLASS, left - 2, top, right - left + 4, bottom - top));
}
return boxes;
}
const previewLayer = layer({
above: false,
markers: previewBoxes,
update: (u) =>
u.docChanged ||
u.viewportChanged ||
u.geometryChanged ||
u.startState.field(previewField, false) !== u.state.field(previewField, false) ||
u.startState.field(runField, false)?.executing !== u.state.field(runField, false)?.executing,
});
/** How long typing pauses before the preview is split again (until then it follows the edit). */
const PREVIEW_TYPING_DELAY_MS = 150;
/** Re-splits the caret's (or the selection's) range for the preview, as `executeConsole` does. */
const previewSync = ViewPlugin.define((view) => {
const path = view.state.facet(consolePath);
let run = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const preview = () => {
clearTimeout(timer);
timer = undefined;
const id = consoleSource(path);
if (!id) return;
const sent = view.state.doc;
const sel = view.state.selection.main;
const token = ++run;
void call(commands.dbStatements(id, sent.toString(), sel.from, sel.to))
.then((statements) => {
// A newer move, an edit or a run started since: what came back no longer applies.
if (token !== run || view.state.doc !== sent || view.state.field(runField, false)?.executing) return;
view.dispatch({ effects: setPreview.of(statements.map((st) => ({ from: st.from, to: st.to }))) });
})
.catch(() => {});
};
preview();
return {
update(u) {
const executing = (s: EditorState) => !!s.field(runField, false)?.executing;
if (executing(u.startState) && !executing(u.state)) preview();
// While a run is in progress its submitted range stays; the caret is not followed.
else if (executing(u.state)) return;
// Typing sends the whole text each time: wait for a pause, the mapped preview meanwhile.
else if (u.docChanged) {
clearTimeout(timer);
timer = setTimeout(preview, PREVIEW_TYPING_DELAY_MS);
} else if (u.selectionSet) preview();
},
destroy() {
clearTimeout(timer);
run++;
},
};
});
/** An in-editor result and the statement it shows under (mapped through edits). */
interface InlineAnchor {
id: number;
@@ -1207,6 +1342,9 @@ export function consoleExtension(ctx: EditorDocContext): Extension {
consolePath.of(ctx.path),
runField,
runGutter,
previewField,
previewLayer,
previewSync,
inlineField,
syncInline,
showPanel.of(consolePanel(ctx.path)),
+229
Переглянути файл
@@ -0,0 +1,229 @@
import { act } from "@testing-library/react";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import { consoleExtension, executeInView, previewRanges } from "./console";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { streamExecution } from "./executeStream.fixture";
import { useDatabase } from "./store";
import { provideToolWindowService } from "@/workbench/contributions";
const backend = vi.hoisted(() => ({ execute: vi.fn(), stream: vi.fn(), statements: vi.fn() }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/platform/ipc")>();
return {
...actual,
commands: {
...actual.commands,
dbExecute: backend.execute,
dbExecuteStream: backend.stream,
dbStatements: backend.statements,
},
};
});
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = (_event: unknown) => {};
},
}));
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
getTotalSize: () => count * 24,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })),
scrollToIndex: () => {},
}),
}));
const PATH = "/p/console.sql";
const initial = useDatabase.getState();
/** The same split as the console's backend: a selection's statements, else the one at the caret. */
function statements(text: string, from: number, to: number) {
let at = from < to ? from : 0;
const sql = from < to ? text.slice(from, to) : text;
const all = sql.split(";").flatMap((part) => {
const start = at + part.length - part.trimStart().length;
at += part.length + 1;
const st = part.trim();
return st ? [{ from: start, to: start + st.length, text: st }] : [];
});
return from === to ? all.filter((s) => s.from <= from && from <= s.to + 1) : all;
}
beforeEach(() => {
backend.stream.mockReset().mockImplementation(streamExecution(backend.execute));
provideToolWindowService({ show: () => {} } as never);
useProject.setState({
project: { name: "p", root: "/p", trusted: true } as never,
settings: {} as never,
});
useDatabase.setState({
...initial,
loaded: true,
sources: [{ id: "pg", name: "Local", driver: "postgres", readOnly: false }],
completion: { pg: { defaultSchema: "public", tables: [], foreignKeys: [] } },
consoles: { [PATH]: "pg" },
results: [],
inline: [],
});
backend.statements.mockImplementation((_id: unknown, text: string, from: number, to: number) =>
Promise.resolve({ status: "ok", data: statements(text, from, to) }),
);
backend.execute.mockImplementation((_r: unknown, _id: unknown, submitted: Array<{ text: string }>) =>
Promise.resolve({
status: "ok",
data: submitted.map((st) => ({
statement: st,
error: null,
result: {
statement: st.text,
columns: [],
rows: [],
affected: null,
hasMore: false,
elapsedMs: 1,
executionMs: 1,
truncated: [],
},
})),
}),
);
});
afterEach(() => {
document.body.innerHTML = "";
});
function makeView(doc: string, anchor: number, head = anchor) {
const parent = document.body.appendChild(document.createElement("div"));
const view = new EditorView({
parent,
state: EditorState.create({
doc,
selection: { anchor, head },
extensions: consoleExtension({ language: SQL_LANGUAGE, path: PATH } as never),
}),
});
return view;
}
/** The text each execution-range box surrounds (jsdom has no layout to draw the boxes in). */
const bordered = (view: EditorView) => previewRanges(view.state).map((r) => view.state.sliceDoc(r.from, r.to));
describe("the execution range preview", () => {
it("borders the statement the caret is in, asking the splitter the run asks", async () => {
const doc = "SELECT 1;\nSELECT 2;\nSELECT 3;";
const view = makeView(doc, 13); // Inside the second statement.
try {
await act(async () => {});
expect(bordered(view)).toEqual(["SELECT 2"]);
// The same splitting request an Execute with this caret would make.
expect(backend.statements).toHaveBeenCalledWith("pg", doc, 13, 13);
} finally {
view.destroy();
}
});
it("borders the selected statements instead, leaving the selection alone", async () => {
const doc = "SELECT 1;\nSELECT 2;\nSELECT 3;";
const view = makeView(doc, 0);
try {
view.dispatch({ selection: { anchor: 0, head: 19 } }); // The first two statements.
await act(async () => {});
expect(bordered(view)).toEqual(["SELECT 1", "SELECT 2"]);
// The preview never touched the selection.
expect([view.state.selection.main.from, view.state.selection.main.to]).toEqual([0, 19]);
// Back to the caret of the third statement.
view.dispatch({ selection: { anchor: 25 } });
await act(async () => {});
expect(bordered(view)).toEqual(["SELECT 3"]);
expect(view.state.selection.main.head).toBe(25);
} finally {
view.destroy();
}
});
it("keeps the submitted range bordered while a run is in progress, then follows the caret again", async () => {
const doc = "SELECT 1;\nSELECT 2;\nSELECT 3;";
const view = makeView(doc, 13); // Executing the second statement.
let finish!: () => void;
const gate = new Promise<void>((resolve) => (finish = resolve));
const execute = backend.execute.getMockImplementation()!;
backend.execute.mockImplementationOnce(async (...args: unknown[]) => {
await gate;
return execute(...(args as Parameters<typeof execute>));
});
let pending!: Promise<void>;
try {
await act(async () => {
pending = executeInView(view, PATH);
await vi.waitFor(() => expect(view.dom.querySelector(".cm-openidea-db-executing")).not.toBeNull());
});
expect(bordered(view)).toEqual(["SELECT 2"]);
// Moving the caret during the run does not move the submitted range.
const asked = backend.statements.mock.calls.length;
act(() => view.dispatch({ selection: { anchor: 25 } }));
await act(async () => {});
expect(bordered(view)).toEqual(["SELECT 2"]);
expect(backend.statements.mock.calls.length).toBe(asked);
await act(async () => {
finish();
await pending;
});
await act(async () => {});
expect(bordered(view)).toEqual(["SELECT 3"]);
} finally {
finish();
if (pending)
await act(async () => {
await pending;
});
view.destroy();
}
});
it("waits for a pause in typing before splitting again, following the edit meanwhile", async () => {
vi.useFakeTimers();
const view = makeView("SELECT 1;\nSELECT 2;", 18); // After "SELECT 2".
try {
await act(async () => {});
expect(bordered(view)).toEqual(["SELECT 2"]);
const asked = backend.statements.mock.calls.length;
for (const ch of "0, 3") act(() => view.dispatch(view.state.replaceSelection(ch)));
await act(async () => {});
// No request per keystroke; the border is the old one, mapped through the edits.
expect(backend.statements.mock.calls.length).toBe(asked);
expect(bordered(view)).toEqual(["SELECT 2"]);
await act(async () => {
await vi.advanceTimersByTimeAsync(200);
});
expect(backend.statements.mock.calls.length).toBe(asked + 1);
expect(bordered(view)).toEqual(["SELECT 20, 3"]);
} finally {
view.destroy();
vi.useRealTimers();
}
});
it("borders nothing where no statement would be submitted", async () => {
const view = makeView("SELECT 1;\n", 10); // After the last statement.
try {
await act(async () => {});
expect(bordered(view)).toEqual([]);
// And the preview comes back once the caret is on a statement again.
view.dispatch({ selection: { anchor: 3 } });
await act(async () => {});
expect(bordered(view)).toEqual(["SELECT 1"]);
} finally {
view.destroy();
}
});
});