Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 9b4358f046 fix(database): show a running SQL statement in the editor and results
The console only tracked the running request for Run and Cancel; statement
marks and result tabs arrived after the request ended, and the Results view
said "No results" in the meantime. While a request runs, the submitted
statements are now highlighted with a spinner in the gutter and a ticking
elapsed time, and the Results view opens with an executing bar above the
previous result. Edits made meanwhile move the marks, and the outcomes land
on their statements. Cancel or an error clears the indication and keeps the
previous result and marks.

Fixes #4565
2026-11-20 04:05:59 +08:00
12 змінених файлів з 368 додано та 17 видалено

No files matched your search

+28
Переглянути файл
@@ -154,6 +154,28 @@
flex: 1;
min-height: 0;
}
/* A console's request in flight; the previous result stays below it. */
.executing {
flex: none;
display: flex;
align-items: center;
gap: var(--space-2);
min-width: 0;
padding: var(--space-1) var(--space-3);
border-bottom: 1px solid var(--border);
color: var(--fg-muted);
font-size: var(--fs-small);
}
.executingText {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.executingTime {
flex: none;
font-variant-numeric: tabular-nums;
}
/* Gives way before the name does. */
.treeDetail {
color: var(--fg-muted);
@@ -657,6 +679,12 @@
}
/* Console run feedback: timing after a statement, gutter check / error, error banner. */
:global(.cm-openidea-db-executing) {
background: var(--accent-soft);
}
:global(.cm-openidea-db-elapsed) {
font-variant-numeric: tabular-nums;
}
:global(.cm-openidea-db-timing) {
margin-left: 1.5em;
color: var(--fg-muted);
+39 -1
Переглянути файл
@@ -16,6 +16,8 @@ import {
type MouseEvent,
} from "react";
import clsx from "clsx";
import { useShallow } from "zustand/react/shallow";
import { basename } from "@/platform/project";
import { call, commands, type DbPlanNode, type DbQueryResult } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { setContext } from "@/platform/context";
@@ -35,7 +37,7 @@ import {
resolveTarget,
type EditBlockReason,
} from "./resultEditing";
import { pageWindow } from "./resultView";
import { formatElapsed, pageWindow } from "./resultView";
import { resultTabMenu } from "./resultTabActions";
import { analyze } from "./sql/analyze";
import { nameMatcher } from "./sql/dialect";
@@ -55,6 +57,7 @@ import {
rerunResult,
useDatabase,
withConnection,
type ConsoleExecution,
type OutputLine,
type ResultTab,
} from "./store";
@@ -744,8 +747,40 @@ function PinButton({ tab }: { tab: ResultTab }) {
);
}
/** The most recently started console request, while it runs. */
function useLatestExecution(): [string, ConsoleExecution] | undefined {
return useDatabase(
useShallow((s) => {
let latest: [string, ConsoleExecution] | undefined;
for (const entry of Object.entries(s.executions))
if (!latest || entry[1].startedAt > latest[1].startedAt) latest = entry;
return latest;
}),
);
}
function ExecutingBar({ path, execution }: { path: string; execution: ConsoleExecution }) {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 100);
return () => clearInterval(timer);
}, [execution.startedAt]);
const name = basename(path);
const count = execution.statements;
return (
<div className={styles.executing} role="status">
<Spinner size={12} label={tx("Executing")} />
<span className={styles.executingText} title={path}>
{count > 1 ? tx`Executing ${count} statements in ${name}…` : tx`Executing in ${name}…`}
</span>
<span className={styles.executingTime}>{formatElapsed(Math.max(0, now - execution.startedAt))}</span>
</div>
);
}
export function ResultsView() {
const results = useDatabase((s) => s.results);
const execution = useLatestExecution();
const active = useDatabase((s) => s.activeResult);
const hasOutput = useDatabase((s) => s.output.length > 0);
const root = useRef<HTMLDivElement>(null);
@@ -772,6 +807,8 @@ export function ResultsView() {
owner: e.currentTarget,
});
};
const executing = execution && <ExecutingBar path={execution[0]} execution={execution[1]} />;
if (!results.length && !hasOutput && executing) return <div className={styles.view}>{executing}</div>;
if (!results.length && !hasOutput)
return (
<EmptyState title="No results">
@@ -825,6 +862,7 @@ export function ResultsView() {
]}
/>
</ToolWindowContentTabs>
{executing}
<div
ref={panel}
className={styles.fill}
+126 -12
Переглянути файл
@@ -23,6 +23,7 @@ import {
Facet,
Prec,
RangeSet,
type Range,
StateEffect,
StateField,
type Extension,
@@ -42,8 +43,15 @@ import {
import { useEffect, useMemo, useRef, useState, type PointerEvent } from "react";
import { createRoot } from "react-dom/client";
import type { EditorDocContext } from "@/editor/api";
import { iconNode } from "@/ui/iconNode";
import { call, commands, type DbDriver, type DbSessionContext, type DbStatementOutcome } from "@/platform/ipc";
import { iconNode, spinnerNode } from "@/ui/iconNode";
import {
call,
commands,
type DbDriver,
type DbSessionContext,
type DbStatementOutcome,
type SqlStatement,
} from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui";
import { useProject } from "@/platform/project";
@@ -93,6 +101,7 @@ import type { ResultTab } from "./store";
/** `templates` feature's language-data key for finer template contexts. */
const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts";
import { formatElapsed } from "./resultView";
import { SQL_LANGUAGE } from "./sqlLanguage";
export { SQL_LANGUAGE };
const ROW_LIMITS = ["100", "500", "1000", "5000", "50000"];
@@ -107,19 +116,40 @@ interface RunMark {
ms: number | null;
}
/** The statements a running request submitted (a batch: all of them, in order). */
interface Executing {
/** Tells this run from a later one on the same console. */
token: number;
/** The statements' offsets in the text sent. */
sent: readonly { from: number; to: number }[];
/** Where they are now. */
spans: readonly { from: number; to: number }[];
/** Where the elapsed time shows: after the last statement's `;`. */
at: number;
startedAt: number;
}
interface RunState {
marks: readonly RunMark[];
/** Message of the bottom error banner (`null`: hidden). */
banner: string | null;
executing: Executing | null;
}
const setRun = StateEffect.define<RunState>();
const runField = StateField.define<RunState>({
create: () => ({ marks: [], banner: null }),
create: () => ({ marks: [], banner: null, executing: null }),
update(value, tr) {
for (const e of tr.effects) if (e.is(setRun)) return e.value;
if (!tr.docChanged) return value;
// The request runs the text it was sent; edits only move where that shows.
const ex = value.executing;
const executing = ex && {
...ex,
spans: ex.spans.map((r) => ({ from: tr.changes.mapPos(r.from, 1), to: tr.changes.mapPos(r.to, -1) })),
at: tr.changes.mapPos(ex.at),
};
// Editing a statement drops its mark.
const marks: RunMark[] = [];
for (const m of value.marks) {
@@ -135,12 +165,18 @@ const runField = StateField.define<RunState>({
timingAt: tr.changes.mapPos(m.timingAt),
});
}
return { ...value, marks };
return { ...value, marks, executing };
},
provide: (f) => [
EditorView.decorations.from(f, (st) => {
const ranges = [];
const ex = st.executing;
for (const r of ex?.spans ?? [])
if (r.from < r.to) ranges.push(Decoration.mark({ class: "cm-openidea-db-executing" }).range(r.from, r.to));
if (ex) ranges.push(Decoration.widget({ widget: new ElapsedWidget(ex.startedAt), side: 1 }).range(ex.at));
for (const m of st.marks) {
// The new run takes the place of a statement's last outcome.
if (ex?.spans.some((r) => r.from <= m.to && m.from <= r.to)) continue;
if (m.error)
ranges.push(
Decoration.mark({ class: "cm-openidea-db-error", attributes: { title: m.error } }).range(m.from, m.to),
@@ -164,11 +200,47 @@ class TimingWidget extends WidgetType {
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing";
span.textContent = this.ms < 1000 ? `${Math.round(this.ms)} ms` : `${(this.ms / 1000).toFixed(1)} s`;
span.textContent = formatElapsed(this.ms);
return span;
}
}
/** The running time of the request, ticking until it ends. */
class ElapsedWidget extends WidgetType {
private timer: ReturnType<typeof setInterval> | undefined;
constructor(readonly startedAt: number) {
super();
}
eq(other: ElapsedWidget) {
return other.startedAt === this.startedAt;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing cm-openidea-db-elapsed";
const tick = () => {
const elapsed = formatElapsed(Date.now() - this.startedAt);
span.textContent = tx`Executing… ${elapsed}`;
};
tick();
this.timer = setInterval(tick, 100);
return span;
}
destroy() {
clearInterval(this.timer);
}
}
class ExecutingMarker extends GutterMarker {
eq(other: GutterMarker) {
return other instanceof ExecutingMarker;
}
toDOM() {
const el = spinnerNode(12, "cm-openidea-db-run-executing");
el.title = tx("Executing");
return el;
}
}
class RunMarker extends GutterMarker {
constructor(readonly error: string | null) {
super();
@@ -192,9 +264,12 @@ const runGutter = gutter({
markers: (view) => {
const st = view.state.field(runField);
const doc = view.state.doc;
const ranges = st.marks
.filter((m) => m.from <= doc.length)
const ex = st.executing;
const ranges: Range<GutterMarker>[] = st.marks
.filter((m) => m.from <= doc.length && !ex?.spans.some((r) => r.from <= m.to && m.from <= r.to))
.map((m) => new RunMarker(m.error).range(doc.lineAt(m.from).from));
const first = ex?.spans[0];
if (first && first.from <= doc.length) ranges.push(new ExecutingMarker().range(doc.lineAt(first.from).from));
return RangeSet.of(ranges, true);
},
});
@@ -233,20 +308,59 @@ export function markOutcomes(view: EditorView, outcomes: readonly DbStatementOut
}));
const failed = outcomes.find((o) => o.error);
const name = failed ? (sourceById(consoleSource(view.state.facet(consolePath)))?.name ?? "") : "";
view.dispatch({ effects: setRun.of({ marks, banner: failed ? `[${name}] ${failed.error}` : null }) });
view.dispatch({
effects: setRun.of({ ...view.state.field(runField), marks, banner: failed ? `[${name}] ${failed.error}` : null }),
});
}
let nextExecution = 0;
/** `outcomes` at where their statements are now, when the text was edited while they ran. */
function placed(
executing: Executing | null,
token: number,
outcomes: readonly DbStatementOutcome[],
): readonly DbStatementOutcome[] {
if (executing?.token !== token) return outcomes;
return outcomes.map((o) => {
const i = executing.sent.findIndex((r) => r.from === o.statement.from && r.to === o.statement.to);
const now = executing.spans[i];
return now ? { ...o, statement: { ...o.statement, from: now.from, to: now.to } } : o;
});
}
/** Runs `from`–`to` of `view`, showing the submitted statements as executing until the request ends. */
async function executeRange(view: EditorView, path: string, from: number, to: number) {
const token = ++nextExecution;
const sent = view.state.doc;
const start = (statements: readonly SqlStatement[]) => {
// The offsets are into the text sent; an edit since (while asking for parameters) leaves them unplaced.
if (view.state.doc !== sent) return;
const spans = statements.map((st) => ({ from: st.from, to: st.to }));
const last = spans.at(-1);
if (!last) return;
const at = view.state.sliceDoc(last.to, last.to + 1) === ";" ? last.to + 1 : last.to;
const executing = { token, sent: spans, spans, at, startedAt: Date.now() };
view.dispatch({ effects: setRun.of({ ...view.state.field(runField), executing }) });
};
try {
const outcomes = await executeConsole(path, sent.toString(), from, to, start);
if (outcomes.length) markOutcomes(view, placed(view.state.field(runField).executing, token, outcomes));
} finally {
const st = view.state.field(runField, false);
if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) });
}
}
/** Runs the statement at the caret (or the selected ones) of `view`. */
export async function executeInView(view: EditorView, path: string) {
const sel = view.state.selection.main;
const outcomes = await executeConsole(path, view.state.doc.toString(), sel.from, sel.to);
if (outcomes.length) markOutcomes(view, outcomes);
await executeRange(view, path, sel.from, sel.to);
}
/** Runs every statement of `view`, in order (stops at the first that fails). */
export async function executeScriptInView(view: EditorView, path: string) {
const outcomes = await executeConsole(path, view.state.doc.toString(), 0, view.state.doc.length);
if (outcomes.length) markOutcomes(view, outcomes);
await executeRange(view, path, 0, view.state.doc.length);
}
/** Explain Plan of the statement at the caret (or the first selected one) of `view`. */
+59 -1
Переглянути файл
@@ -3,9 +3,10 @@ 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 } from "./console";
import { consoleExtension, executeScriptInView } from "./console";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { executeConsole, rerunResult, useDatabase } from "./store";
import { provideToolWindowService } from "@/workbench/contributions";
const backend = vi.hoisted(() => ({ execute: vi.fn(), statements: vi.fn() }));
@@ -30,6 +31,7 @@ const initial = useDatabase.getState();
let runs = 0;
beforeEach(() => {
provideToolWindowService({ show: () => {} } as never);
runs = 0;
useProject.setState({
project: { name: "p", root: "/p", trusted: true } as never,
@@ -134,3 +136,59 @@ describe("In-Editor Results", () => {
view.destroy();
});
});
describe("statements in flight", () => {
it("marks what was submitted with its running time, then the outcome", async () => {
const parent = document.createElement("div");
document.body.append(parent);
const doc = "SELECT 1;\nSELECT 2;\n";
const view = new EditorView({
parent,
state: EditorState.create({
doc,
extensions: consoleExtension({ language: SQL_LANGUAGE, path: PATH } as never),
}),
});
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>));
});
const executing = () => [...view.dom.querySelectorAll(".cm-openidea-db-executing")].map((e) => e.textContent);
const elapsed = () => view.dom.querySelector(".cm-openidea-db-elapsed")?.textContent;
let pending!: Promise<void>;
await act(async () => {
pending = executeScriptInView(view, PATH);
await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled());
});
expect(executing()).toEqual(["SELECT 1", "SELECT 2"]);
expect(elapsed()).toMatch(/^Executing… \d+ ms$/);
expect(view.dom.querySelector(".cm-openidea-db-run-executing")).not.toBeNull();
// Typing above moves the marks with their text.
act(() => view.dispatch({ changes: { from: 0, insert: "-- a longer note above\n" } }));
expect(executing()).toEqual(["SELECT 1", "SELECT 2"]);
await act(async () => {
finish();
await pending;
});
expect(executing()).toEqual([]);
expect(elapsed()).toBeUndefined();
// The outcomes land on the statements, not on where they were when sent.
const lines = [...view.dom.querySelectorAll(".cm-openidea-db-gutter .cm-gutterElement")]
.filter((e) => e.querySelector(".cm-openidea-db-run-ok"))
.map((e) => e.getBoundingClientRect().top);
expect(lines).toHaveLength(2);
expect(view.dom.querySelectorAll(".cm-openidea-db-timing")).toHaveLength(2);
expect(view.state.doc.lineAt(view.posAtDOM(view.dom.querySelector(".cm-openidea-db-timing")!)).text).toBe(
"SELECT 1;",
);
view.destroy();
});
});
+1
Переглянути файл
@@ -157,6 +157,7 @@ export function activate(): () => void {
manualCommit: new Set(),
pendingTx: new Set(),
running: {},
executions: {},
dialog: null,
newMenuOpen: false,
});
+3
Переглянути файл
@@ -67,6 +67,7 @@ import {
useDatabase,
withConnection,
} from "./store";
import { provideToolWindowService } from "@/workbench/contributions";
const initial = useDatabase.getState();
const initialProject = useProject.getState();
@@ -129,6 +130,8 @@ function switchProject(project: ProjectInfo) {
}
beforeEach(() => {
// `showServiceView` reaches the real service, not the mocked accessor above.
provideToolWindowService({ show: ui.show } as never);
vi.resetAllMocks();
useProject.setState({ project: projectA });
savedSources = [pg, other];
+6 -1
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Pure helpers of the result views: IDEA's local filter and client-side sort
* of loaded rows, search in the grid, paging of console results, the
* Aggregates of a selection, and the series of the chart.
* Aggregates of a selection, the series of the chart, and how long a statement took.
*/
import type { Cell } from "./model";
@@ -462,3 +462,8 @@ export function pageWindow({ page, pageSize, rows, hasMore, total }: PageState):
export function pageFetch(page: number, pageSize: number): { maxRows: number; skip: number } {
return { maxRows: pageSize, skip: page * pageSize };
}
/** A statement's run time as IDEA shows it: `840 ms`, `3.2 s`. */
export function formatElapsed(ms: number): string {
return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
}
+63
Переглянути файл
@@ -9,6 +9,7 @@ import { ResultsView } from "./ResultsView";
import { executeConsole, explainConsole, pinResult, rerunResult, useDatabase, type ResultTab } from "./store";
import { registerResultTabActions } from "./resultTabActions";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
import { provideToolWindowService } from "@/workbench/contributions";
const backend = vi.hoisted(() => ({
driver: "postgres" as DbDriver,
@@ -95,6 +96,7 @@ function show(text: string, columns: Array<{ name: string }>, rows: (string | nu
}
beforeEach(() => {
provideToolWindowService({ show: () => {} } as never);
vi.clearAllMocks();
backend.statements.mockImplementation((_id: unknown, text: string) =>
Promise.resolve({ status: "ok", data: [{ from: 0, to: text.length, text }] }),
@@ -809,3 +811,64 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab
expect(useDatabase.getState().activeResult).toBe(fresh);
});
});
describe("a console request in flight", () => {
const hold = () => {
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>));
});
return () => finish();
};
it("shows that it is executing instead of No results on a first run", async () => {
show("SELECT 1", [{ name: "id" }], [["1"]]);
useDatabase.setState({ results: [], activeResult: null, consoles: { "console.sql": "pg" } });
const finish = hold();
await act(async () => render(<ResultsView />));
let pending!: Promise<unknown>;
await act(async () => {
pending = executeConsole("console.sql", "SELECT pg_sleep(5)", 0, 0);
await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled());
});
expect(screen.queryByText("No results")).toBeNull();
expect(screen.getByText("Executing in console.sql…").parentElement).toHaveTextContent(/\d+ ms$/);
await act(async () => {
finish();
await pending;
});
expect(screen.queryByText(/Executing in/)).toBeNull();
expect(useDatabase.getState().executions).toEqual({});
});
it("keeps the previous result visible while the next run executes", async () => {
show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
useDatabase.setState({ consoles: { "console.sql": "pg" } });
backend.statements.mockResolvedValueOnce({
status: "ok",
data: [
{ from: 0, to: 8, text: "SELECT 1" },
{ from: 10, to: 18, text: "SELECT 2" },
],
});
const finish = hold();
await act(async () => render(<ResultsView />));
let pending!: Promise<unknown>;
await act(async () => {
pending = executeConsole("console.sql", "SELECT 1; SELECT 2", 0, 18);
await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled());
});
expect(screen.getByText("Executing 2 statements in console.sql…")).toBeTruthy();
expect(screen.getByText("Ann")).toBeTruthy();
await act(async () => {
finish();
await pending;
});
expect(screen.queryByText(/Executing/)).toBeNull();
});
});
+21 -2
Переглянути файл
@@ -174,6 +174,12 @@ export interface SourceCatalog {
databases: Record<string, DbCatalogSchema[]>;
}
export interface ConsoleExecution {
startedAt: number;
/** Statements submitted (a batch runs them in order; the backend doesn't say which one is current). */
statements: number;
}
interface DatabaseState {
sources: DataSource[];
loaded: boolean;
@@ -205,6 +211,8 @@ interface DatabaseState {
output: OutputLine[];
/** Console path → running request. */
running: Record<string, RequestId>;
/** Console path → what its running request submitted, and since when (ms since the epoch). */
executions: Record<string, ConsoleExecution>;
maxRows: number;
dialog: DialogState | null;
/** Target of the tree's lead node. */
@@ -271,6 +279,7 @@ export const useDatabase = create<DatabaseState>(() => ({
activeResult: null,
output: [],
running: {},
executions: {},
maxRows: 500,
dialog: null,
selectedSource: null,
@@ -1233,6 +1242,8 @@ export async function executeConsole(
text: string,
from: number,
to: number,
/** Called once the statements are submitted, with what was submitted. */
onStart?: (statements: readonly SqlStatement[]) => void,
): Promise<DbStatementOutcome[]> {
const id = consoleSource(path);
if (!id) {
@@ -1252,8 +1263,14 @@ export async function executeConsole(
const prev = useDatabase.getState().running[path];
if (prev) void commands.cancelRequest(prev);
const request = nextRequestId();
useDatabase.setState((s) => ({ running: { ...s.running, [path]: request } }));
useDatabase.setState((s) => ({
running: { ...s.running, [path]: request },
executions: { ...s.executions, [path]: { startedAt: Date.now(), statements: statements.length } },
}));
onStart?.(statements);
try {
// IDEA brings the results up as the run starts, showing it executing.
if (!inEditorResults()) showServiceView(RESULTS_VIEW, false);
const pageSize = useDatabase.getState().maxRows;
const schema = consoleSchema(path) || (await loadCompletion(id))?.defaultSchema || "";
if (!current()) return [];
@@ -1296,7 +1313,9 @@ export async function executeConsole(
if (s.running[path] !== request) return s;
const running = { ...s.running };
delete running[path];
return { running };
const executions = { ...s.executions };
delete executions[path];
return { running, executions };
});
}
}
+4
Переглянути файл
@@ -166,6 +166,10 @@
"Select Next Tab": "Select Next Tab",
"Select Previous Tab": "Select Previous Tab",
"Result {n}-{index}": "Result {n}-{index}",
"Executing": "Executing",
"Executing {count} statements in {name}…": "Executing {count} statements in {name}…",
"Executing in {name}…": "Executing in {name}…",
"Executing… {elapsed}": "Executing… {elapsed}",
"Absolute": "Absolute",
"Relative": "Relative",
"Hybrid": "Hybrid",
+4
Переглянути файл
@@ -4861,6 +4861,10 @@
"Remove data source '{name}'? Its query console file stays on disk.": "是否移除数据源 '{name}'?其查询控制台文件将保留在磁盘上。",
"Result {n}": "结果 {n}",
"Result {n}-{index}": "结果 {n}-{index}",
"Executing": "正在执行",
"Executing {count} statements in {name}…": "正在 {name} 中执行 {count} 条语句…",
"Executing in {name}…": "正在 {name} 中执行…",
"Executing… {elapsed}": "正在执行… {elapsed}",
"{name} has uncommitted changes. Commit or roll them back before switching to auto-commit?": "{name} 有未提交的更改。是否在切换到自动提交前提交或回滚这些更改?",
"Cannot copy the name": "无法复制名称",
"Cannot copy the reference": "无法复制引用",
+14
Переглянути файл
@@ -1,5 +1,6 @@
/** Design-system icons as DOM nodes for CodeMirror widgets. */
import { iconMarkupOrFallback, type IconName } from "./icons";
import spinnerStyles from "./Spinner.module.css";
export function iconNode(name: IconName | (string & {}), size = 16, className?: string): HTMLElement {
const span = document.createElement("span");
@@ -8,3 +9,16 @@ export function iconNode(name: IconName | (string & {}), size = 16, className?:
span.innerHTML = iconMarkupOrFallback(name, size);
return span;
}
/** The ring `Spinner` as a DOM node for CodeMirror widgets and gutters. */
export function spinnerNode(size = 14, className?: string): HTMLElement {
const span = document.createElement("span");
span.className = className ? `cm-openidea-icon ${className}` : "cm-openidea-icon";
span.setAttribute("aria-hidden", "true");
span.innerHTML =
`<svg class="${spinnerStyles.spinner}" width="${size}" height="${size}" viewBox="0 0 24 24">` +
'<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-opacity="0.2" stroke-width="2.4"/>' +
'<path d="M21 12a9 9 0 0 0-9-9" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/>' +
"</svg>";
return span;
}