дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
109a8408bb | ||
|
|
750d35dd6e | ||
|
|
f0273690b9 | ||
|
|
04611c0388 | ||
|
|
1cfc71ae58 |
No files matched your search
@@ -596,3 +596,15 @@ test("dragging the Markdown split divider resizes and reflows editor and preview
|
||||
.poll(async () => Math.round((await reopenedEditor.boundingBox())!.width))
|
||||
.toBe(Math.round(initialEditor));
|
||||
});
|
||||
|
||||
test("Markdown Preview only leaves the Project view clickable", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "README.md");
|
||||
await page.getByRole("button", { name: "Preview Only" }).click();
|
||||
await expect(page.getByRole("document", { name: "Markdown preview" })).toBeVisible();
|
||||
|
||||
const row = page.getByRole("treeitem", { name: "build.gradle.kts", exact: true });
|
||||
// A hidden editor panel used to leave an implicit resize region over everything left of the preview,
|
||||
// which swallowed the click.
|
||||
await row.click();
|
||||
await expect(row).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
+76
-3
@@ -3,15 +3,21 @@
|
||||
* the process. Processes are stubbed at the IPC layer; `crates/ide-run` covers spawning them.
|
||||
*/
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { RunConfig } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const RUN_ID = 7;
|
||||
|
||||
/** One saved `npm run dev` configuration; `run_start` prints `output` and exits with `exit` unless null. */
|
||||
async function stubRun(page: Page, output: { kind: string; text: string }[], exit: number | null) {
|
||||
async function stubRun(
|
||||
page: Page,
|
||||
output: { kind: string; text: string }[],
|
||||
exit: number | null,
|
||||
overrides: Partial<RunConfig> = {},
|
||||
) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ output, exit, runId }) => {
|
||||
async ({ output, exit, runId, overrides }) => {
|
||||
const config = {
|
||||
id: "npm:dev",
|
||||
name: "dev",
|
||||
@@ -23,6 +29,7 @@ async function stubRun(page: Page, output: { kind: string; text: string }[], exi
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
...overrides,
|
||||
};
|
||||
const h = window.__ipc.handlers;
|
||||
h.run_configs = () => [config];
|
||||
@@ -43,7 +50,7 @@ async function stubRun(page: Page, output: { kind: string; text: string }[], exi
|
||||
await loadConfigs();
|
||||
selectConfig(config.id);
|
||||
},
|
||||
{ output, exit, runId: RUN_ID },
|
||||
{ output, exit, runId: RUN_ID, overrides },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -177,6 +184,72 @@ test("Go reruns keep each package's exact failures and the original configuratio
|
||||
]);
|
||||
});
|
||||
|
||||
test("test results keep counts, actions and selected output visible as the pane narrows", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1060, height: 740 });
|
||||
const goPackage = "example.com/checkout";
|
||||
const name = "TestCheckoutTotalsWithDiscountsAndPendingInventoryReservations";
|
||||
const message = "expected subtotal 42, got 37";
|
||||
const records = [
|
||||
{ Action: "run", Test: name },
|
||||
{ Action: "output", Test: name, Output: message + "\n" },
|
||||
{ Action: "fail", Test: name, Elapsed: 0.125 },
|
||||
{ Action: "pass", Test: "TestPayment", Elapsed: 0.02 },
|
||||
{ Action: "skip", Test: "TestDelayedShipping" },
|
||||
{ Action: "fail", Elapsed: 0.17 },
|
||||
];
|
||||
await stubRun(
|
||||
page,
|
||||
records.map((record) => ({ kind: "stdout", text: JSON.stringify({ Package: goPackage, ...record }) + "\n" })),
|
||||
1,
|
||||
{
|
||||
id: "go:checkout-tests",
|
||||
name: "Checkout tests",
|
||||
kind: "go",
|
||||
command: "go",
|
||||
args: ["test", "-json"],
|
||||
isTest: true,
|
||||
},
|
||||
);
|
||||
await page.keyboard.press("Control+r");
|
||||
const run = page.getByRole("region", { name: "Run", exact: true });
|
||||
const tree = run.getByRole("tree", { name: "Test results" });
|
||||
const row = tree.getByRole("treeitem", { name: new RegExp(name) });
|
||||
await row.click();
|
||||
const output = run.getByRole("log");
|
||||
await expect(output).toContainText(message);
|
||||
await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
|
||||
await page.setViewportSize({ width: 540, height: 740 });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const [list, console] = await Promise.all([tree.boundingBox(), output.boundingBox()]);
|
||||
return !!list && !!console && console.y >= list.y + list.height - 1;
|
||||
})
|
||||
.toBe(true);
|
||||
const summary = run.getByRole("status").filter({ hasText: "1 failing" });
|
||||
for (const count of ["1 failing", "1 passed", "1 ignored"]) await expect(summary.getByText(count)).toBeVisible();
|
||||
await expect(row).toHaveAttribute("aria-selected", "true");
|
||||
await expect(row.getByText("125 ms")).toBeVisible();
|
||||
await expect(output).toContainText(message);
|
||||
const toolbar = run.getByRole("toolbar", { name: "Test results" });
|
||||
await toolbar.getByRole("button", { name: "More Actions" }).click();
|
||||
await expect(page.getByRole("menuitem", { name: "Collapse All" })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Export Test Results…" })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
const divider = run.getByRole("separator");
|
||||
const treeHeight = async () => (await tree.boundingBox())!.height;
|
||||
const beforeResize = await treeHeight();
|
||||
await divider.press("ArrowDown");
|
||||
await expect.poll(treeHeight).toBeGreaterThan(beforeResize + 1);
|
||||
const customizedHeight = await treeHeight();
|
||||
await page.setViewportSize({ width: 1060, height: 740 });
|
||||
await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
|
||||
await page.setViewportSize({ width: 540, height: 740 });
|
||||
await expect.poll(async () => Math.abs((await treeHeight()) - customizedHeight)).toBeLessThan(2);
|
||||
await expect(output).toContainText(message);
|
||||
});
|
||||
|
||||
test("CMake builds the selected target in Build before starting only the application in Run", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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`. */
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -157,6 +157,7 @@ export function activate(): () => void {
|
||||
manualCommit: new Set(),
|
||||
pendingTx: new Set(),
|
||||
running: {},
|
||||
executions: {},
|
||||
dialog: null,
|
||||
newMenuOpen: false,
|
||||
});
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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`;
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,26 +253,44 @@
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.testHeader {
|
||||
.testToolbar,
|
||||
.testStatusBar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
height: 28px;
|
||||
padding: 0 4px 0 10px;
|
||||
min-height: 28px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.testToolbar {
|
||||
gap: var(--space-0-5);
|
||||
padding: var(--space-0-5) var(--space-1);
|
||||
}
|
||||
.testStatusBar {
|
||||
gap: var(--space-0-5) var(--space-2);
|
||||
padding: var(--space-0-5) var(--space-2);
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.testCounts {
|
||||
flex: 1 1 auto;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-0-5) var(--space-2);
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.testStatus,
|
||||
.testTotalDuration {
|
||||
flex: none;
|
||||
}
|
||||
.testTotalDuration {
|
||||
margin-left: auto;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.testTree {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
@@ -299,8 +317,11 @@
|
||||
flex: none;
|
||||
padding-right: 8px;
|
||||
color: var(--fg-subtle);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.testTree [aria-selected="true"] .testDuration {
|
||||
color: var(--fg);
|
||||
}
|
||||
.testEmpty {
|
||||
padding: 12px;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { GroupImperativeHandle, Layout } from "react-resizable-panels";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import type { RunTargetValid } from "@/platform/remoteSettings";
|
||||
import { useAgentRunSettings, useWorkflowSettings } from "@/platform/workflowSettings";
|
||||
@@ -47,7 +48,7 @@ import {
|
||||
} from "./store";
|
||||
import { rerunFailedConfigs } from "./testing/rerun";
|
||||
import { formatDuration, nodeOutput } from "./testing";
|
||||
import { TestTreeView } from "./TestTreeView";
|
||||
import { TestStatusBar, TestTreeView } from "./TestTreeView";
|
||||
import { StackTracePanel, useStackTraces, type StackTraceTab } from "./stackTrace";
|
||||
import { closeRunTab, runTabMenu } from "./runTabs";
|
||||
import { showApplicationUpdate, useApplicationUpdates } from "./applicationUpdate";
|
||||
@@ -59,6 +60,11 @@ import { archivedAgentSessions, closeAgentArchive } from "./agentRuns";
|
||||
import styles from "./Run.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
const TEST_SPLIT_DEFAULTS = {
|
||||
horizontal: { tests: 34, console: 66 },
|
||||
vertical: { tests: 48, console: 52 },
|
||||
};
|
||||
|
||||
function failed(s: RunSession): boolean {
|
||||
return s.status === "failed" || (s.status === "finished" && s.exitCode !== 0 && !s.stopped);
|
||||
}
|
||||
@@ -93,6 +99,25 @@ export function SessionPanel({
|
||||
const softWrap = wrapOverride ?? defaultWrap;
|
||||
const [selectedTest, setSelectedTest] = useState<string | null>(null);
|
||||
const [findOpen, setFindOpen] = useState(false);
|
||||
const body = useRef<HTMLDivElement>(null);
|
||||
const [stackedTests, setStackedTests] = useState(false);
|
||||
const testSplit = useRef<GroupImperativeHandle>(null);
|
||||
const testLayouts = useRef<Record<keyof typeof TEST_SPLIT_DEFAULTS, Layout>>({ ...TEST_SPLIT_DEFAULTS });
|
||||
const testOrientation = stackedTests ? "vertical" : "horizontal";
|
||||
const hasTests = !!rt?.tests;
|
||||
useLayoutEffect(() => {
|
||||
const pane = body.current;
|
||||
if (!hasTests || !pane) return;
|
||||
const measure = () => setStackedTests(pane.clientWidth < 560);
|
||||
measure();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const resize = new ResizeObserver(measure);
|
||||
resize.observe(pane);
|
||||
return () => resize.disconnect();
|
||||
}, [hasTests]);
|
||||
useLayoutEffect(() => {
|
||||
if (hasTests) testSplit.current?.setLayout(testLayouts.current[testOrientation]);
|
||||
}, [hasTests, testOrientation]);
|
||||
const running = isLive(session);
|
||||
const cwd = runDirectory(session.config.cwd);
|
||||
const baseConfig = useRun(() => baseConfigOf(session));
|
||||
@@ -136,6 +161,7 @@ export function SessionPanel({
|
||||
|
||||
const consoleColumn = (
|
||||
<div className={styles.consoleColumn}>
|
||||
{rt.tests && <TestStatusBar results={rt.tests} version={version} running={running} />}
|
||||
{rt.console.dropped > 0 && !testModel && (
|
||||
<div className={styles.notice}>{tx`${rt.console.dropped.toLocaleString()} earlier lines were discarded`}</div>
|
||||
)}
|
||||
@@ -279,10 +305,19 @@ export function SessionPanel({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.sessionBody}>
|
||||
<div ref={body} className={styles.sessionBody}>
|
||||
{rt.tests ? (
|
||||
<SplitGroup orientation="horizontal" id={`run-tests-${session.id}`} className={styles.testSplit}>
|
||||
<SplitPanel id="tests" defaultSize="32%" minSize="140px">
|
||||
<SplitGroup
|
||||
orientation={testOrientation}
|
||||
id={`run-tests-${session.id}`}
|
||||
className={styles.testSplit}
|
||||
groupRef={testSplit}
|
||||
defaultLayout={TEST_SPLIT_DEFAULTS[testOrientation]}
|
||||
onLayoutChanged={(layout, meta) => {
|
||||
if (meta.isUserInteraction) testLayouts.current[testOrientation] = meta.requestedLayout ?? layout;
|
||||
}}
|
||||
>
|
||||
<SplitPanel id="tests" minSize={stackedTests ? "28%" : "140px"}>
|
||||
<TestTreeView
|
||||
results={rt.tests}
|
||||
version={version}
|
||||
@@ -296,7 +331,7 @@ export function SessionPanel({
|
||||
/>
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="console" minSize="200px">
|
||||
<SplitPanel id="console" minSize={stackedTests ? "28%" : "200px"}>
|
||||
{consoleColumn}
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
|
||||
@@ -49,6 +49,12 @@ function Host(props: {
|
||||
);
|
||||
}
|
||||
|
||||
function moreItem(name: string) {
|
||||
const trigger = screen.getByRole("button", { name: "More Actions" });
|
||||
if (trigger.getAttribute("aria-expanded") !== "true") fireEvent.click(trigger);
|
||||
return screen.getByRole("menuitem", { name });
|
||||
}
|
||||
|
||||
describe("TestTreeView", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
@@ -264,17 +270,17 @@ describe("Expand All / Collapse All", () => {
|
||||
expect(rows()).toContain("reuses()");
|
||||
});
|
||||
|
||||
it("the buttons run the actions, and are unavailable without suites", () => {
|
||||
it("the menu runs the actions, and they are unavailable without suites", () => {
|
||||
const dispose = registerActions([
|
||||
{ id: "run.expandAllTests", title: "Expand All", run: () => {} },
|
||||
{ id: "run.collapseAllTests", title: "Collapse All", run: () => {} },
|
||||
]);
|
||||
onTestFinished(dispose);
|
||||
const { unmount } = render(view(nested()));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Expand All" }));
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("run.expandAllTests", undefined);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Collapse All" }));
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("run.collapseAllTests", undefined);
|
||||
fireEvent.click(moreItem("Expand All"));
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("run.expandAllTests");
|
||||
fireEvent.click(moreItem("Collapse All"));
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("run.collapseAllTests");
|
||||
unmount();
|
||||
expect(testTree.expandAll).toBeNull();
|
||||
|
||||
@@ -282,8 +288,8 @@ describe("Expand All / Collapse All", () => {
|
||||
flat.apply([{ type: "result", path: ["main_test"], status: "failed" }]);
|
||||
flat.finish(1);
|
||||
render(view(flat));
|
||||
expect(screen.getByRole("button", { name: "Expand All" })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "Collapse All" })).toBeDisabled();
|
||||
expect(moreItem("Expand All")).toHaveAttribute("aria-disabled", "true");
|
||||
expect(moreItem("Collapse All")).toHaveAttribute("aria-disabled", "true");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -306,9 +312,9 @@ describe("Export Test Results", () => {
|
||||
/>
|
||||
);
|
||||
|
||||
it("the button and the action open the dialog for the finished run", () => {
|
||||
it("the menu and the action open the dialog for the finished run", () => {
|
||||
const { unmount } = render(view(finished(), false));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Export Test Results…" }));
|
||||
fireEvent.click(moreItem("Export Test Results…"));
|
||||
expect(screen.getByRole("dialog", { name: "Export Test Results" })).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
act(() => testTree.exportResults!());
|
||||
@@ -322,13 +328,13 @@ describe("Export Test Results", () => {
|
||||
|
||||
it("is unavailable while the tests run and without results", () => {
|
||||
const { rerender } = render(view(finished(), true));
|
||||
expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled();
|
||||
expect(moreItem("Export Test Results…")).toHaveAttribute("aria-disabled", "true");
|
||||
expect(testTree.exportResults).toBeNull();
|
||||
rerender(view(new TestResults(), false));
|
||||
expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled();
|
||||
expect(moreItem("Export Test Results…")).toHaveAttribute("aria-disabled", "true");
|
||||
expect(testTree.exportResults).toBeNull();
|
||||
rerender(view(finished(), false));
|
||||
expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeEnabled();
|
||||
expect(moreItem("Export Test Results…")).not.toHaveAttribute("aria-disabled", "true");
|
||||
expect(testTree.exportResults).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
showContextMenu,
|
||||
useContextMenuStore,
|
||||
Spinner,
|
||||
Toolbar,
|
||||
Tree,
|
||||
type MenuItem,
|
||||
type TreeHandle,
|
||||
@@ -83,6 +84,41 @@ export function StatusIcon({ status }: { status: TestStatus | null }) {
|
||||
}
|
||||
}
|
||||
|
||||
export function TestStatusBar({
|
||||
results,
|
||||
version,
|
||||
running,
|
||||
}: {
|
||||
results: TestResults;
|
||||
version: number;
|
||||
running: boolean;
|
||||
}) {
|
||||
const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const status = running
|
||||
? "running"
|
||||
: counts.failed
|
||||
? "failed"
|
||||
: counts.passed
|
||||
? "passed"
|
||||
: counts.skipped
|
||||
? "skipped"
|
||||
: null;
|
||||
const duration = results.summary.durationMs;
|
||||
|
||||
return (
|
||||
<div className={styles.testStatusBar} role="status">
|
||||
<StatusIcon status={status} />
|
||||
<span className={styles.testCounts}>
|
||||
{counts.failed > 0 && <span className={styles.failed}>{tx`${counts.failed} failing`}</span>}
|
||||
{counts.passed > 0 && <span>{tx`${counts.passed} passed`}</span>}
|
||||
{counts.skipped > 0 && <span className={styles.skipped}>{tx`${counts.skipped} ignored`}</span>}
|
||||
{counts.total === 0 && <span className={styles.skipped}>{running ? tx("Running…") : tx("No tests")}</span>}
|
||||
</span>
|
||||
{duration !== undefined && <span className={styles.testTotalDuration}>{formatDuration(duration)}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const isFailedTest = (n: TestNode) => n.children.length === 0 && nodeStatus(n) === "failed";
|
||||
|
||||
const treeModel = {
|
||||
@@ -163,6 +199,8 @@ export function TestTreeView({
|
||||
});
|
||||
const sortButton = useRef<HTMLButtonElement>(null);
|
||||
const [sortMenu, setSortMenu] = useState(false);
|
||||
const moreButton = useRef<HTMLButtonElement>(null);
|
||||
const [moreMenu, setMoreMenu] = useState(false);
|
||||
const [expanded, setExpanded] = useState<Set<string> | null>(null);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [selection, setSelection] = useState<Set<string>>(new Set());
|
||||
@@ -226,7 +264,6 @@ export function TestTreeView({
|
||||
}
|
||||
};
|
||||
|
||||
const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// Like IDEA, Sort by Duration applies once the run has finished, so rows don't jump while tests report.
|
||||
const byDuration = sortByDuration && !running;
|
||||
const roots = useMemo(() => {
|
||||
@@ -276,21 +313,9 @@ export function TestTreeView({
|
||||
const hasPrevFailed = findOccurrence(roots, selected, -1, treeModel) !== null;
|
||||
const hasNextFailed = findOccurrence(roots, selected, 1, treeModel) !== null;
|
||||
|
||||
const status = running ? "running" : counts.failed > 0 ? "failed" : counts.total > 0 ? "passed" : null;
|
||||
const duration = results.summary.durationMs;
|
||||
|
||||
return (
|
||||
<div className={styles.testPane}>
|
||||
<div className={styles.testHeader}>
|
||||
<StatusIcon status={status} />
|
||||
<span className={styles.testCounts}>
|
||||
{counts.failed > 0 && <span className={styles.failed}>{tx`${counts.failed} failing`}</span>}
|
||||
{counts.passed > 0 && <span>{tx`${counts.passed} passed`}</span>}
|
||||
{counts.skipped > 0 && <span className={styles.skipped}>{tx`${counts.skipped} ignored`}</span>}
|
||||
{counts.total === 0 && <span className={styles.skipped}>{running ? tx("Running…") : tx("No tests")}</span>}
|
||||
{duration !== undefined && <span className={styles.skipped}>{formatDuration(duration)}</span>}
|
||||
</span>
|
||||
<span className={styles.spacer} />
|
||||
<Toolbar className={styles.testToolbar} aria-label="Test results">
|
||||
<IconButton
|
||||
icon="test-show-passed"
|
||||
size="small"
|
||||
@@ -332,14 +357,6 @@ export function TestTreeView({
|
||||
]}
|
||||
onClose={() => setSortMenu(false)}
|
||||
/>
|
||||
<IconButton icon="expand-all" action="run.expandAllTests" size="small" iconSize={16} disabled={!hasSuites} />
|
||||
<IconButton
|
||||
icon="collapse-all"
|
||||
action="run.collapseAllTests"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
disabled={!hasSuites}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
action="navigate.prevOccurrence"
|
||||
@@ -357,14 +374,42 @@ export function TestTreeView({
|
||||
disabled={!hasNextFailed}
|
||||
/>
|
||||
<IconButton
|
||||
icon="export"
|
||||
ref={moreButton}
|
||||
icon="more-horizontal"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Export Test Results…"
|
||||
disabled={!canExport}
|
||||
onClick={() => setExporting(true)}
|
||||
title="More Actions"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={moreMenu}
|
||||
onClick={() => setMoreMenu((open) => !open)}
|
||||
/>
|
||||
</div>
|
||||
<Menu
|
||||
open={moreMenu}
|
||||
anchor={moreButton}
|
||||
onClose={() => setMoreMenu(false)}
|
||||
items={[
|
||||
{
|
||||
icon: "expand-all",
|
||||
label: "Expand All",
|
||||
disabled: !hasSuites,
|
||||
run: () => void executeAction("run.expandAllTests"),
|
||||
},
|
||||
{
|
||||
icon: "collapse-all",
|
||||
label: "Collapse All",
|
||||
disabled: !hasSuites,
|
||||
run: () => void executeAction("run.collapseAllTests"),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{
|
||||
icon: "export",
|
||||
label: "Export Test Results…",
|
||||
disabled: !canExport,
|
||||
run: () => setExporting(true),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Toolbar>
|
||||
{exporting && (
|
||||
<ExportTestResultsDialog results={results} name={name} cwd={cwd} onClose={() => setExporting(false)} />
|
||||
)}
|
||||
@@ -396,7 +441,9 @@ export function TestTreeView({
|
||||
return (
|
||||
<span className={styles.testRow}>
|
||||
<StatusIcon status={s} />
|
||||
<span className={clsx(styles.testName, s === "skipped" && styles.skipped)}>{n.name}</span>
|
||||
<span className={clsx(styles.testName, s === "skipped" && styles.skipped)} title={n.name}>
|
||||
{n.name}
|
||||
</span>
|
||||
{d !== undefined && <span className={styles.testDuration}>{formatDuration(d)}</span>}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { BranchInfo, FileStatus, ProjectInfo, VcsRoot } from "@/bindings";
|
||||
import { commands, isTauri } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { deferred } from "@/test/deferred";
|
||||
import { getFileDecoration } from "@/workbench/contributions";
|
||||
import {
|
||||
discoverRoots,
|
||||
installVcsStore,
|
||||
onConflictsAppeared,
|
||||
onConflictsCleared,
|
||||
refreshNow,
|
||||
refreshPathsNow,
|
||||
useVcs,
|
||||
} from "./store";
|
||||
|
||||
vi.mock(import("@/platform/ipc"), async (original) => ({
|
||||
...(await original()),
|
||||
isTauri: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
const git: ProjectInfo = { root: "/a", name: "a", isGit: true, trusted: true, settings: {} };
|
||||
const nonGit: ProjectInfo = { root: "/b", name: "b", isGit: false, trusted: true, settings: {} };
|
||||
const branch: BranchInfo = {
|
||||
head: "feature-a",
|
||||
headCommit: "abc1234",
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: "merge",
|
||||
};
|
||||
const roots: VcsRoot[] = [{ root: git.root, head: branch.head, headCommit: branch.headCommit, operation: "merge" }];
|
||||
const conflicted: FileStatus = {
|
||||
path: "/a/src/conflict.ts",
|
||||
relPath: "src/conflict.ts",
|
||||
staged: null,
|
||||
unstaged: "conflicted",
|
||||
renamedFrom: null,
|
||||
};
|
||||
const modified: FileStatus = {
|
||||
...conflicted,
|
||||
path: "/a/src/edited.ts",
|
||||
relPath: "src/edited.ts",
|
||||
unstaged: "modified",
|
||||
};
|
||||
const status = [conflicted, modified];
|
||||
|
||||
type Ok<T> = { status: "ok"; data: T };
|
||||
const ok = <T>(data: T): Ok<T> => ({ status: "ok", data });
|
||||
|
||||
let dispose: () => void;
|
||||
const appeared = vi.fn();
|
||||
const cleared = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(commands, "vcsRoots").mockResolvedValue(ok(roots));
|
||||
vi.spyOn(commands, "vcsStatus").mockResolvedValue(ok(status));
|
||||
vi.spyOn(commands, "vcsBranchInfo").mockResolvedValue(ok(branch));
|
||||
onConflictsAppeared(appeared);
|
||||
onConflictsCleared(cleared);
|
||||
dispose = installVcsStore();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
dispose();
|
||||
onConflictsAppeared(() => undefined);
|
||||
onConflictsCleared(() => undefined);
|
||||
appeared.mockClear();
|
||||
cleared.mockClear();
|
||||
vi.restoreAllMocks();
|
||||
vi.mocked(isTauri).mockReset();
|
||||
useProject.setState(useProject.getInitialState(), true);
|
||||
useVcs.setState(useVcs.getInitialState(), true);
|
||||
});
|
||||
|
||||
describe("VCS status ownership", () => {
|
||||
it.each([
|
||||
{ command: "status", reopen: false },
|
||||
{ command: "roots", reopen: false },
|
||||
{ command: "status", reopen: true },
|
||||
])("drops a late $command response after switching projects (reopen: $reopen)", async ({ command, reopen }) => {
|
||||
const response = deferred<void>();
|
||||
const request =
|
||||
command === "status"
|
||||
? vi.mocked(commands.vcsStatus).mockReturnValueOnce(response.promise.then(() => ok(status)))
|
||||
: vi.mocked(commands.vcsRoots).mockReturnValueOnce(response.promise.then(() => ok(roots)));
|
||||
useProject.setState({ project: git });
|
||||
const refreshing = refreshNow();
|
||||
try {
|
||||
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
|
||||
// Emulate desktop discovery of nested roots for the non-Git project; there are none.
|
||||
vi.mocked(isTauri).mockReturnValueOnce(true);
|
||||
vi.mocked(commands.vcsRoots).mockResolvedValueOnce(ok([]));
|
||||
useProject.setState({ project: nonGit });
|
||||
const current = reopen ? { ...git } : nonGit;
|
||||
if (reopen) useProject.setState({ project: current });
|
||||
const reset = useVcs.getState();
|
||||
expect(reset).toMatchObject({ root: current.root, status: [], branch: null, statusLoaded: false });
|
||||
|
||||
response.resolve();
|
||||
await refreshing;
|
||||
|
||||
expect(useProject.getState().project).toBe(current);
|
||||
expect.soft(useVcs.getState()).toEqual(reset);
|
||||
expect.soft(getFileDecoration(conflicted.path)).toBeUndefined();
|
||||
expect.soft(getFileDecoration(modified.path)).toBeUndefined();
|
||||
expect.soft(appeared).not.toHaveBeenCalled();
|
||||
expect.soft(cleared).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
response.resolve();
|
||||
await refreshing;
|
||||
}
|
||||
});
|
||||
|
||||
it("does not publish an old refresh error in the new project", async () => {
|
||||
const reply = deferred<Ok<FileStatus[]>>();
|
||||
const request = vi.mocked(commands.vcsStatus).mockReturnValueOnce(reply.promise);
|
||||
useProject.setState({ project: git });
|
||||
const refreshing = refreshNow();
|
||||
try {
|
||||
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
|
||||
useProject.setState({ project: nonGit });
|
||||
const reset = useVcs.getState();
|
||||
|
||||
reply.reject(new Error("project A's Git status failed"));
|
||||
await refreshing;
|
||||
|
||||
expect(useVcs.getState()).toEqual(reset);
|
||||
} finally {
|
||||
reply.resolve(ok(status));
|
||||
await refreshing;
|
||||
}
|
||||
});
|
||||
|
||||
it("does not enable VCS from a discovery started before reopening the same folder", async () => {
|
||||
const reply = deferred<Ok<VcsRoot[]>>();
|
||||
const request = vi.mocked(commands.vcsRoots).mockReturnValueOnce(reply.promise);
|
||||
const folder = { ...git, isGit: false };
|
||||
useProject.setState({ project: folder });
|
||||
vi.mocked(isTauri).mockReturnValueOnce(true);
|
||||
const discovering = discoverRoots();
|
||||
// Drain any incorrectly started full refresh before disposing.
|
||||
const refreshed = deferred<void>();
|
||||
const offRefresh = useVcs.subscribe((s, prev) => {
|
||||
if (prev.loading && !s.loading) refreshed.resolve();
|
||||
});
|
||||
try {
|
||||
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
|
||||
useProject.setState({ project: nonGit });
|
||||
useProject.setState({ project: { ...folder } });
|
||||
|
||||
reply.resolve(ok(roots));
|
||||
await discovering;
|
||||
if (useVcs.getState().loading) await refreshed.promise;
|
||||
|
||||
expect.soft(useVcs.getState()).toMatchObject({ root: folder.root, available: false, roots: [], status: [] });
|
||||
expect.soft(commands.vcsStatus).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
reply.resolve(ok([]));
|
||||
await discovering;
|
||||
if (useVcs.getState().loading) await refreshed.promise;
|
||||
offRefresh();
|
||||
}
|
||||
});
|
||||
|
||||
it("drains a queued refresh for the new project without retrying the old incremental refresh", async () => {
|
||||
useProject.setState({ project: git });
|
||||
await refreshNow();
|
||||
const reply = deferred<Ok<FileStatus[]>>();
|
||||
const request = vi.spyOn(commands, "vcsStatusPaths").mockReturnValueOnce(reply.promise);
|
||||
const refreshing = refreshPathsNow([conflicted.path]);
|
||||
let next: Promise<void> | undefined;
|
||||
try {
|
||||
await vi.waitFor(() => expect(request).toHaveBeenCalledWith([conflicted.path]));
|
||||
const nextBranch = { ...branch, head: "main", operation: null };
|
||||
vi.mocked(commands.vcsRoots).mockResolvedValue(
|
||||
ok([{ root: nonGit.root, head: nextBranch.head, headCommit: nextBranch.headCommit, operation: null }]),
|
||||
);
|
||||
vi.mocked(commands.vcsStatus).mockResolvedValue(ok([]));
|
||||
vi.mocked(commands.vcsBranchInfo).mockResolvedValue(ok(nextBranch));
|
||||
vi.mocked(isTauri).mockReturnValueOnce(true);
|
||||
useProject.setState({ project: { ...nonGit, isGit: true } });
|
||||
next = refreshNow();
|
||||
|
||||
reply.resolve(ok([conflicted]));
|
||||
await Promise.all([refreshing, next]);
|
||||
|
||||
expect(useVcs.getState()).toMatchObject({ root: nonGit.root, status: [], branch: nextBranch });
|
||||
expect(getFileDecoration(conflicted.path)).toBeUndefined();
|
||||
expect(commands.vcsStatus).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
reply.resolve(ok([]));
|
||||
await Promise.all([refreshing, next]);
|
||||
}
|
||||
});
|
||||
|
||||
it("applies branch, changed files, decorations and conflict notifications for the active project", async () => {
|
||||
useProject.setState({ project: git });
|
||||
await refreshNow();
|
||||
|
||||
expect(useVcs.getState()).toMatchObject({ root: git.root, roots: [git.root], branch, status, statusLoaded: true });
|
||||
expect(useVcs.getState().byPath).toEqual(new Map(status.map((file) => [file.path, file])));
|
||||
expect(getFileDecoration(conflicted.path)?.color).toBe("var(--vcs-conflict)");
|
||||
expect(getFileDecoration(modified.path)?.color).toBe("var(--vcs-modified)");
|
||||
expect(appeared).toHaveBeenCalledExactlyOnceWith([conflicted]);
|
||||
expect(cleared).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -152,6 +152,9 @@ export function conflictedFiles(status: readonly FileStatus[] = useVcs.getState(
|
||||
return status.filter((f) => effectiveKind(f) === "conflicted");
|
||||
}
|
||||
|
||||
// Reopening the same root starts a new lifetime.
|
||||
let projectGeneration = 0;
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
/** A full refresh is queued; it answers for every path an incremental one would. */
|
||||
let pendingFull = false;
|
||||
@@ -221,6 +224,7 @@ export function refreshNow(): Promise<void> {
|
||||
});
|
||||
return followUp;
|
||||
}
|
||||
const generation = projectGeneration;
|
||||
inflight = (async () => {
|
||||
useVcs.setState({ loading: true });
|
||||
try {
|
||||
@@ -238,6 +242,7 @@ export function refreshNow(): Promise<void> {
|
||||
call(commands.vcsStatus()),
|
||||
scoped,
|
||||
]);
|
||||
if (generation !== projectGeneration) return;
|
||||
const roots = vcsRoots.map((r) => r.root);
|
||||
if ("error" in selected) {
|
||||
// The selected repository is gone (removed since the last scan): fall back to the primary one.
|
||||
@@ -263,9 +268,13 @@ export function refreshNow(): Promise<void> {
|
||||
void refreshNow();
|
||||
}
|
||||
} catch (e) {
|
||||
useVcs.setState({ error: e instanceof Error ? e.message : String(e) });
|
||||
if (generation === projectGeneration) {
|
||||
useVcs.setState({ error: e instanceof Error ? e.message : String(e) });
|
||||
}
|
||||
} finally {
|
||||
useVcs.setState((st) => ({ loading: false, version: st.version + 1 }));
|
||||
if (generation === projectGeneration) {
|
||||
useVcs.setState((st) => ({ loading: false, version: st.version + 1 }));
|
||||
}
|
||||
inflight = null;
|
||||
}
|
||||
})();
|
||||
@@ -292,9 +301,11 @@ export function refreshPathsNow(paths: readonly string[]): Promise<void> {
|
||||
});
|
||||
return followUp;
|
||||
}
|
||||
const generation = projectGeneration;
|
||||
const run = (async () => {
|
||||
try {
|
||||
const fresh = await call(commands.vcsStatusPaths([...paths]));
|
||||
if (generation !== projectGeneration) return false;
|
||||
const current = useVcs.getState();
|
||||
if (!current.statusLoaded || pairsRenames(current.status, paths, fresh)) return false;
|
||||
applyStatus(mergeStatus(current.status, paths, fresh), current.branch);
|
||||
@@ -306,7 +317,7 @@ export function refreshPathsNow(paths: readonly string[]): Promise<void> {
|
||||
})();
|
||||
const done = run.then((ok) => {
|
||||
inflight = null;
|
||||
return ok ? undefined : refreshNow();
|
||||
return ok || generation !== projectGeneration ? undefined : refreshNow();
|
||||
});
|
||||
inflight = done;
|
||||
return done;
|
||||
@@ -396,10 +407,10 @@ export function statusOf(path: string): FileStatus | undefined {
|
||||
|
||||
/** Repositories found below a project that is not itself under git (scanned in the background). */
|
||||
export async function discoverRoots() {
|
||||
const root = useVcs.getState().root;
|
||||
if (!root || !isTauri()) return;
|
||||
if (!useVcs.getState().root || !isTauri()) return;
|
||||
const generation = projectGeneration;
|
||||
const roots = await call(commands.vcsRoots()).catch(() => []);
|
||||
if (!roots.length || useVcs.getState().root !== root || useVcs.getState().available) return;
|
||||
if (!roots.length || generation !== projectGeneration || useVcs.getState().available) return;
|
||||
useVcs.setState({ available: true });
|
||||
setContext("vcsAvailable", true);
|
||||
void refreshNow();
|
||||
@@ -412,7 +423,9 @@ export function installVcsStore(): () => void {
|
||||
const available = !!project?.isGit;
|
||||
const root = project?.root ?? null;
|
||||
if (useVcs.getState().root === root && useVcs.getState().available === available) return;
|
||||
projectGeneration++;
|
||||
clearTimeout(timer);
|
||||
pendingPaths.clear();
|
||||
useVcs.setState({ ...initial, available, root, version: useVcs.getState().version + 1 });
|
||||
setContext("vcsAvailable", available);
|
||||
setFileDecorations("vcs", new Map());
|
||||
|
||||
@@ -122,7 +122,10 @@ export function MarkdownEditor({
|
||||
className={styles.group}
|
||||
storageKey={mode === "split" ? SPLIT_STORAGE_KEY : undefined}
|
||||
>
|
||||
<SplitPanel id="editor" style={{ overflow: "hidden" }} {...splitBounds}>
|
||||
{/* Hidden but mounted in Preview only (its caret drives the preview). Disabled, it leaves the group a
|
||||
single resizable panel: two enabled panels without a separator get an implicit resize region between
|
||||
them, which for a hidden panel spans everything left of the preview. */}
|
||||
<SplitPanel id="editor" style={{ overflow: "hidden" }} disabled={mode === "preview"} {...splitBounds}>
|
||||
<div ref={editorRef} className={styles.editor}>
|
||||
{children}
|
||||
</div>
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "无法复制引用",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
export function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason: unknown) => void;
|
||||
const promise = new Promise<T>((done, fail) => {
|
||||
resolve = done;
|
||||
reject = fail;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача