дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 10:07:11 +02:00
Merge remote-tracking branch 'origin/main' into HEAD
Цей коміт міститься в:
коміт
1fc71cad4e
150 files changed
+3830
-1034
No files matched your search
@@ -6267,11 +6267,11 @@ export type ExternalDiffSide = {
|
||||
};
|
||||
|
||||
/** A formatter that runs outside the language servers, with its own settings group. */
|
||||
export type ExternalFormatter = "prettier" | "oxfmt" | "ruff";
|
||||
export type ExternalFormatter = "prettier" | "oxfmt" | "biome" | "ruff";
|
||||
|
||||
/** An external formatter (Prettier, oxfmt, Ruff) and the languages it formats. */
|
||||
/** An external formatter (Prettier, oxfmt, Biome, Ruff) and the languages it formats. */
|
||||
export type ExternalFormatterSettings = {
|
||||
/** Empty path: project node_modules (Prettier/oxfmt), managed installation, then PATH. */
|
||||
/** Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH. */
|
||||
path?: string,
|
||||
/** Ruff only: directory containing its configuration, or a configuration file. */
|
||||
configurationDirectory?: string,
|
||||
@@ -8349,6 +8349,7 @@ export type LanguagesSettings = {
|
||||
typescript?: TypeScriptSettings,
|
||||
prettier?: ExternalFormatterSettings,
|
||||
oxfmt?: ExternalFormatterSettings,
|
||||
biome?: ExternalFormatterSettings,
|
||||
ruff?: ExternalFormatterSettings,
|
||||
java?: JavaSettings,
|
||||
ruby?: RubySettings,
|
||||
|
||||
@@ -40,6 +40,7 @@ import { rootOfPath } from "@/platform/projectRoots";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import { cornerInset } from "@/editor/core/cm/cornerInset";
|
||||
export { iconAreaSource, mapLineStart, type IconAreaSource } from "@/editor/core/cm/iconArea";
|
||||
export { disambiguateTitles } from "@/editor/core/model/tabTitles";
|
||||
export {
|
||||
invalidateNavigationProviders,
|
||||
navigationEpoch,
|
||||
|
||||
@@ -26,6 +26,12 @@ describe("disambiguateTitles", () => {
|
||||
expect(m.get("/r/a/d/f.ts")).toBe("d");
|
||||
});
|
||||
|
||||
it("distinguishes directory names that occur at different depths", () => {
|
||||
const paths = ["/r/prod/shared/f.ts", "/r/shared/prod/f.ts", "/r/test/shared/f.ts"];
|
||||
const labels = disambiguateTitles(paths);
|
||||
expect(paths.map((path) => labels.get(path))).toEqual(["prod/shared", "shared/prod", "test"]);
|
||||
});
|
||||
|
||||
it("ignores duplicates of the same path", () => {
|
||||
expect(disambiguateTitles(["/p/a/x.ts", "/p/a/x.ts"]).size).toBe(0);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* IDEA-style editor tab titles for files that share a name: the nearest parent
|
||||
* directory that tells them apart is shown after the name (`lib.rs — ide-lsp`
|
||||
* Directory hints for files that share a name: a distinguishing parent
|
||||
* directory is shown after the name (`lib.rs — ide-lsp`
|
||||
* for `crates/ide-lsp/src/lib.rs` next to `crates/ide-vcs/src/lib.rs`).
|
||||
*/
|
||||
|
||||
@@ -27,25 +27,24 @@ export function disambiguateTitles(paths: readonly string[], titleOf = baseName)
|
||||
for (const group of groups.values()) {
|
||||
if (group.length < 2) continue;
|
||||
const dirs = group.map(parents);
|
||||
const nameCounts = new Map<string, number>();
|
||||
const suffixCounts = new Map<string, number>();
|
||||
const suffixes = dirs.map((names) => {
|
||||
for (const name of new Set(names)) {
|
||||
nameCounts.set(name, (nameCounts.get(name) ?? 0) + 1);
|
||||
}
|
||||
let suffix = "";
|
||||
return names.map((name) => {
|
||||
suffix = suffix ? `${name}/${suffix}` : name;
|
||||
suffixCounts.set(suffix, (suffixCounts.get(suffix) ?? 0) + 1);
|
||||
return suffix;
|
||||
});
|
||||
});
|
||||
group.forEach((path, i) => {
|
||||
const own = dirs[i]!;
|
||||
let hint: string | null = null;
|
||||
for (let depth = 0; depth < own.length; depth++) {
|
||||
const seg = own[depth]!;
|
||||
if (dirs.every((other, j) => j === i || other[depth] !== seg)) {
|
||||
hint = seg;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hint === null) {
|
||||
// No single directory is unique: the shortest distinguishing parent path.
|
||||
const suffix = (d: string[], k: number) => d.slice(0, k).reverse().join("/");
|
||||
for (let k = 2; k <= own.length && hint === null; k++) {
|
||||
const mine = suffix(own, k);
|
||||
if (dirs.every((other, j) => j === i || suffix(other, k) !== mine)) hint = mine;
|
||||
}
|
||||
}
|
||||
out.set(path, hint ?? (own.length ? own.slice().reverse().join("/") : "/"));
|
||||
const name = dirs[i]!.find((segment) => nameCounts.get(segment) === 1);
|
||||
const paths = suffixes[i]!;
|
||||
const hint = name ?? paths.find((suffix, depth) => depth > 0 && suffixCounts.get(suffix) === 1);
|
||||
out.set(path, hint ?? paths.at(-1) ?? "/");
|
||||
});
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -150,6 +150,28 @@
|
||||
.deprecated {
|
||||
text-decoration-line: line-through;
|
||||
}
|
||||
.tabPath {
|
||||
--tab-directory-min: min(5ch, 25%);
|
||||
display: flex;
|
||||
}
|
||||
.tabDirectory > span,
|
||||
.tabFilename {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.tabDirectory {
|
||||
flex: 0 1000 max-content;
|
||||
/* Leave space for a short prefix without stretching one that already fits. */
|
||||
width: var(--tab-directory-min);
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.tabDirectory > span {
|
||||
display: block;
|
||||
}
|
||||
.tabFilename {
|
||||
flex: none;
|
||||
max-width: calc(100% - var(--tab-directory-min));
|
||||
}
|
||||
.dupe {
|
||||
color: var(--fg-faint);
|
||||
margin-left: 4px;
|
||||
|
||||
@@ -219,15 +219,23 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
const pin = t.pinned ? <Icon name="pin" size={11} className={styles.pin} label="Pinned" /> : null;
|
||||
const file = t.input.kind === "file" && t.input.path ? files.get(t.input.path) : undefined;
|
||||
const title = markModified && dirty[i] ? `*${name}` : name;
|
||||
const prefix = t.input.kind === "file" && dupe ? (dupe.endsWith("/") ? dupe : `${dupe}/`) : null;
|
||||
return {
|
||||
id: t.id,
|
||||
label: (
|
||||
label: prefix ? (
|
||||
<span className={styles.tabPath}>
|
||||
<span className={styles.tabDirectory}>
|
||||
<span>{prefix}</span>
|
||||
</span>
|
||||
<span className={clsx(styles.tabFilename, file?.deprecated && styles.deprecated)}>{title}</span>
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{file?.deprecated ? <span className={styles.deprecated}>{title}</span> : title}
|
||||
{dupe && <span className={styles.dupe}>{dupe}</span>}
|
||||
</>
|
||||
),
|
||||
text: dupe ? `${name} — ${dupe}` : name,
|
||||
text: prefix ? `${prefix}${name}` : dupe ? `${name} — ${dupe}` : name,
|
||||
icon: showFileIcon
|
||||
? t.input.kind === "file" && t.input.path
|
||||
? (tabIcons[i] ?? file?.icon)
|
||||
|
||||
@@ -532,20 +532,6 @@
|
||||
.renamePreview .previewList {
|
||||
overflow: visible;
|
||||
}
|
||||
.renamePreview .previewName {
|
||||
min-width: 0;
|
||||
max-width: 55%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.renamePreview .previewOp {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.renamePreview .previewWarning {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -571,23 +557,46 @@
|
||||
padding: 0 14px;
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.previewName {
|
||||
color: var(--fg-emphasis);
|
||||
.previewFile {
|
||||
flex: 1 1 auto;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
.previewPath {
|
||||
.previewName,
|
||||
.previewDirectory,
|
||||
.previewOp {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.previewName {
|
||||
flex: none;
|
||||
max-inline-size: 100%;
|
||||
color: var(--fg-emphasis);
|
||||
}
|
||||
.previewFile:has(.previewDirectory) .previewName {
|
||||
max-inline-size: 70%;
|
||||
}
|
||||
.previewDirectory {
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
direction: rtl;
|
||||
}
|
||||
.previewOp,
|
||||
.previewCount {
|
||||
flex: none;
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.previewOp {
|
||||
max-inline-size: 55%;
|
||||
}
|
||||
.previewCount {
|
||||
flex: none;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.previewWarning {
|
||||
flex: none;
|
||||
|
||||
@@ -15,7 +15,7 @@ vi.mock("@/workbench/contributions", async (orig) => {
|
||||
});
|
||||
|
||||
const { LspPopups, DocumentationWindow } = await import("./Popups");
|
||||
const { closePopup, openPopup, useLspPopup } = await import("./popupStore");
|
||||
const { closePopup, openPopup, updatePopup, useLspPopup } = await import("./popupStore");
|
||||
const { useDocWindow, hoverDoc, pushHistory, stepHistory, hoverCandidates } = await import("./docs");
|
||||
const { mountHoverDoc } = await import("./DocView");
|
||||
const { hoverSource } = await import("./hover");
|
||||
@@ -139,6 +139,31 @@ describe("list popup", () => {
|
||||
expect(onClose).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("keeps the chosen intention when a quick-fix section arrives ahead of it", () => {
|
||||
const local = ["Extract variable", "Inline value"].map((label) => ({
|
||||
id: label,
|
||||
label,
|
||||
section: { id: "intentions" },
|
||||
run: vi.fn(),
|
||||
}));
|
||||
openPopup({ kind: "list", title: "Intentions", anchor: { x: 0, y: 0 }, items: local, busy: true });
|
||||
render(<LspPopups />);
|
||||
fireEvent.keyDown(screen.getByRole("listbox"), { key: "ArrowDown" });
|
||||
expect(screen.getByRole("option", { name: "Inline value", selected: true })).toBeVisible();
|
||||
|
||||
const runFix = vi.fn();
|
||||
act(() =>
|
||||
updatePopup("list", {
|
||||
busy: false,
|
||||
items: [{ id: "fix", label: "Correct type", section: { id: "quick-fixes" }, run: runFix }, ...local],
|
||||
}),
|
||||
);
|
||||
expect(screen.getByRole("option", { name: "Inline value", selected: true })).toBeVisible();
|
||||
fireEvent.keyDown(screen.getByRole("listbox"), { key: "Enter" });
|
||||
expect(local[1]!.run).toHaveBeenCalledOnce();
|
||||
expect(runFix).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("focuses the rows, not the header's pin button, when it opens", () => {
|
||||
openPopup({
|
||||
kind: "list",
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
selectableText,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { basename, relativePath, useProject } from "@/platform/project";
|
||||
import { basename, relativeDir, relativePath, useProject } from "@/platform/project";
|
||||
import {
|
||||
closePopup,
|
||||
updatePopup,
|
||||
@@ -112,14 +112,10 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
const [query, setQuery] = useState("");
|
||||
const rows = useMemo(() => listPopupRows(popup.items, query), [popup.items, query]);
|
||||
const firstEnabled = rows.findIndex((row) => row.kind === "action" && !row.item.disabled);
|
||||
const [active, setActive] = useState(firstEnabled);
|
||||
const clamped = Math.min(active, rows.length - 1);
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
const selected = rows.findIndex((row) => row.kind === "action" && row.item.id === activeId);
|
||||
const activeIndex =
|
||||
rows[clamped]?.kind === "action"
|
||||
? clamped
|
||||
: firstEnabled >= 0
|
||||
? firstEnabled
|
||||
: firstSelectable(rows, isListSection);
|
||||
selected >= 0 ? selected : firstEnabled >= 0 ? firstEnabled : firstSelectable(rows, isListSection);
|
||||
const activeRow = rows[activeIndex];
|
||||
const activeItem = activeRow?.kind === "action" ? activeRow.item : undefined;
|
||||
const showIcons = !popup.compact || popup.items.some((item) => item.icon || item.symbol);
|
||||
@@ -183,11 +179,11 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
if (item) activate(item);
|
||||
} else if (e.key === "Backspace" && query) {
|
||||
setQuery(query.slice(0, -1));
|
||||
setActive(-1);
|
||||
setActiveId(null);
|
||||
e.preventDefault();
|
||||
} else if (e.key.length === 1 && !(e.key === " " && !query)) {
|
||||
setQuery(query + e.key);
|
||||
setActive(-1);
|
||||
setActiveId(null);
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
@@ -297,7 +293,10 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
row.kind === "section" && row.label ? <T>{row.label}</T> : <span className={styles.listDivider} />
|
||||
}
|
||||
activeIndex={activeIndex}
|
||||
onActiveChange={setActive}
|
||||
onActiveChange={(index) => {
|
||||
const row = rows[index];
|
||||
setActiveId(row?.kind === "action" ? row.item.id : null);
|
||||
}}
|
||||
hoverSelects
|
||||
autoFocus
|
||||
aria-label={popup.title}
|
||||
@@ -762,25 +761,34 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
|
||||
</ul>
|
||||
) : (
|
||||
<ul data-testid="refactor-preview" className={styles.previewList} aria-label={tx("Changes")}>
|
||||
{summary.entries.map((e) => (
|
||||
<li key={e.path} className={styles.previewRow}>
|
||||
<Icon name={fileIconName(basename(e.path), e.path)} size={14} className={styles.itemIcon} />
|
||||
<span className={styles.previewName} title={relativePath(root, e.path)}>
|
||||
{basename(e.path)}
|
||||
</span>
|
||||
<span className={styles.previewPath} title={relativePath(root, e.path)}>
|
||||
{relativePath(root, e.path)}
|
||||
</span>
|
||||
<span className={styles.spacer} />
|
||||
{e.operation === "rename" && e.to && <span className={styles.previewOp}>→ {basename(e.to)}</span>}
|
||||
{e.operation && e.operation !== "rename" && <span className={styles.previewOp}>{e.operation}</span>}
|
||||
{e.edits > 0 && (
|
||||
<span className={styles.previewCount}>
|
||||
{e.edits} {e.edits === 1 ? "occurrence" : "occurrences"}
|
||||
{summary.entries.map((e) => {
|
||||
const name = basename(e.path);
|
||||
const directory = relativeDir(root, e.path);
|
||||
return (
|
||||
<li key={e.path} className={styles.previewRow}>
|
||||
<Icon name={fileIconName(name, e.path)} size={14} className={styles.itemIcon} />
|
||||
<span className={styles.previewFile} title={relativePath(root, e.path)}>
|
||||
<span className={styles.previewName}>{name}</span>
|
||||
{directory && (
|
||||
<span className={styles.previewDirectory}>
|
||||
<bdi>{directory}</bdi>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
{e.operation === "rename" && e.to && (
|
||||
<span className={styles.previewOp} title={relativePath(root, e.to)}>
|
||||
→ {basename(e.to)}
|
||||
</span>
|
||||
)}
|
||||
{e.operation && e.operation !== "rename" && <span className={styles.previewOp}>{e.operation}</span>}
|
||||
{e.edits > 0 && (
|
||||
<span className={styles.previewCount}>
|
||||
{e.edits} {e.edits === 1 ? "occurrence" : "occurrences"}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</Dialog>
|
||||
|
||||
@@ -195,10 +195,10 @@ function editorAction(
|
||||
|
||||
/** Whether saving a `language` file formats it: Format on save, or Run on save of an external formatter. */
|
||||
export function formatsOnSave(settings: Settings | null, language: string): boolean {
|
||||
const { prettier, oxfmt, ruff } = validateLanguages(settings?.languages);
|
||||
const { prettier, oxfmt, biome, ruff } = validateLanguages(settings?.languages);
|
||||
return (
|
||||
!!settings?.editor?.formatOnSave ||
|
||||
[prettier, oxfmt, ruff].some((formatter) => formatter.runOnSave && formatter.languages.includes(language))
|
||||
[prettier, oxfmt, biome, ruff].some((formatter) => formatter.runOnSave && formatter.languages.includes(language))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -275,6 +275,13 @@ export function registerLspActions(): () => void {
|
||||
(v) => formatDocument(v, { explicit: true, tool: "oxfmt" }),
|
||||
{ keywords: ["format", "oxfmt", "oxc"] },
|
||||
),
|
||||
editorAction(
|
||||
"code.reformatWithBiome",
|
||||
"Reformat with Biome",
|
||||
"Code",
|
||||
(v) => formatDocument(v, { explicit: true, tool: "biome" }),
|
||||
{ keywords: ["format", "biome"] },
|
||||
),
|
||||
editorAction(
|
||||
"code.reformatWithRuff",
|
||||
"Reformat with Ruff",
|
||||
|
||||
@@ -173,13 +173,15 @@ describe("format on save provider isolation", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("formats on save for the languages whose Prettier or oxfmt Run on save is on", () => {
|
||||
it("formats on save for the languages whose Prettier, oxfmt or Biome Run on save is on", () => {
|
||||
const settings = (languages: Settings["languages"], formatOnSave = false) =>
|
||||
({ editor: { formatOnSave }, languages }) as Settings;
|
||||
const oxfmt = settings({ oxfmt: { runOnSave: true, languages: ["typescript"] } });
|
||||
expect(formatsOnSave(oxfmt, "typescript")).toBe(true);
|
||||
expect(formatsOnSave(oxfmt, "markdown")).toBe(false);
|
||||
expect(formatsOnSave(settings({ prettier: { runOnSave: true } }), "markdown")).toBe(true);
|
||||
expect(formatsOnSave(settings({ biome: { runOnSave: true } }), "json")).toBe(true);
|
||||
expect(formatsOnSave(settings({ biome: { runOnSave: true } }), "markdown")).toBe(false);
|
||||
expect(formatsOnSave(settings({ ruff: { runOnSave: true } }), "python")).toBe(true);
|
||||
expect(formatsOnSave(settings({ ruff: { runOnSave: true } }), "typescript")).toBe(false);
|
||||
expect(formatsOnSave(settings({}), "typescript")).toBe(false);
|
||||
|
||||
@@ -96,7 +96,7 @@ interface FormatDocumentOptions {
|
||||
explicit: boolean;
|
||||
selectionOnly?: boolean;
|
||||
onSave?: boolean;
|
||||
/** Runs this external formatter whatever the settings select (Reformat with Prettier/oxfmt). */
|
||||
/** Runs this external formatter whatever the settings select (Reformat with Prettier/oxfmt/Biome). */
|
||||
tool?: ExternalFormatter;
|
||||
/** Formats only these ranges, e.g. the text changed since the last commit; an empty list formats nothing. */
|
||||
ranges?: readonly OffsetRange[];
|
||||
@@ -176,6 +176,7 @@ async function format(view: EditorView, opts: FormatDocumentOptions): Promise<Fo
|
||||
? {
|
||||
prettier: { failed: "Prettier formatting failed", timedOut: "Prettier formatting timed out" },
|
||||
oxfmt: { failed: "oxfmt formatting failed", timedOut: "oxfmt formatting timed out" },
|
||||
biome: { failed: "Biome formatting failed", timedOut: "Biome formatting timed out" },
|
||||
ruff: { failed: "Ruff formatting failed", timedOut: "Ruff formatting timed out" },
|
||||
}[e.data.tool]
|
||||
: undefined;
|
||||
|
||||
@@ -44,9 +44,9 @@ afterEach(() => {
|
||||
_resetI18nForTests();
|
||||
});
|
||||
|
||||
describe.each(["prettier", "oxfmt", "ruff"])("%s formatter errors", (name) => {
|
||||
describe.each(["prettier", "oxfmt", "biome", "ruff"])("%s formatter errors", (name) => {
|
||||
const tool = { type: "tool", tool: name, missing: false } as const;
|
||||
const display = name === "prettier" ? "Prettier" : name === "ruff" ? "Ruff" : name;
|
||||
const display = ({ prettier: "Prettier", biome: "Biome", ruff: "Ruff" } as Record<string, string>)[name] ?? name;
|
||||
it("uses structured missing-tool information to request the shared install prompt", async () => {
|
||||
const prompt = vi.fn();
|
||||
const dispose = registerAction({
|
||||
@@ -130,6 +130,7 @@ describe("Reformat with an external formatter", () => {
|
||||
it.each([
|
||||
["code.reformatWithPrettier", "prettier"],
|
||||
["code.reformatWithOxfmt", "oxfmt"],
|
||||
["code.reformatWithBiome", "biome"],
|
||||
["code.reformatWithRuff", "ruff"],
|
||||
])("%s asks the backend for %s whatever the settings select", async (id, tool) => {
|
||||
vi.spyOn(lsp, "lspRequest").mockImplementation(async (request) => {
|
||||
|
||||
@@ -60,11 +60,18 @@ export function quickFixIcon(view: EditorView): "bulb" | "bulb-fix" {
|
||||
|
||||
const isFixItem = (item: ListPopupItem) => item.quickFix ?? item.icon === "bulb-fix";
|
||||
|
||||
/** Local and language-server fixes share icons and the same stable ordering. */
|
||||
/** Local and language-server fixes share icons and are grouped separately from other actions. */
|
||||
export function listedIntentions(view: EditorView, items: ListPopupItem[]): ListPopupItem[] {
|
||||
const rank = (item: ListPopupItem) => (item.disabled ? 4 : 0) + (isFixItem(item) ? 0 : 2) + (item.emphasis ? 0 : 1);
|
||||
return items
|
||||
.map((item) => (isFixItem(item) ? { ...item, quickFix: true, icon: quickFixIcon(view) } : item))
|
||||
.map((item) => {
|
||||
const fix = isFixItem(item);
|
||||
return {
|
||||
...item,
|
||||
...(fix && { quickFix: true, icon: quickFixIcon(view) }),
|
||||
section: item.section ?? { id: item.disabled ? "unavailable" : fix ? "quick-fixes" : "intentions" },
|
||||
};
|
||||
})
|
||||
.sort((a, b) => rank(a) - rank(b));
|
||||
}
|
||||
|
||||
@@ -497,6 +504,7 @@ export function withInspectionControls(view: EditorView, items: ListPopupItem[])
|
||||
...inspections.map((inspection) => ({
|
||||
id: `inspection:${inspection.id}`,
|
||||
label: tx`Inspection '${txPart(inspection.name)}' options`,
|
||||
section: { id: "inspection-options" },
|
||||
icon: "settings",
|
||||
run: () => editInspectionSettings(inspection.id),
|
||||
submenu: intentionControls(inspection),
|
||||
|
||||
@@ -94,10 +94,16 @@
|
||||
flex: none;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.fileName {
|
||||
.fileName,
|
||||
.directory {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.directory {
|
||||
flex: 0 2 auto;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.line {
|
||||
overflow: hidden;
|
||||
text-align: right;
|
||||
|
||||
@@ -8,7 +8,7 @@ import { create } from "zustand";
|
||||
import clsx from "clsx";
|
||||
import { EditorState, StateEffect, StateField } from "@codemirror/state";
|
||||
import { Decoration, EditorView } from "@codemirror/view";
|
||||
import { codePreviewExtensions } from "@/editor/api";
|
||||
import { codePreviewExtensions, disambiguateTitles } from "@/editor/api";
|
||||
import { basename } from "@/platform/project";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { Icon, IconButton, List, Popup, Select, Spinner, fileIconName, listNavigate } from "@/ui";
|
||||
@@ -86,6 +86,14 @@ function UsagesPopupInner() {
|
||||
const preview = useUsagesPopupPreview((s) => s.preview);
|
||||
const rowHeight = useRowHeight(ROW);
|
||||
const all = useMemo<Usage[]>(() => groups.flatMap((g) => g.usages), [groups]);
|
||||
const directories = useMemo(
|
||||
() =>
|
||||
disambiguateTitles(
|
||||
groups.map((g) => g.path),
|
||||
basename,
|
||||
),
|
||||
[groups],
|
||||
);
|
||||
const [filter, setFilter] = useState("");
|
||||
const accessOptions = useUsageAccessOptions();
|
||||
const items = useMemo(
|
||||
@@ -233,11 +241,10 @@ function UsagesPopupInner() {
|
||||
}
|
||||
renderItem={(u) => (
|
||||
<div className={styles.row} data-testid="usage-row" data-path={u.path} data-line={u.line}>
|
||||
<span className={styles.file}>
|
||||
<span className={styles.file} title={u.path}>
|
||||
<Icon name={fileIconName(basename(u.path), u.path)} size={16} className={styles.icon} />
|
||||
<span className={styles.fileName} title={u.path}>
|
||||
{basename(u.path)}
|
||||
</span>
|
||||
<span className={styles.fileName}>{basename(u.path)}</span>
|
||||
{directories.has(u.path) && <span className={styles.directory}>{directories.get(u.path)}</span>}
|
||||
</span>
|
||||
<span className={styles.line}>{u.line + 1}</span>
|
||||
<UsagePreview usage={u} />
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { RgbaColorPicker } from "react-colorful";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { Button, IconButton, Popup, T } from "@/ui";
|
||||
import { fromHex, toHex8, type Rgba } from "./colors";
|
||||
import styles from "./ColorPicker.module.css";
|
||||
import { ColorPicker, rememberColor } from "@/ui/ColorPicker";
|
||||
import type { Rgba } from "@/ui/colorPickerValues";
|
||||
|
||||
interface PickerRequest {
|
||||
view: EditorView;
|
||||
@@ -20,47 +17,13 @@ let root: Root | null = null;
|
||||
let host: HTMLElement | null = null;
|
||||
let active: (PickerRequest & { initial: Rgba }) | null = null;
|
||||
let sequence = 0;
|
||||
const RECENT_KEY = "openidea.colorPicker.recent.v1";
|
||||
const MAX_RECENT = 20;
|
||||
|
||||
function readRecent(): string[] {
|
||||
try {
|
||||
const value: unknown = JSON.parse(localStorage.getItem(RECENT_KEY) ?? "[]");
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === "string" && fromHex(item) !== null).slice(0, MAX_RECENT)
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function rememberColor(value: Rgba) {
|
||||
const hex = toHex8(value);
|
||||
const recent = [hex, ...readRecent().filter((item) => item.toLowerCase() !== hex)].slice(0, MAX_RECENT);
|
||||
try {
|
||||
localStorage.setItem(RECENT_KEY, JSON.stringify(recent));
|
||||
} catch {
|
||||
// Storage can be unavailable in a restricted WebView.
|
||||
}
|
||||
}
|
||||
|
||||
interface EyeDropperResult {
|
||||
sRGBHex: string;
|
||||
}
|
||||
|
||||
interface EyeDropperInstance {
|
||||
open(): Promise<EyeDropperResult>;
|
||||
}
|
||||
|
||||
type EyeDropperWindow = Window & { EyeDropper?: new () => EyeDropperInstance };
|
||||
|
||||
function render() {
|
||||
if (!root) {
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
}
|
||||
root.render(active ? <Picker key={sequence} id={sequence} request={active} /> : null);
|
||||
root.render(active ? <EditorPicker key={sequence} id={sequence} request={active} /> : null);
|
||||
}
|
||||
|
||||
export function openColorPicker(request: PickerRequest) {
|
||||
@@ -100,54 +63,7 @@ export function disposeColorPicker() {
|
||||
host = null;
|
||||
}
|
||||
|
||||
function Field({
|
||||
label,
|
||||
name,
|
||||
value,
|
||||
maxLength,
|
||||
inputMode,
|
||||
isValid,
|
||||
onValid,
|
||||
}: {
|
||||
label: string;
|
||||
name: string;
|
||||
value: string;
|
||||
maxLength: number;
|
||||
inputMode: "numeric" | "text";
|
||||
isValid: (text: string) => boolean;
|
||||
onValid: (text: string) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
const t = useTx();
|
||||
const shown = draft ?? value;
|
||||
return (
|
||||
<label className={styles.field}>
|
||||
<span>{label}</span>
|
||||
<input
|
||||
aria-label={t(name)}
|
||||
aria-invalid={shown !== "" && !isValid(shown)}
|
||||
inputMode={inputMode}
|
||||
maxLength={maxLength}
|
||||
spellCheck={false}
|
||||
value={shown}
|
||||
onChange={(event) => {
|
||||
const next = event.currentTarget.value;
|
||||
setDraft(next);
|
||||
if (isValid(next)) onValid(next);
|
||||
}}
|
||||
onBlur={() => setDraft(null)}
|
||||
onFocus={(event) => event.currentTarget.select()}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function Picker({ id, request }: { id: number; request: PickerRequest }) {
|
||||
const [value, setValue] = useState<Rgba>(request.value);
|
||||
const [recent] = useState(readRecent);
|
||||
const [sampling, setSampling] = useState(false);
|
||||
const t = useTx();
|
||||
const eyeDropper = (window as EyeDropperWindow).EyeDropper;
|
||||
function EditorPicker({ id, request }: { id: number; request: PickerRequest }) {
|
||||
useEffect(() => {
|
||||
const close = () => {
|
||||
if (sequence === id) closeColorPicker();
|
||||
@@ -156,154 +72,18 @@ function Picker({ id, request }: { id: number; request: PickerRequest }) {
|
||||
return () => request.view.scrollDOM.removeEventListener("scroll", close);
|
||||
}, [id, request.view]);
|
||||
|
||||
const update = (next: Rgba) => {
|
||||
if (sequence !== id || !active) return;
|
||||
setValue(next);
|
||||
active = { ...active, value: next };
|
||||
request.onChange?.(next);
|
||||
};
|
||||
const channel = (index: 0 | 1 | 2, text: string) => {
|
||||
const number = Number(text);
|
||||
const next: Rgba = [...value];
|
||||
next[index] = number;
|
||||
update(next);
|
||||
};
|
||||
const alpha = (text: string) => {
|
||||
const number = Number(text);
|
||||
update([value[0], value[1], value[2], number / 100]);
|
||||
};
|
||||
const hex = (text: string) => {
|
||||
const next = fromHex(text);
|
||||
if (next) update(next);
|
||||
};
|
||||
const numeric = (max: number) => (text: string) => /^\d{1,3}$/.test(text) && Number(text) <= max;
|
||||
const sampleScreen = async () => {
|
||||
if (!eyeDropper || sampling) return;
|
||||
setSampling(true);
|
||||
try {
|
||||
const result = await new eyeDropper().open();
|
||||
const next = fromHex(result.sRGBHex);
|
||||
if (next && sequence === id && active) update(next);
|
||||
} catch (error) {
|
||||
if (!(error instanceof DOMException && error.name === "AbortError")) console.warn(error);
|
||||
} finally {
|
||||
if (sequence === id && active) setSampling(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
<ColorPicker
|
||||
anchor={request.anchor}
|
||||
placement="bottom-start"
|
||||
offset={4}
|
||||
onClose={(reason) => closeColorPicker(reason !== "escape")}
|
||||
aria-label={t("Color picker")}
|
||||
className={styles.popup}
|
||||
trapFocus
|
||||
closeOnDeactivate={false}
|
||||
>
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!event.currentTarget.querySelector('[aria-invalid="true"]')) closeColorPicker(true);
|
||||
}}
|
||||
>
|
||||
<div className={styles.pickerArea}>
|
||||
<RgbaColorPicker
|
||||
className={styles.control}
|
||||
color={{ r: value[0], g: value[1], b: value[2], a: value[3] }}
|
||||
onChange={({ r, g, b, a }) => update([r, g, b, a])}
|
||||
/>
|
||||
<div className={styles.sampleRow}>
|
||||
<IconButton
|
||||
icon="eyedropper"
|
||||
title="Pick screen color"
|
||||
size="small"
|
||||
disabled={!eyeDropper || sampling}
|
||||
onClick={() => void sampleScreen()}
|
||||
/>
|
||||
<div className={styles.preview} role="img" aria-label={t("Current color")}>
|
||||
<span style={{ backgroundColor: `rgba(${value.join(", ")})` }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.fields}>
|
||||
<Field
|
||||
label="R"
|
||||
name="Red"
|
||||
value={String(value[0])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(0, v)}
|
||||
/>
|
||||
<Field
|
||||
label="G"
|
||||
name="Green"
|
||||
value={String(value[1])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(1, v)}
|
||||
/>
|
||||
<Field
|
||||
label="B"
|
||||
name="Blue"
|
||||
value={String(value[2])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(2, v)}
|
||||
/>
|
||||
<Field
|
||||
label="A%"
|
||||
name="Alpha percent"
|
||||
value={String(Math.round(value[3] * 100))}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(100)}
|
||||
onValid={alpha}
|
||||
/>
|
||||
<Field
|
||||
label={t("HEX")}
|
||||
name="Hexadecimal"
|
||||
value={toHex8(value).slice(1).toUpperCase()}
|
||||
maxLength={9}
|
||||
inputMode="text"
|
||||
isValid={(v) => fromHex(v) !== null}
|
||||
onValid={hex}
|
||||
/>
|
||||
</div>
|
||||
{recent.length > 0 && (
|
||||
<div className={styles.recent} role="group" aria-label={t("Recent colors")}>
|
||||
{recent.map((hex) => (
|
||||
<button
|
||||
key={hex}
|
||||
type="button"
|
||||
title={hex.toUpperCase()}
|
||||
aria-label={`${t("Recent color")} ${hex.toUpperCase()}`}
|
||||
aria-pressed={hex.toLowerCase() === toHex8(value)}
|
||||
className={styles.recentColor}
|
||||
onClick={() => {
|
||||
const next = fromHex(hex);
|
||||
if (next) update(next);
|
||||
}}
|
||||
>
|
||||
<span style={{ backgroundColor: hex }} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.actions}>
|
||||
<Button size="small" onClick={() => closeColorPicker()}>
|
||||
<T>Cancel</T>
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" size="small">
|
||||
<T>Apply</T>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Popup>
|
||||
initial={request.value}
|
||||
onChange={(value) => {
|
||||
if (sequence !== id || !active) return;
|
||||
active = { ...active, value };
|
||||
request.onChange?.(value);
|
||||
}}
|
||||
onFinish={(commit) => {
|
||||
if (sequence === id) closeColorPicker(commit);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
import { hex2, toHex6, type Rgba } from "@/ui/colorPickerValues";
|
||||
export { fromHex, toHex6, toHex8, type Rgba } from "@/ui/colorPickerValues";
|
||||
|
||||
/**
|
||||
* Color literals of a line for the gutter's color preview: `#rgb` / `#rrggbb` (with alpha),
|
||||
* `rgb()` / `rgba()` / `hsl()` / `hsla()`, and CSS named colors in style sheets. Pure; the
|
||||
@@ -14,9 +17,6 @@ export interface ColorMatch {
|
||||
format: ColorFormat;
|
||||
}
|
||||
|
||||
/** Red, green, blue 0–255 and alpha 0–1. */
|
||||
export type Rgba = [number, number, number, number];
|
||||
|
||||
/** Style sheet languages: named colors and unquoted hex values are colors there. */
|
||||
const STYLE_SHEETS = new Set(["css", "scss", "sass", "less", "stylus", "postcss"]);
|
||||
/** Markup that embeds style sheets (`<style>`, `style="…"`): unquoted hex values too. */
|
||||
@@ -72,34 +72,8 @@ export function findColors(line: string, language: string, isColorName: (word: s
|
||||
}
|
||||
|
||||
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
||||
const hex2 = (v: number) =>
|
||||
Math.round(clamp(v, 0, 255))
|
||||
.toString(16)
|
||||
.padStart(2, "0");
|
||||
const round = (v: number, digits = 2) => String(Number(v.toFixed(digits)));
|
||||
|
||||
/** `#rrggbb` of `rgba`, as `<input type=color>` takes it. */
|
||||
export function toHex6([r, g, b]: Rgba): string {
|
||||
return `#${hex2(r)}${hex2(g)}${hex2(b)}`;
|
||||
}
|
||||
|
||||
export function toHex8(rgba: Rgba): string {
|
||||
return `${toHex6(rgba)}${hex2(rgba[3] * 255)}`;
|
||||
}
|
||||
|
||||
/** Six-digit hex is opaque; eight-digit hex carries its own alpha. */
|
||||
export function fromHex(hex: string): Rgba | null {
|
||||
const m = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i.exec(hex);
|
||||
return m
|
||||
? [
|
||||
Number.parseInt(m[1]!, 16),
|
||||
Number.parseInt(m[2]!, 16),
|
||||
Number.parseInt(m[3]!, 16),
|
||||
m[4] ? Number.parseInt(m[4], 16) / 255 : 1,
|
||||
]
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Components of the browser's computed color (`rgb(1, 2, 3)` / `rgba(1, 2, 3, 0.5)`), null for other spaces. */
|
||||
export function parseComputed(color: string): Rgba | null {
|
||||
const m = /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(color.trim());
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LaunchConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { handleDebugEvent, resetSessions, startSession, useDebug } from "../state";
|
||||
|
||||
const ipc = vi.hoisted(() => {
|
||||
let next = 0;
|
||||
return {
|
||||
/** A backend process numbers its sessions from 1. */
|
||||
restart: () => (next = 0),
|
||||
debugStart: vi.fn(async (_launch: unknown) => ({ status: "ok", data: ++next })),
|
||||
debugStop: vi.fn(async (_id: number) => ({ status: "ok", data: null })),
|
||||
};
|
||||
});
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
const { restart: _restart, ...commands } = ipc;
|
||||
return { ...real, isTauri: () => true, commands: { ...real.commands, ...commands } };
|
||||
});
|
||||
|
||||
const launch: LaunchConfig = {
|
||||
name: "pricing > withTax > adds the rate",
|
||||
adapter: "js-debug",
|
||||
request: "launch",
|
||||
program: null,
|
||||
args: [],
|
||||
cwd: "/p",
|
||||
env: {},
|
||||
extraJson: JSON.stringify({ type: "pwa-node", runtimeExecutable: "npm", runtimeArgs: ["run", "test"] }),
|
||||
};
|
||||
|
||||
/** js-debug's session for a process the debuggee started (`startDebugging`). */
|
||||
const child = (id: number, parent: number, name: string) =>
|
||||
handleDebugEvent(id, { kind: "started", name, adapter: "js-debug", parent });
|
||||
const breakpoint = (id: number) =>
|
||||
handleDebugEvent(id, {
|
||||
kind: "stopped",
|
||||
threadId: 1,
|
||||
reason: "breakpoint",
|
||||
description: null,
|
||||
allThreadsStopped: false,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
useDebug.setState({ sessions: {}, active: null });
|
||||
resetSessions();
|
||||
ipc.restart();
|
||||
useProject.setState({
|
||||
project: { root: "/p" } as ReturnType<typeof useProject.getState>["project"],
|
||||
settings: null,
|
||||
});
|
||||
});
|
||||
|
||||
describe("sessions of a window whose backend changes", () => {
|
||||
it("adopts the children of a new session although an earlier backend used their ids", async () => {
|
||||
// The first backend: `npm run test` and the process js-debug attached to under it.
|
||||
expect(await startSession(launch)).toBe(1);
|
||||
child(2, 1, "npm-cli.js [100]");
|
||||
expect(useDebug.getState().sessions[2]?.parent).toBe(1);
|
||||
|
||||
// The window reopens its project on another backend (a remote reconnect): ids start over.
|
||||
resetSessions();
|
||||
ipc.restart();
|
||||
expect(await startSession(launch)).toBe(1);
|
||||
child(2, 1, "npm-cli.js [200]");
|
||||
child(3, 2, "mocha.js [201]");
|
||||
breakpoint(3);
|
||||
|
||||
const { sessions, active } = useDebug.getState();
|
||||
expect([sessions[2]?.name, sessions[2]?.parent]).toEqual(["npm-cli.js [200]", 1]);
|
||||
expect([sessions[3]?.name, sessions[3]?.parent, sessions[3]?.status]).toEqual(["mocha.js [201]", 2, "paused"]);
|
||||
expect(active).toBe(3);
|
||||
});
|
||||
|
||||
it("still ignores late events of the sessions it forgot", async () => {
|
||||
await startSession(launch);
|
||||
child(2, 1, "npm-cli.js [100]");
|
||||
resetSessions();
|
||||
|
||||
breakpoint(2);
|
||||
handleDebugEvent(1, { kind: "output", category: "stdout", output: "late\n" });
|
||||
expect(useDebug.getState().sessions).toEqual({});
|
||||
expect(useDebug.getState().console).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -307,7 +307,9 @@ function ownSession(id: DebugSessionId, event: DebugEvent): DebugSession | null
|
||||
const st = useDebug.getState();
|
||||
const existing = st.sessions[id];
|
||||
if (existing) return existing;
|
||||
if (owned.has(id)) return null;
|
||||
// `started` is a session's first event, sent once when the backend creates it: never a late event
|
||||
// of a forgotten session, though its id may be one (another backend numbers from 1 again).
|
||||
if (owned.has(id) && event.kind !== "started") return null;
|
||||
if (event.kind === "started" && event.parent != null) {
|
||||
if (!st.sessions[event.parent]) return null;
|
||||
return adoptSession(id, { name: event.name, adapter: event.adapter, parent: event.parent });
|
||||
|
||||
@@ -29,6 +29,23 @@
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.bpActions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-small);
|
||||
}
|
||||
|
||||
.bpActions > legend {
|
||||
padding-inline: var(--space-1);
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.bpTitle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -212,7 +229,7 @@
|
||||
font-family: var(--font-ui);
|
||||
}
|
||||
|
||||
.detail .label {
|
||||
:is(.detail, .bpEditor) .label {
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
|
||||
@@ -212,12 +212,14 @@ function BreakpointFields({
|
||||
focus,
|
||||
onEnter,
|
||||
commitRef,
|
||||
showRemoveOnceHit = false,
|
||||
}: {
|
||||
path: string;
|
||||
bp: BreakpointEntry;
|
||||
focus?: "condition" | "log";
|
||||
onEnter?: () => void;
|
||||
commitRef?: MutableRefObject<(() => void) | null>;
|
||||
showRemoveOnceHit?: boolean;
|
||||
}) {
|
||||
const [condition, setCondition] = useState(bp.condition ?? "");
|
||||
const [hitCondition, setHitCondition] = useState(bp.hitCondition ?? "");
|
||||
@@ -308,32 +310,44 @@ function BreakpointFields({
|
||||
aria-label="Hit count condition"
|
||||
/>
|
||||
</label>
|
||||
<Checkbox
|
||||
checked={!!bp.logHit}
|
||||
onChange={(on) => updateBreakpoint(path, bp.id, { logHit: on || undefined })}
|
||||
label={'"Breakpoint hit" message'}
|
||||
/>
|
||||
<Checkbox
|
||||
checked={logEval}
|
||||
onChange={(on) => {
|
||||
setLogEval(on);
|
||||
draft.current = { ...draft.current, logEval: on };
|
||||
commitText();
|
||||
}}
|
||||
label="Evaluate and log"
|
||||
/>
|
||||
{logEval && (
|
||||
<Input
|
||||
mono
|
||||
value={logMessage}
|
||||
onChange={(e) => setLogMessage(e.target.value)}
|
||||
onBlur={commitText}
|
||||
onKeyDown={onKey}
|
||||
placeholder="Value: {expression}"
|
||||
data-autofocus={focus === "log" ? "" : undefined}
|
||||
aria-label="Evaluate and log"
|
||||
<fieldset className={styles.bpActions}>
|
||||
<legend>
|
||||
<T>Actions</T>
|
||||
</legend>
|
||||
<Checkbox
|
||||
checked={!!bp.logHit}
|
||||
onChange={(on) => updateBreakpoint(path, bp.id, { logHit: on || undefined })}
|
||||
label={'"Breakpoint hit" message'}
|
||||
/>
|
||||
)}
|
||||
<Checkbox
|
||||
checked={logEval}
|
||||
onChange={(on) => {
|
||||
setLogEval(on);
|
||||
draft.current = { ...draft.current, logEval: on };
|
||||
commitText();
|
||||
}}
|
||||
label="Evaluate and log"
|
||||
/>
|
||||
{logEval && (
|
||||
<Input
|
||||
mono
|
||||
value={logMessage}
|
||||
onChange={(e) => setLogMessage(e.target.value)}
|
||||
onBlur={commitText}
|
||||
onKeyDown={onKey}
|
||||
placeholder="Value: {expression}"
|
||||
data-autofocus={focus === "log" ? "" : undefined}
|
||||
aria-label="Evaluate and log"
|
||||
/>
|
||||
)}
|
||||
{showRemoveOnceHit && (
|
||||
<Checkbox
|
||||
checked={!!bp.temporary}
|
||||
onChange={(temporary) => updateBreakpoint(path, bp.id, { temporary })}
|
||||
label="Remove once hit"
|
||||
/>
|
||||
)}
|
||||
</fieldset>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -771,12 +785,7 @@ function BreakpointDetail({
|
||||
</Button>
|
||||
</div>
|
||||
{st && <div className={styles.statusLine}>{st.verified ? tx("Verified") : (st.message ?? "Not verified")}</div>}
|
||||
<BreakpointFields path={path} bp={bp} commitRef={commitRef} />
|
||||
<Checkbox
|
||||
checked={!!bp.temporary}
|
||||
onChange={(temporary) => updateBreakpoint(path, bp.id, { temporary })}
|
||||
label="Remove once hit"
|
||||
/>
|
||||
<BreakpointFields path={path} bp={bp} commitRef={commitRef} showRemoveOnceHit />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
min-width: min(8ch, 45%);
|
||||
/* Cap the automatic flex minimum at the space needed for a short preview. */
|
||||
width: min(14ch, 50%);
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
@@ -135,9 +136,8 @@
|
||||
}
|
||||
|
||||
.type {
|
||||
min-width: 0;
|
||||
max-width: 25%;
|
||||
flex: 0 1 auto;
|
||||
min-width: min(3ch, 10%);
|
||||
flex: 0 4 auto;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-subtle);
|
||||
|
||||
@@ -507,7 +507,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
{config.kind === "tomcat" ? (
|
||||
<TomcatSettings config={config} onChange={onChange} />
|
||||
) : (
|
||||
<>
|
||||
<div className={styles.formSettings}>
|
||||
{!noProcess && (
|
||||
<Field
|
||||
label="Run on"
|
||||
@@ -860,7 +860,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -143,7 +143,10 @@ export function foldRows(
|
||||
const fold: Fold = { start: i, count: j - i, id: lines[i]!.id, expanded: expanded.has(lines[i]!.id) };
|
||||
const prev = rows[rows.length - 1];
|
||||
if (prev?.kind === "line") prev.fold = fold;
|
||||
else if (!fold.expanded) rows.push({ kind: "fold", fold });
|
||||
else if (fold.expanded) {
|
||||
rows.push({ kind: "line", index: i, fold });
|
||||
i++;
|
||||
} else rows.push({ kind: "fold", fold });
|
||||
if (fold.expanded) for (; i < j; i++) rows.push({ kind: "line", index: i });
|
||||
i = j;
|
||||
continue;
|
||||
@@ -230,7 +233,7 @@ export function ConsoleView({
|
||||
// Pending input continues the open line (a prompt), or starts a row of its own.
|
||||
const lastRow = folded[folded.length - 1];
|
||||
const inputInline =
|
||||
!!input && !!model.openLine && lastRow?.kind === "line" && !lastRow.fold && lines[lastRow.index] === model.openLine;
|
||||
!!input && !!model.openLine && lastRow?.kind === "line" && lines[lastRow.index] === model.openLine;
|
||||
const inputRow = !!input && !inputInline;
|
||||
const [widest] = useState(() => new WidestColumns());
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- `version` marks in-place appends to `lines`
|
||||
@@ -255,7 +258,7 @@ export function ConsoleView({
|
||||
getItemKey: (i) => {
|
||||
const r = rows[i];
|
||||
if (!r) return "input";
|
||||
return r.kind === "fold" ? `f${r.fold.id}` : (lines[r.index]?.id ?? i);
|
||||
return r.kind === "fold" ? r.fold.id : (lines[r.index]?.id ?? i);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -486,7 +489,7 @@ export function ConsoleView({
|
||||
return;
|
||||
}
|
||||
if (copySelectionOnKeyDown(e, selectedOutput)) return;
|
||||
if (!input) return;
|
||||
if (!input || e.target instanceof HTMLButtonElement) return;
|
||||
if (e.key === "d" && e.ctrlKey && !e.metaKey && !e.altKey) {
|
||||
e.preventDefault();
|
||||
input.onEof();
|
||||
@@ -523,19 +526,24 @@ export function ConsoleView({
|
||||
const foldButton = (fold: Fold, attached: boolean) =>
|
||||
fold.expanded ? (
|
||||
<button
|
||||
key={fold.id}
|
||||
type="button"
|
||||
className={styles.foldToggle}
|
||||
style={{ height: rowHeight }}
|
||||
title={tx("Collapse folded lines")}
|
||||
aria-label={tx("Collapse folded lines")}
|
||||
aria-expanded={true}
|
||||
onClick={() => toggleFold(fold.id)}
|
||||
>
|
||||
<Icon name="chevron-up" size={10} />
|
||||
<Icon name="chevron-down" size={10} />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
key={fold.id}
|
||||
type="button"
|
||||
className={styles.fold}
|
||||
title={tx("Expand folded lines")}
|
||||
aria-expanded={false}
|
||||
onClick={() => toggleFold(fold.id)}
|
||||
>
|
||||
{`${attached ? " " : ""}${fold.count === 1 ? tx`<${fold.count} internal line>` : tx`<${fold.count} internal lines>`}`}
|
||||
@@ -651,6 +659,7 @@ export function ConsoleView({
|
||||
className={clsx(styles.line, styles[line.kind])}
|
||||
style={{ ...rowStyle(item.start), color, background: ruled?.line?.bg }}
|
||||
>
|
||||
{row.fold?.expanded && foldButton(row.fold, false)}
|
||||
<Line
|
||||
line={line}
|
||||
marks={marksByLine.get(row.index)}
|
||||
@@ -658,7 +667,7 @@ export function ConsoleView({
|
||||
length={line.text.length}
|
||||
cwd={cwd}
|
||||
/>
|
||||
{row.fold && foldButton(row.fold, true)}
|
||||
{row.fold && !row.fold.expanded && foldButton(row.fold, true)}
|
||||
{inputInline && item.index === rows.length - 1 && pendingInput}
|
||||
{"\n"}
|
||||
</div>
|
||||
|
||||
@@ -212,7 +212,7 @@
|
||||
top: 0;
|
||||
left: 0;
|
||||
min-width: 100%;
|
||||
padding: 0 12px;
|
||||
padding: 0 var(--space-3);
|
||||
line-height: inherit;
|
||||
white-space: pre;
|
||||
tab-size: 4;
|
||||
@@ -258,12 +258,12 @@
|
||||
.testStatusBar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
min-height: 28px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.testToolbar {
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1);
|
||||
padding: var(--space-0-5) var(--space-1);
|
||||
}
|
||||
@@ -275,27 +275,36 @@
|
||||
border-inline-end: 1px solid var(--border);
|
||||
}
|
||||
.testStatusBar {
|
||||
gap: var(--space-0-5) var(--space-2);
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-0-5) var(--space-2);
|
||||
border-block-end-width: var(--space-0-5);
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.testStatusBar[data-outcome="passed"] {
|
||||
border-block-end-color: var(--success);
|
||||
}
|
||||
.testStatusBar[data-outcome="skipped"] {
|
||||
border-block-end-color: var(--warning);
|
||||
}
|
||||
.testStatusBar[data-running] {
|
||||
border-block-end-color: var(--accent);
|
||||
}
|
||||
.testStatusBar[data-outcome="failed"] {
|
||||
border-block-end-color: var(--danger);
|
||||
}
|
||||
.testCounts {
|
||||
flex: 1 1 auto;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-0-5) var(--space-2);
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.testStatus,
|
||||
.testTotalDuration {
|
||||
.testStatus {
|
||||
flex: none;
|
||||
}
|
||||
.testTotalDuration {
|
||||
margin-left: auto;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.testTree {
|
||||
@@ -665,22 +674,39 @@
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.configFields {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-columns: fit-content(40%) minmax(0, 1fr);
|
||||
grid-template-rows: [notice] auto [header] auto [options] minmax(0, 1fr);
|
||||
column-gap: var(--space-3);
|
||||
row-gap: var(--space-2);
|
||||
align-content: start;
|
||||
min-width: 0;
|
||||
}
|
||||
.configFields > * {
|
||||
.configFields > *,
|
||||
.formSettings > * {
|
||||
grid-column: 1 / -1;
|
||||
min-width: 0;
|
||||
}
|
||||
.configFields:not(.configFieldsTomcat) > .field,
|
||||
.configFields > .notice {
|
||||
grid-row: notice;
|
||||
}
|
||||
.configFields:not(.configFieldsTomcat) > .notice,
|
||||
.configFields:not(.configFieldsTomcat) > .formHeader {
|
||||
margin-bottom: var(--space-2);
|
||||
}
|
||||
.configFields:not(.configFieldsTomcat) > .formHeader,
|
||||
.configFields:not(.configFieldsTomcat) > .formHeader > .field {
|
||||
.configFields:not(.configFieldsTomcat) > .formHeader > .field,
|
||||
.formSettings > .field {
|
||||
grid-template-columns: subgrid;
|
||||
}
|
||||
.formSettings {
|
||||
display: grid;
|
||||
grid-row: options;
|
||||
grid-template-columns: subgrid;
|
||||
row-gap: var(--space-2);
|
||||
align-content: start;
|
||||
overflow: auto;
|
||||
}
|
||||
.formHeader > .field {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
@@ -688,8 +714,6 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
.configFieldsTomcat {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
@@ -793,6 +817,7 @@
|
||||
}
|
||||
.formHeader {
|
||||
display: grid;
|
||||
grid-row: header;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
@@ -1118,15 +1143,19 @@
|
||||
color: var(--fg);
|
||||
}
|
||||
.foldToggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin-left: 6px;
|
||||
padding: 0 2px;
|
||||
position: sticky;
|
||||
inset-inline-start: 0;
|
||||
z-index: 1;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: var(--space-3);
|
||||
margin-inline-start: calc(-1 * var(--space-3));
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 3px;
|
||||
background: none;
|
||||
border-radius: var(--radius-small);
|
||||
background: var(--bg-app);
|
||||
color: var(--fg-faint);
|
||||
vertical-align: middle;
|
||||
vertical-align: top;
|
||||
cursor: pointer;
|
||||
}
|
||||
.foldToggle:hover {
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
Icon,
|
||||
IconButton,
|
||||
Menu,
|
||||
type MenuItem,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
@@ -100,21 +101,33 @@ export function SessionPanel({
|
||||
const [selectedTest, setSelectedTest] = useState<string | null>(null);
|
||||
const [findOpen, setFindOpen] = useState(false);
|
||||
const body = useRef<HTMLDivElement>(null);
|
||||
const moreButton = useRef<HTMLButtonElement>(null);
|
||||
const [moreOpen, setMoreOpen] = useState(false);
|
||||
const [compactToolbar, setCompactToolbar] = useState(false);
|
||||
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 hasRuntime = !!rt;
|
||||
const hasTests = !!rt?.tests;
|
||||
const canUpdateApplication = isUpdatable(session.config);
|
||||
const hasFlutterActions = supportsHotReload(session.config);
|
||||
// Eight standard buttons with group spacing and insets, then 24 px plus gap per extra button.
|
||||
const fullToolbarWidth = 228 + 26 * (Number(hasTests) + Number(canUpdateApplication) + 2 * Number(hasFlutterActions));
|
||||
useLayoutEffect(() => {
|
||||
const pane = body.current;
|
||||
if (!hasTests || !pane) return;
|
||||
const measure = () => setStackedTests(pane.clientWidth < 560);
|
||||
if (!hasRuntime || !pane || (!showLifecycle && !hasTests)) return;
|
||||
const measure = () => {
|
||||
const width = pane.clientWidth;
|
||||
if (showLifecycle) setCompactToolbar(width < fullToolbarWidth);
|
||||
if (hasTests) setStackedTests(width < 560);
|
||||
};
|
||||
measure();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const resize = new ResizeObserver(measure);
|
||||
resize.observe(pane);
|
||||
return () => resize.disconnect();
|
||||
}, [hasTests]);
|
||||
}, [hasRuntime, hasTests, showLifecycle, fullToolbarWidth]);
|
||||
useLayoutEffect(() => {
|
||||
if (hasTests) testSplit.current?.setLayout(testLayouts.current[testOrientation]);
|
||||
}, [hasTests, testOrientation]);
|
||||
@@ -157,7 +170,24 @@ export function SessionPanel({
|
||||
}, [selectedTest, rt, version]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
if (!rt) return null;
|
||||
const toggleWrap = () => setWrapOverride(!softWrap);
|
||||
const overflowConsoleToggles = showLifecycle && compactToolbar && !rt.terminal;
|
||||
const consoleToggles = [
|
||||
{ label: "Scroll to End", icon: "scroll-to-end", checked: follow, run: () => setFollow((v) => !v) },
|
||||
{ label: "Soft-Wrap", icon: "soft-wrap", checked: softWrap, run: () => setWrapOverride(!softWrap) },
|
||||
];
|
||||
const moreItems: MenuItem[] = [{ kind: "action", action: "run.editConfigs", arg: session.config.id }];
|
||||
if (overflowConsoleToggles) {
|
||||
moreItems.unshift(...consoleToggles, { kind: "separator" });
|
||||
}
|
||||
const stopButton = (
|
||||
<IconButton
|
||||
icon="stop"
|
||||
title={session.status === "stopping" ? tx`Stopping… (click to kill)` : "Stop"}
|
||||
tone={running ? "danger" : "default"}
|
||||
disabled={!running}
|
||||
onClick={() => void stopSession(session.id)}
|
||||
/>
|
||||
);
|
||||
|
||||
const consoleColumn = (
|
||||
<div className={styles.consoleColumn}>
|
||||
@@ -223,6 +253,7 @@ export function SessionPanel({
|
||||
shortcut={shortcutLabel("run.rerun")}
|
||||
onClick={() => rerunSession(session.id)}
|
||||
/>
|
||||
{!hasFlutterActions && stopButton}
|
||||
{/* Switch the launch mode: the same configuration started under the debugger. */}
|
||||
<IconButton
|
||||
icon="debug"
|
||||
@@ -240,14 +271,7 @@ export function SessionPanel({
|
||||
onClick={() => void rerunFailed(session.id)}
|
||||
/>
|
||||
)}
|
||||
<IconButton
|
||||
icon="stop"
|
||||
title={session.status === "stopping" ? tx`Stopping… (click to kill)` : "Stop"}
|
||||
tone={running ? "danger" : "default"}
|
||||
disabled={!running}
|
||||
onClick={() => void stopSession(session.id)}
|
||||
/>
|
||||
{isUpdatable(session.config) && (
|
||||
{canUpdateApplication && (
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
title="Update Application"
|
||||
@@ -256,8 +280,9 @@ export function SessionPanel({
|
||||
onClick={() => showApplicationUpdate(session.id)}
|
||||
/>
|
||||
)}
|
||||
{supportsHotReload(session.config) && (
|
||||
{hasFlutterActions && (
|
||||
<>
|
||||
{stopButton}
|
||||
<IconButton
|
||||
icon="hot-reload"
|
||||
title="Hot Reload"
|
||||
@@ -286,23 +311,41 @@ export function SessionPanel({
|
||||
pressed={findOpen}
|
||||
onClick={() => setFindOpen((v) => !v)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="scroll-to-end"
|
||||
title="Scroll to End"
|
||||
pressed={follow}
|
||||
onClick={() => setFollow((v) => !v)}
|
||||
/>
|
||||
<IconButton icon="soft-wrap" title="Soft-Wrap" pressed={softWrap} onClick={toggleWrap} />
|
||||
{!overflowConsoleToggles &&
|
||||
consoleToggles.map(({ label, icon, checked, run }) => (
|
||||
<IconButton key={label} icon={icon} title={label} pressed={checked} onClick={run} />
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
<IconButton icon="trash" title="Clear All" onClick={() => clearConsole(session.id)} />
|
||||
</div>
|
||||
<div className={styles.toolbarGroup}>
|
||||
<IconButton
|
||||
icon="settings"
|
||||
title="Edit Configurations…"
|
||||
onClick={() => void executeAction("run.editConfigs", session.config.id)}
|
||||
/>
|
||||
{showLifecycle ? (
|
||||
<>
|
||||
<IconButton
|
||||
ref={moreButton}
|
||||
icon="more-horizontal"
|
||||
title="More Actions"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={moreOpen}
|
||||
onClick={() => setMoreOpen((open) => !open)}
|
||||
/>
|
||||
<Menu
|
||||
open={moreOpen}
|
||||
anchor={moreButton}
|
||||
aria-label="More Actions"
|
||||
placement="bottom-end"
|
||||
items={moreItems}
|
||||
onClose={() => setMoreOpen(false)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<IconButton
|
||||
icon="settings"
|
||||
title="Edit Configurations…"
|
||||
onClick={() => void executeAction("run.editConfigs", session.config.id)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div ref={body} className={styles.sessionBody}>
|
||||
|
||||
@@ -112,27 +112,24 @@ export function TestStatusBar({
|
||||
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 outcome = 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} />
|
||||
<div
|
||||
className={styles.testStatusBar}
|
||||
role="status"
|
||||
data-running={running || undefined}
|
||||
data-outcome={outcome ?? undefined}
|
||||
>
|
||||
<StatusIcon status={running ? "running" : outcome} />
|
||||
<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>}
|
||||
{!outcome && <span className={styles.skipped}>{running ? tx("Running…") : tx("No tests")}</span>}
|
||||
{duration !== undefined && <span className={styles.testTotalDuration}>{formatDuration(duration)}</span>}
|
||||
</span>
|
||||
{duration !== undefined && <span className={styles.testTotalDuration}>{formatDuration(duration)}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -221,6 +221,8 @@ export function testBasesFor(relPath: string, configs: RunConfig[], content?: st
|
||||
// Configurations produced from a test or file are results of narrowing, never bases for it.
|
||||
const candidates = configs
|
||||
.filter((c) => c.isTest && kinds.includes(c.kind) && !c.id.startsWith("context:"))
|
||||
// `node` configurations run a file of their own; only Playwright's (`npx playwright test`) take a test file.
|
||||
.filter((c) => c.kind !== "node" || frameworkFor(c) === "playwright")
|
||||
.sort((a, b) => kinds.indexOf(a.kind) - kinds.indexOf(b.kind));
|
||||
const best = allClosest(candidates, relPath);
|
||||
if (best.length) return content === undefined ? best : byRunner(best, content);
|
||||
|
||||
@@ -32,7 +32,15 @@ import { firstTopLevelType, scanJvmTargets, simpleClassName } from "./jvmTargets
|
||||
import { isWindows } from "./jvmTypes";
|
||||
import { inheritedRunTargets } from "./inheritedMain";
|
||||
import { withMavenTests } from "./mavenTests";
|
||||
import { detectRunTargets, goFuzzConfig, targetConfig, targetLanguage, zigTargets, type RunTarget } from "./targets";
|
||||
import {
|
||||
detectRunTargets,
|
||||
goFuzzConfig,
|
||||
targetConfig,
|
||||
targetLanguage,
|
||||
testsInTestDirectory,
|
||||
zigTargets,
|
||||
type RunTarget,
|
||||
} from "./targets";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
export interface LocatedTool {
|
||||
@@ -1137,7 +1145,7 @@ export function fileTargets(
|
||||
(t) => t.kind === "main" && (!t.className || /\.(java|kt)$/.test(input.path)),
|
||||
);
|
||||
}
|
||||
const targets = detectRunTargets(content, s.rel, hasDjangoTests(input.configs));
|
||||
const targets = detectRunTargets(content, s.rel, hasDjangoTests(input.configs), testsInTestDirectory(input.configs));
|
||||
return /\.java$/.test(input.path) ? [...targets, ...inheritedRunTargets(input.path, content)] : targets;
|
||||
}
|
||||
|
||||
|
||||
@@ -352,10 +352,6 @@ function jvmTargets(lines: string[], relPath: string): RunTarget[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run targets of a file (relative path picks the language). `django`: a Django project, where
|
||||
* `tests.py` (Django's default test module) holds tests too.
|
||||
*/
|
||||
/** Zig: a top-level `pub fn main` and `test "name" {` / `test name {` blocks, nested ones too. */
|
||||
export function zigTargets(content: string): RunTarget[] {
|
||||
if (content.length > MAX_SCAN) return [];
|
||||
@@ -372,7 +368,17 @@ export function zigTargets(content: string): RunTarget[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
export function detectRunTargets(text: string, relPath: string, django = false): RunTarget[] {
|
||||
/** Whether the project tests with Mocha or `node --test`, which look in `test/` by default, whatever a file's name. */
|
||||
export function testsInTestDirectory(configs: readonly RunConfig[]): boolean {
|
||||
return configs.some((c) => c.isTest && ["mocha", "node-test"].includes(frameworkFor(c)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Run targets of a file (relative path picks the language). `django`: a Django project, where
|
||||
* `tests.py` (Django's default test module) holds tests too. `testDirectory`: JS files in `test/`
|
||||
* hold tests whatever their name (`testsInTestDirectory`).
|
||||
*/
|
||||
export function detectRunTargets(text: string, relPath: string, django = false, testDirectory = false): RunTarget[] {
|
||||
if (text.length > MAX_SCAN) return [];
|
||||
const lines = text.split("\n");
|
||||
switch (targetLanguage(relPath)) {
|
||||
@@ -381,8 +387,10 @@ export function detectRunTargets(text: string, relPath: string, django = false):
|
||||
case "rust":
|
||||
return rustTargets(lines, relPath);
|
||||
case "js":
|
||||
// `test/`: where Mocha (and `node --test`) look for tests by default, whatever the file's name.
|
||||
return /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)(__tests__|test)\//.test(relPath) ? jsTargets(lines) : [];
|
||||
return /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)__tests__\//.test(relPath) ||
|
||||
(testDirectory && /(^|\/)test\//.test(relPath))
|
||||
? jsTargets(lines)
|
||||
: [];
|
||||
case "python":
|
||||
return pythonTargets(lines).filter(
|
||||
(t) =>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { detectRunTargets, targetConfig } from "../targets";
|
||||
import { detectRunTargets, targetConfig, testsInTestDirectory } from "../targets";
|
||||
import { createTestParser, frameworkFor, nodeOutput, parseAll, TestResults, withTestReporting } from "./index";
|
||||
import { failedTestPaths, rerunFailedConfigs } from "./rerun";
|
||||
|
||||
@@ -95,18 +95,28 @@ describe("Mocha gutter targets", () => {
|
||||
"});",
|
||||
].join("\n");
|
||||
|
||||
it("are found in test/ whatever the file's name, `specify` included", () => {
|
||||
expect(detectRunTargets(src, "test/pricing.js").map((t) => [t.line, t.kind, t.path.join("/")])).toEqual([
|
||||
it("are found in test/ whatever the file's name in Mocha projects, `specify` included", () => {
|
||||
expect(testsInTestDirectory([script])).toBe(true);
|
||||
expect(
|
||||
detectRunTargets(src, "test/pricing.js", false, true).map((t) => [t.line, t.kind, t.path.join("/")]),
|
||||
).toEqual([
|
||||
[0, "suite", "pricing"],
|
||||
[1, "test", "pricing/adds tax"],
|
||||
[2, "suite", "pricing/bulk"],
|
||||
[3, "test", "pricing/bulk/discounts"],
|
||||
]);
|
||||
expect(detectRunTargets(src, "lib/pricing.js")).toEqual([]);
|
||||
expect(detectRunTargets(src, "lib/pricing.js", false, true)).toEqual([]);
|
||||
});
|
||||
|
||||
it("are not looked for in test/ of a Jest or Vitest project", () => {
|
||||
const vitest = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"] });
|
||||
expect(testsInTestDirectory([vitest])).toBe(false);
|
||||
expect(detectRunTargets(src, "test/pricing.js")).toEqual([]);
|
||||
expect(detectRunTargets(src, "test/pricing.test.js")).toHaveLength(4);
|
||||
});
|
||||
|
||||
it("run by file and full title", () => {
|
||||
const targets = detectRunTargets(src, "test/pricing.js");
|
||||
const targets = detectRunTargets(src, "test/pricing.js", false, true);
|
||||
expect(targetConfig(targets[3]!, "test/pricing.js", [script], src)?.args).toEqual([
|
||||
"run",
|
||||
"test",
|
||||
|
||||
@@ -203,6 +203,12 @@ describe("Playwright gutter targets", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("take node test configurations as bases only when they run Playwright", () => {
|
||||
// Jest as imported from JetBrains (`npx jest`): not a base for gutter runs, as before.
|
||||
const jest = cfg({ id: "jest", kind: "node", command: "npx", args: ["jest"] });
|
||||
expect(testBasesFor("src/cart.test.ts", [jest], "test('adds', () => {});")).toEqual([]);
|
||||
expect(testBasesFor("e2e/cart.spec.ts", [jest, npx], spec).map((c) => c.id)).toEqual(["playwright"]);
|
||||
});
|
||||
it("send specs to Playwright and other tests to the project's other runner", () => {
|
||||
const vitest = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"] });
|
||||
const configs = [vitest, npx];
|
||||
|
||||
@@ -162,8 +162,8 @@
|
||||
}
|
||||
.outdated .rowText,
|
||||
.outdated .rowText *,
|
||||
.outdated .rowFile,
|
||||
.outdated .rowFile * {
|
||||
.outdated .rowLocation,
|
||||
.outdated .rowLocation * {
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
.rowText {
|
||||
@@ -174,18 +174,28 @@
|
||||
font-family: var(--font-mono);
|
||||
font-weight: var(--fw-code);
|
||||
}
|
||||
.rowFile {
|
||||
.rowLocation {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: var(--space-1-5);
|
||||
max-width: 40%;
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.rowLocationActive {
|
||||
color: var(--fg-emphasis);
|
||||
}
|
||||
.rowFile {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.rowFileActive {
|
||||
.rowFileRepeated {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.rowLine {
|
||||
color: var(--fg-faint);
|
||||
flex: none;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.previewHeader {
|
||||
|
||||
@@ -622,6 +622,7 @@ function FindInFilesDialog() {
|
||||
}
|
||||
renderItem={(r, st) => {
|
||||
const state = s.replace ? groupState(r, marks) : "pending";
|
||||
const repeatedFile = !st.active && rows[st.index - 1]?.path === r.path;
|
||||
return (
|
||||
<>
|
||||
<span
|
||||
@@ -637,13 +638,20 @@ function FindInFilesDialog() {
|
||||
source={{ path: r.path, line: r.line, col: r.textCol }}
|
||||
/>
|
||||
</span>
|
||||
<span className={clsx(styles.rowFile, st.active && styles.rowFileActive)}>
|
||||
{state === "done" && (
|
||||
<span className={styles.rowLine}>
|
||||
<T>replaced ·</T>{" "}
|
||||
</span>
|
||||
)}
|
||||
{workspace ? r.relPath : basename(r.relPath)} <span className={styles.rowLine}>{r.line + 1}</span>
|
||||
<span className={clsx(styles.rowLocation, st.active && styles.rowLocationActive)}>
|
||||
<span
|
||||
className={clsx(styles.rowFile, repeatedFile && styles.rowFileRepeated)}
|
||||
title={r.relPath}
|
||||
dir="auto"
|
||||
>
|
||||
{state === "done" && (
|
||||
<>
|
||||
<T>replaced ·</T>{" "}
|
||||
</>
|
||||
)}
|
||||
{workspace ? r.relPath : basename(r.relPath)}
|
||||
</span>{" "}
|
||||
<span className={styles.rowLine}>{r.line + 1}</span>
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -15,6 +15,7 @@ import { call, commands, type OutlineItem } from "@/platform/ipc";
|
||||
import { monoFontFamily } from "@/platform/fonts";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { isVirtualUri, virtualContainer } from "@/platform/virtualDocs";
|
||||
import {
|
||||
Checkbox,
|
||||
Dialog,
|
||||
@@ -40,7 +41,7 @@ import {
|
||||
type ToolWindowContribution,
|
||||
} from "@/workbench/contributions";
|
||||
import { highlightTokens, languageForPath, type CodeToken } from "@/editor/lsp/markdown";
|
||||
import { basename, openInListOrder, openLocation } from "../common/open";
|
||||
import { basename, openInListOrder, openLocation, relDir } from "../common/open";
|
||||
import { outlinePathAt } from "../structure/outline";
|
||||
import { fromNavigationHistory, isDismissed, mergeLocations, type RecentLocation } from "../common/locations";
|
||||
import { dismissLocation, useTracking } from "../common/tracking";
|
||||
@@ -688,33 +689,39 @@ function RecentLocationsDialog() {
|
||||
rowHeight={rowHeight}
|
||||
aria-label="Recent locations"
|
||||
empty={<span>{changedOnly ? tx("No changed locations") : tx("No recent locations")}</span>}
|
||||
renderItem={(l) => (
|
||||
<div className={styles.location}>
|
||||
<div className={styles.locationHeader}>
|
||||
<Icon name={fileIconName(basename(l.rel), l.rel)} size={14} className={styles.icon} />
|
||||
<HighlightedText
|
||||
className={clsx(styles.name, styles.locationName)}
|
||||
text={basename(l.rel)}
|
||||
indices={l.nameIndices}
|
||||
tone="strong"
|
||||
renderItem={(l) => {
|
||||
const name = basename(l.rel);
|
||||
const breadcrumb = breadcrumbOf(outlines.get(l.path), l);
|
||||
const directory = isVirtualUri(l.path) ? virtualContainer(l.path) : relDir(l.rel);
|
||||
const context = breadcrumb && breadcrumb !== name ? breadcrumb : directory;
|
||||
return (
|
||||
<div className={styles.location}>
|
||||
<div className={styles.locationHeader} title={l.rel}>
|
||||
<Icon name={fileIconName(name, l.rel)} size={14} className={styles.icon} />
|
||||
<HighlightedText
|
||||
className={clsx(styles.name, styles.locationName)}
|
||||
text={name}
|
||||
indices={l.nameIndices}
|
||||
tone="strong"
|
||||
/>
|
||||
{context && <span className={styles.dir}>{context}</span>}
|
||||
{l.changed && (
|
||||
<span className={styles.changed}>
|
||||
<T>changed</T>
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.time}>{locationTime(l.time, now)}</span>
|
||||
</div>
|
||||
<SnippetCode
|
||||
path={l.path}
|
||||
lines={dedent(l.snippet)}
|
||||
first={l.snippetStart}
|
||||
caret={l.line}
|
||||
style={snippetStyle}
|
||||
/>
|
||||
<span className={styles.dir}>{breadcrumbOf(outlines.get(l.path), l) || l.rel}</span>
|
||||
{l.changed && (
|
||||
<span className={styles.changed}>
|
||||
<T>changed</T>
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.time}>{locationTime(l.time, now)}</span>
|
||||
</div>
|
||||
<SnippetCode
|
||||
path={l.path}
|
||||
lines={dedent(l.snippet)}
|
||||
first={l.snippetStart}
|
||||
caret={l.line}
|
||||
style={snippetStyle}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Dialog>
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { act, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { Dialog } from "@/ui";
|
||||
import { ColorSwatches } from "../components/Form";
|
||||
import { useSetting } from "../components/context";
|
||||
import { ACCENT_PRESETS, validateSettings } from "../model/schema";
|
||||
import { applySettings, closeSettings, useSettingsDialog } from "../model/staging";
|
||||
|
||||
const saved = useSettingsDialog.getState();
|
||||
const savedSettings = useProject.getState().settings;
|
||||
afterEach(() => {
|
||||
useSettingsDialog.setState(saved);
|
||||
useProject.setState({ settings: savedSettings });
|
||||
localStorage.removeItem("openidea.colorPicker.recent.v1");
|
||||
});
|
||||
|
||||
function Accent() {
|
||||
const [value, setValue] = useSetting<string>("appearance.accent");
|
||||
return <ColorSwatches value={value} onChange={setValue} presets={ACCENT_PRESETS} useColorPicker />;
|
||||
}
|
||||
|
||||
it("stages opaque accent colors and persists them only through Settings Apply", async () => {
|
||||
const base = validateSettings({ appearance: { accent: "#abc" } });
|
||||
useSettingsDialog.setState({ base, globalBase: base, staged: {}, open: true });
|
||||
const dismissSettings = vi.fn();
|
||||
render(
|
||||
<Dialog open title="Settings" onClose={dismissSettings}>
|
||||
<Accent />
|
||||
</Dialog>,
|
||||
);
|
||||
const staged = () => useSettingsDialog.getState().staged["global|appearance.accent"]?.value;
|
||||
const trigger = screen.getByRole("button", { name: "Custom colour #abc" });
|
||||
expect(trigger).toHaveAttribute("aria-pressed", "true");
|
||||
fireEvent.click(trigger);
|
||||
const picker = within(screen.getByRole("dialog", { name: "Color picker" }));
|
||||
const hex = picker.getByRole("textbox", { name: "Hexadecimal" });
|
||||
expect(hex).toHaveValue("AABBCC");
|
||||
expect(picker.queryByRole("textbox", { name: "Alpha percent" })).toBeNull();
|
||||
fireEvent.change(hex, { target: { value: "1234567" } });
|
||||
fireEvent.blur(hex);
|
||||
fireEvent.submit(hex.closest("form")!);
|
||||
expect(hex).toHaveAttribute("aria-invalid", "true");
|
||||
expect(staged()).toBeUndefined();
|
||||
fireEvent.change(picker.getByRole("textbox", { name: "Red" }), { target: { value: "12" } });
|
||||
fireEvent.change(hex, { target: { value: "#DeF" } });
|
||||
fireEvent.keyDown(hex, { key: "Escape" });
|
||||
expect(staged()).toBeUndefined();
|
||||
expect(dismissSettings).not.toHaveBeenCalled();
|
||||
expect(trigger).toHaveFocus();
|
||||
fireEvent.click(trigger);
|
||||
fireEvent.change(pickerFor("Hexadecimal"), { target: { value: "#DeF" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
|
||||
expect(staged()).toBe("#ddeeff");
|
||||
expect(trigger).toHaveAccessibleName("Custom colour #ddeeff");
|
||||
const set = vi.fn(async () => validateSettings({ appearance: { accent: "#ddeeff" } }));
|
||||
expect(set).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
expect(await applySettings({ backend: true, set, setSecret: async () => {}, reload: async () => {} })).toBe(true);
|
||||
});
|
||||
expect(set).toHaveBeenCalledWith("global", "appearance.accent", JSON.stringify("#ddeeff"));
|
||||
fireEvent.click(trigger);
|
||||
expect(pickerFor("Hexadecimal")).toHaveValue("DDEEFF");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Teal" }));
|
||||
expect(staged()).toBe("#24a394");
|
||||
act(closeSettings);
|
||||
expect(staged()).toBeUndefined();
|
||||
});
|
||||
|
||||
function pickerFor(name: string) {
|
||||
return within(screen.getByRole("dialog", { name: "Color picker" })).getByRole("textbox", { name });
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { CLEAR_COLOR, _setSchemeSource } from "@/platform/colorScheme";
|
||||
import { CLEAR_COLOR, _setSchemeSource, resolvedAttribute } from "@/platform/colorScheme";
|
||||
import { setLocale } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { DEFAULT_SETTINGS } from "../model/schema";
|
||||
@@ -430,33 +430,38 @@ describe("Console Colors (#2698)", () => {
|
||||
});
|
||||
|
||||
describe("Diff & Merge colors", () => {
|
||||
it("groups change types and the folded wave, and overrides the stripe from the preview", () => {
|
||||
// The three-pane preview is registered by the VCS feature's editor kind, absent in this
|
||||
// isolated settings test, so drive the attribute tree directly.
|
||||
const expand = (tree: HTMLElement, group: string) => {
|
||||
const row = within(tree).getByRole("treeitem", { name: group });
|
||||
act(() => fireEvent.mouseDown(within(row).getByText(group).previousElementSibling!, { button: 0 }));
|
||||
};
|
||||
|
||||
it("groups change types and the folded wave, and overrides the stripe", () => {
|
||||
act(() => stage("editor.colorScheme", "global", "editor.colorScheme", "dark"));
|
||||
schemePage("editor.colorScheme.diff-and-merge");
|
||||
const tree = screen.getByRole("tree", { name: "Color scheme attributes" });
|
||||
expect(within(tree).getByRole("treeitem", { name: "Changed lines" })).toBeInTheDocument();
|
||||
expect(within(tree).getByRole("treeitem", { name: "Folded unchanged fragments" })).toBeInTheDocument();
|
||||
// Change-type strips select their attribute; the stripe cell selects the same one.
|
||||
const preview = screen.getByLabelText("Color scheme preview");
|
||||
act(() => fireEvent.click(within(preview).getByText("def MyClass():")));
|
||||
expect(screen.getByRole("treeitem", { name: "Changed", selected: true })).toBeInTheDocument();
|
||||
expand(tree, "Changed lines");
|
||||
act(() => fireEvent.click(within(tree).getByRole("treeitem", { name: "Changed" })));
|
||||
act(() => fireEvent.click(screen.getByRole("checkbox", { name: "Error stripe mark" })));
|
||||
const stripe = screen.getByRole("textbox", { name: "Error stripe mark hex" });
|
||||
act(() => fireEvent.change(stripe, { target: { value: "#ff4081" } }));
|
||||
expect(value("colorOverrides")).toEqual({ dark: { diffChanged: { errorStripeColor: "#ff4081" } } });
|
||||
const preview = screen.getByLabelText("Color scheme preview");
|
||||
expect(preview.style.getPropertyValue("--diff-modified-stripe")).toBe("#ff4081");
|
||||
});
|
||||
|
||||
it("selects the wave attribute from the folded separator", () => {
|
||||
it("shows the wave default following the theme's subtle text", () => {
|
||||
_setSchemeSource(readFileSync("src/styles/tokens.css", "utf8"));
|
||||
try {
|
||||
// The default resolves from --fg-subtle, not a hardcoded IDEA colour.
|
||||
expect(resolvedAttribute("dark", "diffSeparatorWave").foreground).toBe("#73767c");
|
||||
act(() => stage("editor.colorScheme", "global", "editor.colorScheme", "dark"));
|
||||
schemePage("editor.colorScheme.diff-and-merge");
|
||||
const preview = screen.getByLabelText("Color scheme preview");
|
||||
act(() => fireEvent.click(within(preview).getByText("6 unchanged lines")));
|
||||
expect(screen.getByRole("treeitem", { name: "Wave", selected: true })).toBeInTheDocument();
|
||||
// The default follows the theme's subtle text rather than a hardcoded IDEA colour.
|
||||
expect(screen.getByRole("textbox", { name: "Foreground hex" })).toHaveValue("#73767c");
|
||||
const tree = screen.getByRole("tree", { name: "Color scheme attributes" });
|
||||
expect(within(tree).getByRole("treeitem", { name: "Folded unchanged fragments" })).toBeInTheDocument();
|
||||
} finally {
|
||||
_setSchemeSource("");
|
||||
}
|
||||
|
||||
@@ -184,6 +184,16 @@ describe("languages settings", () => {
|
||||
expect(v.prettier).toMatchObject({ runOnSave: true, prefer: false, path: "" });
|
||||
});
|
||||
|
||||
it("gives Biome the opt-in settings for the languages it formats", () => {
|
||||
expect(validateLanguages({}).biome).toEqual({
|
||||
...DEFAULT_LANGUAGES.prettier,
|
||||
languages: ["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"],
|
||||
});
|
||||
const v = validateLanguages({ biome: { languages: ["json"], prefer: true, runOnSave: true } });
|
||||
expect(v.biome).toMatchObject({ languages: ["json"], prefer: true, runOnSave: true });
|
||||
expect(v.prettier).toMatchObject({ prefer: false, runOnSave: false });
|
||||
});
|
||||
|
||||
it("enables Ruff for Python by default and keeps its settings separate", () => {
|
||||
expect(validateLanguages({}).ruff).toMatchObject({
|
||||
path: "",
|
||||
@@ -370,6 +380,7 @@ describe("language pages", () => {
|
||||
"PHP",
|
||||
"Prettier",
|
||||
"oxfmt",
|
||||
"Biome",
|
||||
"Ruby",
|
||||
"Rust",
|
||||
"TypeScript",
|
||||
|
||||
@@ -7,6 +7,8 @@ import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "rea
|
||||
import clsx from "clsx";
|
||||
import { Checkbox, IconButton, Input, Select as UiSelect, type SelectOption, T } from "@/ui";
|
||||
import { tx, useTx } from "@/platform/i18n";
|
||||
import { ColorPicker, rememberColor } from "@/ui/ColorPicker";
|
||||
import { fromOpaqueHex, toHex6 } from "@/ui/colorPickerValues";
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { highlightIndices } from "../model/pages";
|
||||
@@ -250,13 +252,23 @@ export interface ColorSwatchesProps {
|
||||
onChange: (value: string) => void;
|
||||
/** Offer a custom colour picker + hex field. */
|
||||
allowCustom?: boolean;
|
||||
useColorPicker?: boolean;
|
||||
"aria-label"?: string;
|
||||
}
|
||||
|
||||
export function ColorSwatches({ value, presets, onChange, allowCustom = true, ...aria }: ColorSwatchesProps) {
|
||||
export function ColorSwatches({
|
||||
value,
|
||||
presets,
|
||||
onChange,
|
||||
allowCustom = true,
|
||||
useColorPicker = false,
|
||||
...aria
|
||||
}: ColorSwatchesProps) {
|
||||
const current = value.toLowerCase();
|
||||
const isPreset = presets.some((p) => p.value.toLowerCase() === current);
|
||||
const [hex, setHex] = useState<string | null>(null);
|
||||
const [anchor, setAnchor] = useState<HTMLButtonElement | null>(null);
|
||||
const initial = useColorPicker ? fromOpaqueHex(value) : null;
|
||||
const hexText = hex ?? (isPreset ? "" : value);
|
||||
const hexInvalid = hex !== null && hex !== "" && !HEX_COLOR.test(hex);
|
||||
return (
|
||||
@@ -278,7 +290,41 @@ export function ColorSwatches({ value, presets, onChange, allowCustom = true, ..
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{allowCustom && (
|
||||
{allowCustom && initial && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(styles.swatch, styles.custom, !isPreset && styles.swatchOn)}
|
||||
aria-label={isPreset ? tx("Custom colour") : `${tx("Custom colour")} ${value}`}
|
||||
aria-pressed={!isPreset}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={!!anchor}
|
||||
title={tx("Custom colour")}
|
||||
onClick={(event) => {
|
||||
event.currentTarget.focus();
|
||||
setAnchor(anchor ? null : event.currentTarget);
|
||||
}}
|
||||
>
|
||||
<span className={styles.swatchColor} style={!isPreset ? { background: value } : undefined} />
|
||||
</button>
|
||||
{anchor && (
|
||||
<ColorPicker
|
||||
anchor={anchor}
|
||||
initial={initial}
|
||||
opaque
|
||||
onFinish={(commit, color) => {
|
||||
setAnchor(null);
|
||||
const next = toHex6(color);
|
||||
if (commit && next !== toHex6(initial)) {
|
||||
rememberColor(color);
|
||||
onChange(next);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{allowCustom && !useColorPicker && (
|
||||
<>
|
||||
<label
|
||||
className={clsx(styles.swatch, styles.custom, !isPreset && styles.swatchOn)}
|
||||
|
||||
@@ -101,19 +101,28 @@
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
}
|
||||
.crumb:last-child {
|
||||
.parentCrumbs {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
}
|
||||
.crumb > span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.crumb {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
.crumbLabel {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.currentCrumb {
|
||||
flex: none;
|
||||
max-width: 100%;
|
||||
}
|
||||
.crumbSep {
|
||||
margin: 0 4px;
|
||||
flex: none;
|
||||
margin-inline: var(--space-1);
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.reset {
|
||||
|
||||
@@ -165,21 +165,29 @@ function PageHost({
|
||||
const [headerSlot, setHeaderSlot] = useState<HTMLElement | null>(null);
|
||||
if (!node) return <EmptyState title="Nothing found" icon="search" />;
|
||||
const Body = page?.component;
|
||||
const parents = crumbs.slice(0, -1);
|
||||
return (
|
||||
<PageContext.Provider value={ctx}>
|
||||
<SettingsFormContext.Provider value={form}>
|
||||
<SettingsPageFocusContext.Provider value={pageFocus}>
|
||||
<SettingsHeaderSlotContext.Provider value={headerSlot}>
|
||||
<div className={styles.pageHeader}>
|
||||
<div className={styles.crumbs} aria-label={tx("Breadcrumb")}>
|
||||
{crumbs.map((c, i) => (
|
||||
<span key={i} className={styles.crumb}>
|
||||
{i > 0 && <Icon name="chevron-right" size={12} className={styles.crumbSep} />}
|
||||
<span>
|
||||
<T>{c}</T>
|
||||
</span>
|
||||
<div className={styles.crumbs} aria-label={tx("Breadcrumb")} title={crumbs.map((c) => tx(c)).join(" › ")}>
|
||||
{parents.length > 0 && (
|
||||
<span className={styles.parentCrumbs}>
|
||||
{parents.map((c, i) => (
|
||||
<span key={i} className={styles.crumb}>
|
||||
<span className={styles.crumbLabel}>
|
||||
<T>{c}</T>
|
||||
</span>
|
||||
<Icon name="chevron-right" size={12} className={styles.crumbSep} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
))}
|
||||
)}
|
||||
<span className={clsx(styles.crumbLabel, styles.currentCrumb)} aria-current="page">
|
||||
<T>{node.title}</T>
|
||||
</span>
|
||||
</div>
|
||||
<div ref={setHeaderSlot} className={styles.headerSlot} />
|
||||
{dirty && (
|
||||
|
||||
@@ -145,6 +145,18 @@ export function OxfmtPage() {
|
||||
);
|
||||
}
|
||||
|
||||
export function BiomePage() {
|
||||
return (
|
||||
<FormatterPage
|
||||
tool="biome"
|
||||
name="Biome"
|
||||
pathLabel="Biome path"
|
||||
providerHint="Biome formats an enabled language instead of Prettier and oxfmt below a Biome configuration file (biome.json, biome.jsonc) or installation, or when it is the selected provider."
|
||||
saveHint="Run Biome on save for enabled languages when it is the selected formatting provider."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function RuffPage() {
|
||||
return (
|
||||
<FormatterPage
|
||||
|
||||
@@ -212,7 +212,13 @@ function AccentRow() {
|
||||
return (
|
||||
<Indented>
|
||||
<Row label="Accent color">
|
||||
<ColorSwatches value={accent} presets={ACCENT_PRESETS} onChange={setAccent} aria-label="Accent color" />
|
||||
<ColorSwatches
|
||||
value={accent}
|
||||
presets={ACCENT_PRESETS}
|
||||
onChange={setAccent}
|
||||
aria-label="Accent color"
|
||||
useColorPicker
|
||||
/>
|
||||
</Row>
|
||||
</Indented>
|
||||
);
|
||||
|
||||
@@ -5,7 +5,16 @@ import { SCHEME_SUBPAGES, languagePageId } from "./colorSchemeMeta";
|
||||
* italic / effects editor, and a live preview. Edits are staged in
|
||||
* `editor.colorOverrides[scheme][attribute]`; `editor/core` injects them.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import {
|
||||
Suspense,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type CSSProperties,
|
||||
type MouseEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
@@ -39,6 +48,7 @@ import styles from "./Editor.module.css";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { ask, confirm, showError } from "@/workbench/messages";
|
||||
import { useContributions } from "@/workbench/contributions";
|
||||
import { parseIcls, SchemeParseError, importScheme, deleteScheme, exportIcls } from "@/platform/icls";
|
||||
import { tx, txPart, useTx } from "@/platform/i18n";
|
||||
import { selectPage } from "../../model/staging";
|
||||
@@ -1496,15 +1506,69 @@ function GitPreview({
|
||||
);
|
||||
}
|
||||
|
||||
/** One diff row in the Changed lines preview: a label, a coloured strip and its overview stripe. */
|
||||
const DIFF_PREVIEW_ROWS: Array<{ attr: string; code: string; bgVar: string; stripeVar: string }> = [
|
||||
{ attr: "diffChanged", code: "def MyClass():", bgVar: "--diff-modified", stripeVar: "--diff-modified-stripe" },
|
||||
{ attr: "diffInserted", code: "value = 123", bgVar: "--diff-inserted", stripeVar: "--diff-inserted-stripe" },
|
||||
{ attr: "diffDeleted", code: "pass # old", bgVar: "--diff-deleted", stripeVar: "--diff-deleted-stripe" },
|
||||
];
|
||||
/**
|
||||
* A static three-pane merge view (left parent / result / right parent) rendered through the
|
||||
* `mergeSchemePreview` editor kind — the same real CodeMirror diff decorations a merge view
|
||||
* uses, so the colours here are exactly the colours users get. Clicking a coloured line
|
||||
* selects its scheme attribute; the long unchanged stretch shows the folded wave separator.
|
||||
* Heads stay the same length so one fold range fits all panes, and every difference is
|
||||
* visible without scrolling: the heads carry the modification and the deletion, the result
|
||||
* gains `return value` right after the fold (an insertion isolated by shared lines, since
|
||||
* an adjacent delete+insert or a document-edge difference collapses into a modification).
|
||||
*/
|
||||
const DIFF_HEAD_A = ["bar(123)", "def foo(self):", " # Left changes", " pass"];
|
||||
const DIFF_HEAD_RESULT = ["class MyClass", "value = 123", "def foo(self):", " pass"];
|
||||
const DIFF_HEAD_B = ["class MyClass", "value = 123", "def foo(self):", " pass"];
|
||||
const DIFF_UNCHANGED = Array.from({ length: 16 }, (_, i) => ` # unchanged context ${i + 1}`);
|
||||
const DIFF_PARENT_A = [
|
||||
...DIFF_HEAD_A,
|
||||
...DIFF_UNCHANGED,
|
||||
" print('mid')",
|
||||
" print('end')",
|
||||
"def bar(self, a, b):",
|
||||
" print a",
|
||||
" print b",
|
||||
].join("\n");
|
||||
const DIFF_RESULT = [
|
||||
...DIFF_HEAD_RESULT,
|
||||
...DIFF_UNCHANGED,
|
||||
" print('mid')",
|
||||
" return value",
|
||||
" print('end')",
|
||||
"def bar(self, a, b):",
|
||||
" print a",
|
||||
" print b",
|
||||
].join("\n");
|
||||
const DIFF_PARENT_B = [
|
||||
...DIFF_HEAD_B,
|
||||
...DIFF_UNCHANGED,
|
||||
" print('mid')",
|
||||
" print('end')",
|
||||
"def bar(self, a, b):",
|
||||
" print a",
|
||||
" print b",
|
||||
].join("\n");
|
||||
function diffMergeInput(): import("@/workbench/contributions").EditorInput {
|
||||
return {
|
||||
kind: "mergeSchemePreview",
|
||||
key: "color-scheme-diff-preview",
|
||||
data: {
|
||||
path: "untitled:diff-merge-preview.py",
|
||||
left: DIFF_PARENT_A,
|
||||
result: DIFF_RESULT,
|
||||
right: DIFF_PARENT_B,
|
||||
labels: [tx("Left"), tx("Result"), tx("Right")],
|
||||
attrs: {
|
||||
inserted: "diffInserted",
|
||||
deleted: "diffDeleted",
|
||||
modified: "diffChanged",
|
||||
wave: "diffSeparatorWave",
|
||||
},
|
||||
fold: { from: 5, to: 20, label: tx("16 unchanged lines") },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The Diff & Merge page shows the real diff surfaces: change-type strips on a side-by-side
|
||||
* diff and the wavy separator on a folded-unchanged fragment. Each colour selects its attribute. */
|
||||
function DiffMergePreview({
|
||||
vars,
|
||||
ids,
|
||||
@@ -1514,67 +1578,17 @@ function DiffMergePreview({
|
||||
ids: Set<string>;
|
||||
reveal: (attrId: string) => void;
|
||||
}) {
|
||||
const click = (attrId: string) => revealPreviewAttr(attrId, ids, reveal);
|
||||
const stripeCell = (attrId: string, colorVar: string, key: string) => (
|
||||
<span
|
||||
key={key}
|
||||
className={`${styles.diffStripe} ${styles.clickable}`}
|
||||
style={{ background: `var(${colorVar})` }}
|
||||
title={tx("Error stripe mark")}
|
||||
onClick={() => click(attrId)}
|
||||
/>
|
||||
);
|
||||
const previewViewer = useContributions((s) => s.editorKinds.get("mergeSchemePreview"));
|
||||
const input = useMemo(() => diffMergeInput(), []);
|
||||
const onClick = (e: MouseEvent<HTMLDivElement>) => {
|
||||
const attr = (e.target as HTMLElement).closest<HTMLElement>("[data-diattr]")?.dataset.diattr;
|
||||
if (attr) revealPreviewAttr(attr, ids, reveal);
|
||||
};
|
||||
return (
|
||||
<div className={styles.diffPreview} style={vars} aria-label={tx("Color scheme preview")}>
|
||||
<div className={styles.gitSection}>
|
||||
<div className={styles.gitSectionTitle}>{tx("Changed lines")}</div>
|
||||
<div className={styles.diffPane}>
|
||||
{DIFF_PREVIEW_ROWS.map((row, i) => (
|
||||
<div key={row.attr} className={styles.diffLine}>
|
||||
<span className={styles.previewGutter}>{i + 1}</span>
|
||||
<span
|
||||
className={`${styles.diffLineBody} ${styles.clickable}`}
|
||||
style={{ background: `color-mix(in srgb, var(${row.bgVar}) 70%, transparent)` }}
|
||||
onClick={() => click(row.attr)}
|
||||
>
|
||||
{row.code}
|
||||
</span>
|
||||
{stripeCell(row.attr, row.stripeVar, "stripe")}
|
||||
</div>
|
||||
))}
|
||||
<div className={styles.diffLine} onClick={() => click("diffConflict")}>
|
||||
<span className={styles.previewGutter}>4</span>
|
||||
<span
|
||||
className={`${styles.diffLineBody} ${styles.clickable}`}
|
||||
style={{ background: `color-mix(in srgb, var(--bg-editor) 100%, transparent)` }}
|
||||
>
|
||||
<span
|
||||
className={styles.diffConflictMark}
|
||||
style={{ background: `var(--diff-conflict-stripe)` }}
|
||||
onClick={() => click("diffConflict")}
|
||||
>
|
||||
<<<< HEAD
|
||||
</span>
|
||||
</span>
|
||||
{stripeCell("diffConflict", "--diff-conflict-stripe", "conflict-stripe")}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.gitSection}>
|
||||
<div className={styles.gitSectionTitle}>{tx("Folded unchanged fragments")}</div>
|
||||
<div className={styles.diffFold}>
|
||||
<div className={styles.diffFoldCode}>def foo(self):</div>
|
||||
<div
|
||||
className={`${styles.diffFoldWave} ${styles.clickable}`}
|
||||
style={{ background: `var(--diff-separator-wave)`, borderBottomColor: `var(--diff-separator-wave)` }}
|
||||
title={tx("Folded unchanged fragments › Wave")}
|
||||
onClick={() => click("diffSeparatorWave")}
|
||||
>
|
||||
<span className={styles.diffFoldChevron}>{tx("6 unchanged lines")}</span>
|
||||
</div>
|
||||
<div className={styles.diffFoldCode}>def bar(self, a, b):</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.diffPreview} style={vars} aria-label={tx("Color scheme preview")} onClick={onClick}>
|
||||
<Suspense fallback={<div className={styles.diffLoading}>{tx("Loading preview…")}</div>}>
|
||||
{previewViewer && <previewViewer.component input={input} />}
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -553,91 +553,26 @@
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
/* Diff & Merge preview mirrors the two real diff surfaces: the change-type strips on a
|
||||
side-by-side diff and the wavy separator where IDEA folds an unchanged fragment. */
|
||||
/* Diff & Merge preview embeds a three-pane merge view (the `mergeSchemePreview` editor kind)
|
||||
painted with the real diff decorations; clicking a coloured line selects its attribute. */
|
||||
.diffPreview {
|
||||
margin: 14px 0 0;
|
||||
border-radius: var(--radius-small);
|
||||
box-shadow: inset 0 0 0 1px var(--border-strong);
|
||||
background: var(--bg-editor, var(--bg-island));
|
||||
overflow: auto;
|
||||
max-height: 260px;
|
||||
}
|
||||
.diffPane {
|
||||
padding: 4px 0;
|
||||
font-family: var(--openidea-editor-font, var(--font-mono));
|
||||
font-weight: var(--fw-code);
|
||||
font-size: var(--fs-code);
|
||||
line-height: var(--lh-code);
|
||||
color: var(--fg-editor, var(--fg));
|
||||
}
|
||||
.diffLine {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
min-height: 22px;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
max-height: 300px;
|
||||
}
|
||||
.diffLineBody {
|
||||
flex: 1;
|
||||
display: block;
|
||||
padding: 2px 8px;
|
||||
min-width: 0;
|
||||
white-space: pre;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.diffStripe {
|
||||
flex: none;
|
||||
width: 4px;
|
||||
align-self: stretch;
|
||||
}
|
||||
.diffConflictMark {
|
||||
padding: 0 4px;
|
||||
border-radius: 2px;
|
||||
color: var(--fg-editor, var(--fg));
|
||||
}
|
||||
.diffFold {
|
||||
padding: 4px 0;
|
||||
font-family: var(--openidea-editor-font, var(--font-mono));
|
||||
font-size: var(--fs-code);
|
||||
line-height: var(--lh-code);
|
||||
color: var(--fg-editor, var(--fg));
|
||||
}
|
||||
.diffFoldCode {
|
||||
padding: 2px 12px;
|
||||
white-space: pre;
|
||||
}
|
||||
.diffFoldWave {
|
||||
position: relative;
|
||||
height: 24px;
|
||||
margin: 2px 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-left: 12px;
|
||||
border-bottom: 2px solid var(--diff-separator-wave);
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
transparent 0,
|
||||
color-mix(in srgb, var(--diff-separator-wave) 22%, var(--bg-editor)) 50%,
|
||||
transparent 100%
|
||||
);
|
||||
}
|
||||
.diffFoldWave::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: auto 0 0 0;
|
||||
height: 6px;
|
||||
background: repeating-linear-gradient(
|
||||
-45deg,
|
||||
var(--diff-separator-wave) 0,
|
||||
var(--diff-separator-wave) 1px,
|
||||
transparent 1px,
|
||||
transparent 5px
|
||||
);
|
||||
}
|
||||
.diffFoldChevron {
|
||||
font-family: var(--font-ui);
|
||||
.diffLoading {
|
||||
padding: var(--space-3);
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.diffPreview :global(.cm-editor) {
|
||||
font-size: var(--fs-code);
|
||||
}
|
||||
|
||||
/* Code Style tables */
|
||||
|
||||
@@ -24,6 +24,7 @@ const PrettierPage = lazyPage("languages.prettier", () =>
|
||||
import("../languages/FormatterPage").then((m) => m.PrettierPage),
|
||||
);
|
||||
const OxfmtPage = lazyPage("languages.oxfmt", () => import("../languages/FormatterPage").then((m) => m.OxfmtPage));
|
||||
const BiomePage = lazyPage("languages.biome", () => import("../languages/FormatterPage").then((m) => m.BiomePage));
|
||||
const DocstringsPage = lazyPage("python.docstrings", () =>
|
||||
import("../languages/DocstringsPage").then((m) => m.DocstringsPage),
|
||||
);
|
||||
@@ -201,6 +202,16 @@ export const LANGUAGE_PAGES: PageSpec[] = [
|
||||
keywords: ["formatter", "oxfmt", "oxc", ".oxfmtrc.json", "format on save", "node_modules"],
|
||||
component: OxfmtPage,
|
||||
},
|
||||
{
|
||||
id: "languages.biome",
|
||||
projectScope: true,
|
||||
defaultScope: "project",
|
||||
title: "Biome",
|
||||
group: LANGUAGES_GROUP,
|
||||
order: 403.7,
|
||||
keywords: ["formatter", "linter", "biome", "biome.json", "format on save", "node_modules"],
|
||||
component: BiomePage,
|
||||
},
|
||||
{
|
||||
id: "python.docstrings",
|
||||
title: "Docstrings",
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { Commit } from "@/bindings";
|
||||
import type { ReactNode } from "react";
|
||||
import { fontWeightOf } from "@/platform/editorSettings";
|
||||
import { resolveMonoFont } from "@/platform/fonts";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
import styles from "./GitLog.module.css";
|
||||
|
||||
export function CommitMessageContent({
|
||||
commit,
|
||||
message,
|
||||
compact = false,
|
||||
renderText = (text) => text,
|
||||
revision = commit.shortId,
|
||||
}: {
|
||||
commit: Commit;
|
||||
message: string;
|
||||
compact?: boolean;
|
||||
renderText?: (text: string) => ReactNode;
|
||||
revision?: ReactNode;
|
||||
}) {
|
||||
const editor = useProject((s) => s.settings?.editor);
|
||||
const { family, size } = resolveMonoFont(undefined, editor);
|
||||
const [subject = "", ...bodyLines] = message.trimEnd().split("\n");
|
||||
const body = compact ? "" : bodyLines.join("\n").replace(/^\n+/, "");
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={styles.messageText}
|
||||
style={{ fontFamily: family, fontSize: size, fontWeight: fontWeightOf(editor?.fontWeight, 400) }}
|
||||
>
|
||||
<div className={styles.subjectLine} style={{ fontWeight: fontWeightOf(editor?.boldFontWeight, 700) }}>
|
||||
{renderText(subject)}
|
||||
</div>
|
||||
{body && <div className={styles.fullMessage}>{renderText(body)}</div>}
|
||||
</div>
|
||||
<div className={styles.meta}>
|
||||
{revision} {commit.author} <{commit.email}>
|
||||
{commit.timeMs ? " " + tx`on ${new Date(commit.timeMs).toLocaleString()}` : ""}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -61,7 +61,7 @@ import {
|
||||
filesOf,
|
||||
groupOf,
|
||||
ignoreTargets,
|
||||
isPartiallyStaged,
|
||||
commitsStagedPart,
|
||||
planCommit,
|
||||
toggledCheck,
|
||||
type ChangeNode,
|
||||
@@ -1020,7 +1020,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
)}
|
||||
{label}
|
||||
{n.type !== "file" && <span className={styles.nodeCount}>{fileCount(n.files.length)}</span>}
|
||||
{!staging && n.type === "file" && n.files[0] && isPartiallyStaged(n.files[0]) && (
|
||||
{!staging && n.type === "file" && n.files[0] && commitsStagedPart(n.files[0]) && (
|
||||
<span className={styles.partial} title={tx("Partially staged: only staged hunks are committed")}>
|
||||
<T>partial</T>
|
||||
</span>
|
||||
|
||||
@@ -118,6 +118,22 @@
|
||||
.sourceLabels .labelFile {
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.labelFile.revisionPath {
|
||||
display: inline-flex;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.revisionDirectory,
|
||||
.revisionFilename {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.revisionFilename {
|
||||
/* Let the directory shrink first, then elide the filename if it still exceeds the path's width. */
|
||||
flex: none;
|
||||
max-width: 100%;
|
||||
}
|
||||
.badge {
|
||||
padding: 0 5px;
|
||||
border-radius: var(--radius-small);
|
||||
|
||||
@@ -111,6 +111,23 @@ import styles from "./DiffEditor.module.css";
|
||||
/** Commands of the focused diff viewer (diff.* actions, vcs.nextChange / prevChange). */
|
||||
export { focusedDiffNavigator, type DiffNavigator };
|
||||
|
||||
interface PaneTitle {
|
||||
label: string;
|
||||
detail?: string;
|
||||
revisionPath?: string;
|
||||
}
|
||||
|
||||
function PaneTitleDetail({ detail, revisionPath }: PaneTitle) {
|
||||
if (!revisionPath) return detail ? <span className={styles.labelFile}>{detail}</span> : null;
|
||||
const filenameStart = revisionPath.lastIndexOf("/") + 1;
|
||||
return (
|
||||
<span className={clsx(styles.labelFile, styles.revisionPath)}>
|
||||
{filenameStart > 0 && <span className={styles.revisionDirectory}>{revisionPath.slice(0, filenameStart)}</span>}
|
||||
<span className={styles.revisionFilename}>{revisionPath.slice(filenameStart)}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
interface Views {
|
||||
/** The right / unified editor (chunks live here). */
|
||||
b: EditorView;
|
||||
@@ -1371,7 +1388,7 @@ export function DiffEditor({
|
||||
const canStage = editableB && isWorktree(right) && left.type === "rev" && !!useVcs.getState().root;
|
||||
const hasSource = !!source;
|
||||
|
||||
const paneTitle = (s: DiffSide): { label: string; detail?: string } => {
|
||||
const paneTitle = (s: DiffSide): PaneTitle => {
|
||||
if (s.type === "worktree" || s.type === "text") return { label: sideLabel(s), detail: s.labelDetail };
|
||||
if (s.type !== "rev") return { label: sideLabel(s) };
|
||||
const file = s.path ?? path;
|
||||
@@ -1379,13 +1396,13 @@ export function DiffEditor({
|
||||
const commit = !s.label && s.rev === "HEAD" && root ? heads[root]?.headCommit : null;
|
||||
return {
|
||||
label: commit ? commit.slice(0, 8) : sideLabel(s),
|
||||
detail: root && file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file,
|
||||
revisionPath: root && file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file,
|
||||
};
|
||||
};
|
||||
const titleA = paneTitle(left);
|
||||
const titleB = paneTitle(right);
|
||||
const captionA = [titleA.label, titleA.detail].filter(Boolean).join(" ");
|
||||
const captionB = [titleB.label, titleB.detail].filter(Boolean).join(" ");
|
||||
const captionA = [titleA.label, titleA.revisionPath ?? titleA.detail].filter(Boolean).join(" ");
|
||||
const captionB = [titleB.label, titleB.revisionPath ?? titleB.detail].filter(Boolean).join(" ");
|
||||
const sourceLabels = "labelDetail" in left || "labelDetail" in right;
|
||||
const labels = clsx(styles.labels, sourceLabels && styles.sourceLabels);
|
||||
|
||||
@@ -1591,7 +1608,7 @@ export function DiffEditor({
|
||||
<div className={labels}>
|
||||
<span className={styles.label} title={captionA}>
|
||||
<span className={styles.labelText}>{titleA.label}</span>
|
||||
{titleA.detail && <span className={styles.labelFile}>{titleA.detail}</span>}
|
||||
<PaneTitleDetail {...titleA} />
|
||||
{eolDiffers && eolA && <span className={styles.badge}>{badgeA}</span>}
|
||||
{editableA && (
|
||||
<span className={styles.badge}>
|
||||
@@ -1601,7 +1618,7 @@ export function DiffEditor({
|
||||
</span>
|
||||
<span className={styles.label} title={captionB}>
|
||||
<span className={styles.labelText}>{titleB.label}</span>
|
||||
{titleB.detail && <span className={styles.labelFile}>{titleB.detail}</span>}
|
||||
<PaneTitleDetail {...titleB} />
|
||||
{eolDiffers && eolB && <span className={styles.badge}>{badgeB}</span>}
|
||||
{editableB && (
|
||||
<span className={styles.badge}>{left.type === "rev" ? tx("working copy") : tx("editable")}</span>
|
||||
@@ -1612,10 +1629,10 @@ export function DiffEditor({
|
||||
<div className={labels}>
|
||||
<span className={styles.label} title={sourceLabels ? `${captionA} → ${captionB}` : undefined}>
|
||||
<span className={styles.labelText}>{sideLabel(left)}</span>
|
||||
{sourceLabels && titleA.detail && <span className={styles.labelFile}>{titleA.detail}</span>}
|
||||
{sourceLabels && <PaneTitleDetail {...titleA} />}
|
||||
{eolDiffers && eolA && <span className={styles.badge}>{badgeA}</span>} →
|
||||
<span className={styles.labelText}>{sideLabel(right)}</span>
|
||||
{sourceLabels && titleB.detail && <span className={styles.labelFile}>{titleB.detail}</span>}
|
||||
{sourceLabels && <PaneTitleDetail {...titleB} />}
|
||||
{eolDiffers && eolB && <span className={styles.badge}>{badgeB}</span>}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -405,9 +405,12 @@
|
||||
.subject {
|
||||
flex: 0 1 auto;
|
||||
min-width: var(--log-subject-min);
|
||||
color: var(--fg);
|
||||
}
|
||||
.subjectText {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg);
|
||||
}
|
||||
.headSubject {
|
||||
font-weight: 600;
|
||||
@@ -437,6 +440,22 @@
|
||||
flex: none;
|
||||
max-width: calc(100% - var(--log-subject-min) - var(--space-1-5));
|
||||
}
|
||||
.commitText > .refsCompact {
|
||||
flex: 0 1 auto;
|
||||
max-width: calc(100% / 3);
|
||||
}
|
||||
.commitText:has(> .refsCompact) > .subject {
|
||||
/* Protect a short subject while leaving room for compact reference names. */
|
||||
flex: 0 1000 max-content;
|
||||
min-width: auto;
|
||||
width: min(75%, 24ch);
|
||||
}
|
||||
.commitText > .refs .ref {
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.refsCompact .ref {
|
||||
min-width: 11px;
|
||||
}
|
||||
.refsLeft {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Static three-pane merge preview used by the Color Scheme › Diff & Merge page. It renders the
|
||||
* real CodeMirror diff decorations (`cm-diffLine-*`), so changing a scheme colour updates the
|
||||
* preview exactly as it updates a real merge view. Unlike `GitMergeDiff` it takes plain static
|
||||
* text instead of reading git revisions, and is offered through the `mergeSchemePreview` editor
|
||||
* kind so the settings feature can use it without importing this feature.
|
||||
*
|
||||
* Each coloured line carries `data-diattr`, so a click can select the matching scheme attribute.
|
||||
*/
|
||||
import { useEffect, useRef } from "react";
|
||||
import { EditorState, Text, type Range } from "@codemirror/state";
|
||||
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
|
||||
import { Chunk } from "@codemirror/merge";
|
||||
import type { EditorInput } from "@/workbench/contributions";
|
||||
import { firstLineOf, languageFor, viewerBase } from "./cm";
|
||||
import styles from "./GitLog.module.css";
|
||||
import { syncMergeScroll } from "./mergeScroll";
|
||||
import { MERGE_SCHEME_PREVIEW_KIND, type MergeSchemePreviewData } from "./mergeSchemePreviewKind";
|
||||
|
||||
export { MERGE_SCHEME_PREVIEW_KIND };
|
||||
export type { MergeSchemePreviewData };
|
||||
|
||||
/** The folded-unchanged separator, IDEA's DiffLineSeparatorRenderer wave. */
|
||||
class FoldWaveWidget extends WidgetType {
|
||||
constructor(
|
||||
readonly label: string,
|
||||
readonly attr: string,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
eq(other: FoldWaveWidget) {
|
||||
return other.label === this.label && other.attr === this.attr;
|
||||
}
|
||||
toDOM() {
|
||||
// Mirror the real collapsed-unchanged widget so the theme's wavy separator
|
||||
// (`.cm-collapsedLines > button::after`) paints with DIFF_SEPARATOR_WAVE.
|
||||
const el = document.createElement("div");
|
||||
el.className = "cm-collapsedLines";
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.setAttribute("data-diattr", this.attr);
|
||||
const text = document.createElement("span");
|
||||
text.className = "cm-diffCollapseLabel";
|
||||
text.textContent = this.label;
|
||||
button.append(text);
|
||||
el.append(button);
|
||||
return el;
|
||||
}
|
||||
ignoreEvent() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function lineAttrs(
|
||||
texts: readonly string[],
|
||||
attrs: MergeSchemePreviewData["attrs"],
|
||||
): Array<Map<number, { kind: string; attr: string }>> {
|
||||
const docs = texts.map((t) => Text.of(t.split("\n")));
|
||||
const marks = docs.map(() => new Map<number, { kind: string; attr: string }>());
|
||||
// Compare each parent against the result, exactly as GitMergeDiff does.
|
||||
for (const parent of [0, 2])
|
||||
for (const chunk of Chunk.build(docs[parent]!, docs[1]!)) {
|
||||
const inserted = chunk.fromA === chunk.toA;
|
||||
const deleted = chunk.fromB === chunk.toB;
|
||||
const kind = inserted ? "inserted" : deleted ? "deleted" : "modified";
|
||||
const attr = inserted ? attrs.inserted : deleted ? attrs.deleted : attrs.modified;
|
||||
for (const [pane, from, to] of [
|
||||
[parent, chunk.fromA, chunk.toA],
|
||||
[1, chunk.fromB, chunk.toB],
|
||||
]) {
|
||||
const doc = docs[pane!]!;
|
||||
for (let line = doc.lineAt(Math.min(from!, doc.length)); line.from < to!;) {
|
||||
marks[pane!]!.set(line.from, { kind, attr });
|
||||
if (line.number === doc.lines) break;
|
||||
line = doc.line(line.number + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return marks;
|
||||
}
|
||||
|
||||
export function MergeSchemePreview({ input }: { input: EditorInput }) {
|
||||
const data = input.data as MergeSchemePreviewData;
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const element = host.current;
|
||||
if (!element) return;
|
||||
let alive = true;
|
||||
const views: EditorView[] = [];
|
||||
let stopScroll: (() => void) | undefined;
|
||||
void languageFor(data.path, firstLineOf(data.result)).then((language) => {
|
||||
if (!alive || !host.current) return;
|
||||
const texts = [data.left, data.result, data.right];
|
||||
const marks = lineAttrs(texts, data.attrs);
|
||||
for (const [i, text] of texts.entries()) {
|
||||
const pane = document.createElement("div");
|
||||
pane.className = styles.mergeDiffPane!;
|
||||
host.current.append(pane);
|
||||
const doc = Text.of(text.split("\n"));
|
||||
const foldFrom = doc.line(Math.min(data.fold.from, doc.lines)).from;
|
||||
const foldTo = doc.line(Math.min(data.fold.to, doc.lines)).to;
|
||||
const decos: Range<Decoration>[] = [...marks[i]!]
|
||||
.sort((a, b) => a[0] - b[0])
|
||||
.map(([from, m]) =>
|
||||
Decoration.line({ class: `cm-diffLine-${m.kind}`, attributes: { "data-diattr": m.attr } }).range(from),
|
||||
);
|
||||
if (foldFrom < foldTo)
|
||||
decos.push(
|
||||
Decoration.replace({
|
||||
widget: new FoldWaveWidget(data.fold.label, data.attrs.wave),
|
||||
block: true,
|
||||
}).range(foldFrom, foldTo),
|
||||
);
|
||||
views.push(
|
||||
new EditorView({
|
||||
parent: pane,
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
extensions: [
|
||||
viewerBase({ readOnly: true }),
|
||||
...(language ? [language] : []),
|
||||
EditorView.decorations.of(Decoration.set(decos, true)),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
stopScroll = syncMergeScroll({ ours: views[0]!, result: views[1]!, theirs: views[2]! });
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
stopScroll?.();
|
||||
views.forEach((v) => v.destroy());
|
||||
element.replaceChildren();
|
||||
};
|
||||
}, [data]);
|
||||
return (
|
||||
<div className={styles.mergeDiff}>
|
||||
<div className={styles.mergeDiffLabels}>
|
||||
{data.labels.map((label, i) => (
|
||||
<span key={i}>{label}</span>
|
||||
))}
|
||||
</div>
|
||||
<div className={styles.mergeDiffPanes} ref={host} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { executeAction } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { Button, IconButton, Spinner, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
|
||||
import { CommitMessageContent } from "./CommitMessageContent";
|
||||
import { ComparisonTree } from "./ComparisonTree";
|
||||
import { buildFileTree } from "./fileTree";
|
||||
import { flatFileNodes, toLogChanges, type LogChange } from "./logChanges";
|
||||
@@ -151,14 +152,9 @@ export function PushChanges({
|
||||
|
||||
/** The selected commit's full message, revision, author and time. */
|
||||
function PushCommitDetails({ commit }: { commit: Commit }) {
|
||||
const date = commit.timeMs ? new Date(commit.timeMs).toLocaleString() : null;
|
||||
return (
|
||||
<section className={styles.pushCommitDetails} aria-label={tx("Commit details")}>
|
||||
<div className={styles.pushCommitMessage}>{commit.message.trimEnd() || commit.summary}</div>
|
||||
<div className={styles.fileDir}>
|
||||
{commit.shortId} {commit.author} <{commit.email}>
|
||||
{date ? " " + tx`on ${date}` : ""}
|
||||
</div>
|
||||
<CommitMessageContent commit={commit} message={commit.message.trimEnd() || commit.summary} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { FileStatus } from "@/bindings";
|
||||
|
||||
const stage = vi.hoisted(() => vi.fn(async () => ({ status: "ok", data: null })));
|
||||
const ignore = vi.hoisted(() => vi.fn(async () => ({ status: "ok", data: [] })));
|
||||
const notify = vi.hoisted(() => vi.fn());
|
||||
const project = vi.hoisted(() => ({ paths: [] as string[] }));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsStage: stage,
|
||||
vcsAddToIgnore: ignore,
|
||||
vcsStatus: async () => ({ status: "ok", data: [] }),
|
||||
vcsBranchInfo: async () => ({ status: "ok", data: null }),
|
||||
vcsRoots: async () => ({ status: "ok", data: [{ root: "/repo", operation: null }] }),
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/workbench/contributions")>()),
|
||||
projectViewSelection: () => project.paths,
|
||||
notifications: () => ({ notify }),
|
||||
}));
|
||||
vi.mock("../comparePaths", () => ({ showDirectoryWorkingDiff: async () => false }));
|
||||
vi.mock("../diffDialog", () => ({ openDiffDialog: vi.fn() }));
|
||||
vi.mock("../DiffWindow", () => ({ showDiffWindow: vi.fn() }));
|
||||
|
||||
import { getAction } from "@/platform/actions";
|
||||
import { registerVcsActions } from "../actions";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const fs = (relPath: string, unstaged: FileStatus["unstaged"]): FileStatus => ({
|
||||
path: `/repo/${relPath}`,
|
||||
relPath,
|
||||
staged: null,
|
||||
unstaged,
|
||||
renamedFrom: null,
|
||||
});
|
||||
|
||||
let unregister: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
stage.mockClear();
|
||||
ignore.mockClear();
|
||||
notify.mockClear();
|
||||
project.paths = [];
|
||||
const files = [fs("dir/new.ts", "untracked"), fs("dir/sub/n2.ts", "untracked"), fs("dir/tracked.ts", "modified")];
|
||||
useVcs.setState({
|
||||
root: "/repo",
|
||||
roots: ["/repo"],
|
||||
status: files,
|
||||
byPath: new Map(files.map((f) => [f.path, f])),
|
||||
statusLoaded: true,
|
||||
});
|
||||
unregister = registerVcsActions();
|
||||
});
|
||||
|
||||
afterEach(() => unregister());
|
||||
|
||||
const addToVcs = () => getAction("vcs.addToVcs")!;
|
||||
|
||||
describe("Add to VCS", () => {
|
||||
it("adds the unversioned files below the Project view's selected directory", async () => {
|
||||
project.paths = ["/repo/dir"];
|
||||
await addToVcs().run({ arg: undefined, ctx: { vcsAvailable: true, projectViewFocus: true } });
|
||||
expect(stage).toHaveBeenCalledWith(["/repo/dir/new.ts", "/repo/dir/sub/n2.ts"]);
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves the Project view's selection alone while another view has focus", async () => {
|
||||
project.paths = ["/repo/dir"];
|
||||
await addToVcs().run({ arg: undefined, ctx: { vcsAvailable: true } });
|
||||
expect(stage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("only adds the unversioned files under an explicit selection", async () => {
|
||||
await addToVcs().run({ arg: ["/repo/dir/tracked.ts"], ctx: { vcsAvailable: true } });
|
||||
expect(stage).not.toHaveBeenCalled();
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Nothing to add: the files are already under version control" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Add to .gitignore", () => {
|
||||
it("ignores the Project view's selection while it has focus, and not otherwise", async () => {
|
||||
project.paths = ["/repo/dir/new.ts"];
|
||||
await getAction("vcs.ignoreShared")!.run({ arg: undefined, ctx: { vcsAvailable: true, projectViewFocus: true } });
|
||||
expect(ignore).toHaveBeenCalledWith(["/repo/dir/new.ts"], "gitignore");
|
||||
ignore.mockClear();
|
||||
await getAction("vcs.ignoreShared")!.run({ arg: undefined, ctx: { vcsAvailable: true } });
|
||||
expect(ignore).not.toHaveBeenCalledWith(["/repo/dir/new.ts"], "gitignore");
|
||||
});
|
||||
});
|
||||
@@ -433,6 +433,13 @@ describe("commit inclusion", () => {
|
||||
expect(initialCheck(status[5]!)).toBe("none");
|
||||
});
|
||||
|
||||
it("commits a new file edited after Add to Git with its working-tree content", () => {
|
||||
// Add to Git staged the file as created (empty); the edits after it are unstaged.
|
||||
const created = fs("src/main/kotlin/New.kt", "added", "modified");
|
||||
expect(initialCheck(created)).toBe("all");
|
||||
expect(planCommit([created], new Map()).stage).toEqual(["/r/src/main/kotlin/New.kt"]);
|
||||
});
|
||||
|
||||
it("starts all files unchecked when default inclusion is disabled", () => {
|
||||
const checks = new Map<string, CheckState>();
|
||||
expect(aggregateCheck(status, checks, false)).toEqual({ checked: false, indeterminate: false, on: 0 });
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { Chunk } from "@codemirror/merge";
|
||||
|
||||
// The Color Scheme › Diff & Merge sample (ColorSchemeBody.tsx) must keep showing all three
|
||||
// change kinds without scrolling: the heads carry the modification and the deletion, the
|
||||
// result gains `return value` right after the fold. Guards against edits that let
|
||||
// `Chunk.build` collapse two of the kinds into a single modified chunk.
|
||||
const UNCHANGED = Array.from({ length: 16 }, (_, i) => ` # unchanged context ${i + 1}`);
|
||||
const HEAD_A = ["bar(123)", "def foo(self):", " # Left changes", " pass"];
|
||||
const HEAD_R = ["class MyClass", "value = 123", "def foo(self):", " pass"];
|
||||
const MID = [" print('mid')"];
|
||||
const END = [" print('end')", "def bar(self, a, b):", " print a", " print b"];
|
||||
|
||||
const classify = (x: string, y: string) =>
|
||||
Chunk.build(Text.of(x.split("\n")), Text.of(y.split("\n"))).map((c) =>
|
||||
c.fromA === c.toA ? "inserted" : c.fromB === c.toB ? "deleted" : "modified",
|
||||
);
|
||||
|
||||
it("classifies the Diff & Merge sample into modified, inserted and deleted", () => {
|
||||
const a = [...HEAD_A, ...UNCHANGED, ...MID, ...END].join("\n");
|
||||
const r = [...HEAD_R, ...UNCHANGED, ...MID, " return value", ...END].join("\n");
|
||||
const b = [...HEAD_R, ...UNCHANGED, ...MID, ...END].join("\n");
|
||||
const vsLeft = classify(a, r);
|
||||
const vsRight = classify(b, r);
|
||||
expect(vsLeft).toContain("modified");
|
||||
expect(vsLeft).toContain("deleted");
|
||||
expect(vsLeft).toContain("inserted");
|
||||
expect(vsRight).toContain("inserted");
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import type { Commit } from "@/bindings";
|
||||
|
||||
const { files, combined, executeAction } = vi.hoisted(() => ({
|
||||
@@ -69,8 +69,10 @@ describe("Push dialog changes", () => {
|
||||
const one = { ...older, message: "Add order service\n\nIntroduces the service.\n", timeMs: 1_700_000_000_000 };
|
||||
render(<PushChanges repo="/r" commits={[one]} />);
|
||||
const details = screen.getByRole("region", { name: "Commit details" });
|
||||
expect(details.textContent).toContain("Add order service\n\nIntroduces the service.");
|
||||
expect(details.textContent).toContain("aaaaaaa me <[email protected]> on ");
|
||||
const message = within(details);
|
||||
expect(message.getByText("Add order service", { exact: true })).toBeTruthy();
|
||||
expect(message.getByText("Introduces the service.", { exact: true })).toBeTruthy();
|
||||
expect(message.getByText(/^aaaaaaa me <me@example\.com> on /)).toBeTruthy();
|
||||
expect(await screen.findByText("src/orders")).toBeTruthy();
|
||||
expect(screen.getAllByRole("treeitem")).toHaveLength(2);
|
||||
const grouping = screen.getByRole("button", { name: "Group by Directory" });
|
||||
|
||||
@@ -156,6 +156,11 @@ function selectedPaths(arg: unknown): string[] {
|
||||
return project.length ? project : contextPaths(arg);
|
||||
}
|
||||
|
||||
/** Paths a file action targets: the Project view's selection while it has focus, else the open file. */
|
||||
function focusedPaths(arg: unknown, ctx: { projectViewFocus?: unknown }): string[] {
|
||||
return ctx.projectViewFocus ? selectedPaths(arg) : contextPaths(arg);
|
||||
}
|
||||
|
||||
/**
|
||||
* The repository a repository-wide dialog (Pull, Merge, Rebase) starts on: the one holding the
|
||||
* action's file, else the Project view's selection while it has focus, else the active editor's
|
||||
@@ -661,8 +666,8 @@ export function registerVcsActions(): () => void {
|
||||
category: "Git",
|
||||
icon: "history",
|
||||
when: VCS,
|
||||
run: ({ arg }) => {
|
||||
const path = contextPaths(arg)[0];
|
||||
run: ({ arg, ctx }) => {
|
||||
const path = focusedPaths(arg, ctx)[0];
|
||||
if (!path) return;
|
||||
openLogTab("history", path);
|
||||
showGitWindow();
|
||||
@@ -717,7 +722,7 @@ export function registerVcsActions(): () => void {
|
||||
category: "Git",
|
||||
when: VCS,
|
||||
keywords: ["ignore", "unversioned", "exclude"],
|
||||
run: ({ arg }) => addToIgnore(contextPaths(arg), destination),
|
||||
run: ({ arg, ctx }) => addToIgnore(focusedPaths(arg, ctx), destination),
|
||||
})),
|
||||
{
|
||||
id: "vcs.addToVcs",
|
||||
@@ -726,9 +731,7 @@ export function registerVcsActions(): () => void {
|
||||
icon: "plus",
|
||||
when: VCS,
|
||||
keywords: ["git add", "stage"],
|
||||
run: ({ arg }) => {
|
||||
return addToVcs(contextPaths(arg));
|
||||
},
|
||||
run: ({ arg, ctx }) => addToVcs(focusedPaths(arg, ctx)),
|
||||
},
|
||||
{
|
||||
id: "vcs.stash",
|
||||
|
||||
@@ -75,12 +75,21 @@ export function isPartiallyStaged(fs: FileStatus): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A partially staged file the commit takes only the staged part of by default. A new file
|
||||
* edited after Add to Git (which staged it as it was on creation) is committed whole: its
|
||||
* staged side is just that first snapshot, not a selection of changes.
|
||||
*/
|
||||
export function commitsStagedPart(fs: FileStatus): boolean {
|
||||
return isPartiallyStaged(fs) && fs.staged !== "added";
|
||||
}
|
||||
|
||||
export function initialCheck(fs: FileStatus, includeByDefault = true): CheckState {
|
||||
if (!includeByDefault) return "none";
|
||||
const g = groupOf(fs);
|
||||
// Unversioned files and unresolved conflicts are opt-in, as in IDEA.
|
||||
if (g !== "changes") return "none";
|
||||
return isPartiallyStaged(fs) ? "staged" : "all";
|
||||
return commitsStagedPart(fs) ? "staged" : "all";
|
||||
}
|
||||
|
||||
export function checkOf(fs: FileStatus, checks: ReadonlyMap<string, CheckState>, includeByDefault = true): CheckState {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { workflowSettings, type GitSettingsValid } from "@/platform/workflowSett
|
||||
import { toolWindowService } from "@/workbench/contributions";
|
||||
import { useCommit, type CommitTab } from "./commitStore";
|
||||
import type { FileStatus } from "@/bindings";
|
||||
import { groupOf, isPartiallyStaged, type CheckState } from "./changes";
|
||||
import { commitsStagedPart, groupOf, type CheckState } from "./changes";
|
||||
import { stashTabOf } from "./gitTabs";
|
||||
import { selectGitTab } from "./logStore";
|
||||
import { isProtectedBranch, pushWithAutoUpdate, showPushDialog } from "./remoteUi";
|
||||
@@ -53,7 +53,7 @@ export function includeOnly(status: readonly FileStatus[], paths: readonly strin
|
||||
for (const fs of status) {
|
||||
const group = groupOf(fs);
|
||||
if (!group || group === "conflicts") continue;
|
||||
checks.set(fs.path, !chosen.has(fs.path) ? "none" : isPartiallyStaged(fs) ? "staged" : "all");
|
||||
checks.set(fs.path, !chosen.has(fs.path) ? "none" : commitsStagedPart(fs) ? "staged" : "all");
|
||||
}
|
||||
return checks;
|
||||
}
|
||||
|
||||
@@ -363,9 +363,6 @@
|
||||
.pushCommitDetails {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
margin: var(--space-1) var(--space-3);
|
||||
padding: var(--space-1) var(--space-2);
|
||||
overflow: auto;
|
||||
@@ -374,11 +371,6 @@
|
||||
-webkit-user-select: text;
|
||||
user-select: text;
|
||||
}
|
||||
.pushCommitMessage {
|
||||
color: var(--fg-strong);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.todoList {
|
||||
margin: 8px 0 0;
|
||||
padding-left: 18px;
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import type { Commit } from "@/bindings";
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { fontWeightOf } from "@/platform/editorSettings";
|
||||
import { resolveMonoFont } from "@/platform/fonts";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
import clsx from "clsx";
|
||||
import { CommitMessageContent } from "../CommitMessageContent";
|
||||
import styles from "../GitLog.module.css";
|
||||
import { IssueText } from "../issueLinks";
|
||||
import { useCommitDetails } from "../logDetails";
|
||||
@@ -37,7 +35,7 @@ export function RefLabels({
|
||||
}) {
|
||||
const labels = refLabels(refs, { compact, tagNames }, remoteNames);
|
||||
return (
|
||||
<span className={clsx(styles.refs, left && styles.refsLeft)}>
|
||||
<span className={clsx(styles.refs, compact && styles.refsCompact, left && styles.refsLeft)}>
|
||||
{labels.map((l) => (
|
||||
<span key={`${l.kind}:${l.title}`} className={clsx(styles.ref, REF_KIND_CLASS[l.kind])} title={l.title}>
|
||||
{l.text && <span className={styles.refText}>{l.text}</span>}
|
||||
@@ -50,39 +48,25 @@ export function RefLabels({
|
||||
/** A commit's message and metadata; `compact` (one of several selected): without the body. */
|
||||
export function CommitMessage({ commit, compact = false }: { commit: Commit; compact?: boolean }) {
|
||||
const { details, error } = useCommitDetails(commit, !compact);
|
||||
const editor = useProject((s) => s.settings?.editor);
|
||||
const { family, size } = resolveMonoFont(undefined, editor);
|
||||
const repo = commitRepo(commit) ?? currentRepo();
|
||||
const message = details?.message || commit.message;
|
||||
const [subject, ...bodyLines] = message.replace(/\s+$/, "").split("\n");
|
||||
const body = compact ? "" : bodyLines.join("\n").replace(/^\n+/, "");
|
||||
return (
|
||||
<div className={clsx(compact && styles.commitEntry)}>
|
||||
<div
|
||||
className={styles.messageText}
|
||||
style={{ fontFamily: family, fontSize: size, fontWeight: fontWeightOf(editor?.fontWeight, 400) }}
|
||||
>
|
||||
<div className={styles.subjectLine} style={{ fontWeight: fontWeightOf(editor?.boldFontWeight, 700) }}>
|
||||
<CommitMessageText text={subject ?? ""} repo={repo} />
|
||||
</div>
|
||||
{body && (
|
||||
<div className={styles.fullMessage}>
|
||||
<CommitMessageText text={body} repo={repo} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.meta}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.linkButton}
|
||||
title={tx("Copy revision number")}
|
||||
onClick={() => void writeClipboardText(commit.id)}
|
||||
>
|
||||
{commit.shortId}
|
||||
</button>{" "}
|
||||
{commit.author} <{commit.email}>
|
||||
{commit.timeMs ? " " + tx`on ${new Date(commit.timeMs).toLocaleString()}` : ""}
|
||||
</div>
|
||||
<CommitMessageContent
|
||||
commit={commit}
|
||||
message={details?.message || commit.message}
|
||||
compact={compact}
|
||||
renderText={(text) => <CommitMessageText text={text} repo={repo} />}
|
||||
revision={
|
||||
<button
|
||||
type="button"
|
||||
className={styles.linkButton}
|
||||
title={tx("Copy revision number")}
|
||||
onClick={() => void writeClipboardText(commit.id)}
|
||||
>
|
||||
{commit.shortId}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
{!compact &&
|
||||
commit.committer &&
|
||||
(commit.committer !== commit.author ||
|
||||
|
||||
@@ -134,7 +134,9 @@ function CommitRowView({
|
||||
setTooltip(false);
|
||||
}}
|
||||
>
|
||||
<IssueText text={c.summary} />
|
||||
<span className={styles.subjectText}>
|
||||
<IssueText text={c.summary} />
|
||||
</span>
|
||||
</span>
|
||||
{!opts.refsOnLeft && refs}
|
||||
</span>
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/** Merge-scheme preview input; kept apart from `MergeSchemePreview` so registering it does not load CodeMirror. */
|
||||
|
||||
export const MERGE_SCHEME_PREVIEW_KIND = "mergeSchemePreview";
|
||||
|
||||
export interface MergeSchemePreviewData {
|
||||
/** Virtual URI; keeps language detection and avoids any file/git access. */
|
||||
path: string;
|
||||
/** Text of the left parent, merge result and right parent. */
|
||||
left: string;
|
||||
result: string;
|
||||
right: string;
|
||||
labels: [string, string, string];
|
||||
/** Attribute id for each change type, used as `data-diattr` on the coloured lines. */
|
||||
attrs: { inserted: string; deleted: string; modified: string; wave: string };
|
||||
/** 1-based, inclusive line range folded into a wavy separator in each pane. */
|
||||
fold: { from: number; to: number; label: string };
|
||||
}
|
||||
@@ -1,13 +1,26 @@
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerSettingsPage } from "@/workbench/contributions";
|
||||
import { registerEditorKind, registerSettingsPage } from "@/workbench/contributions";
|
||||
import { MERGE_SCHEME_PREVIEW_KIND } from "./mergeSchemePreviewKind";
|
||||
|
||||
/** Settings › Version Control › Log (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPage({
|
||||
// The three-pane merge preview of Color Scheme › Diff & Merge: registered here so the
|
||||
// native Settings window has it too, where the workbench's diff viewer never activates.
|
||||
const schemePreview = registerEditorKind({
|
||||
kind: MERGE_SCHEME_PREVIEW_KIND,
|
||||
component: lazyComponent(() => import("./MergeSchemePreview").then((m) => m.MergeSchemePreview)),
|
||||
title: () => tx("Diff & Merge"),
|
||||
});
|
||||
const log = registerSettingsPage({
|
||||
id: "vcs.log",
|
||||
title: "Log",
|
||||
order: 6,
|
||||
keywords: ["git log", "references", "tags", "columns", "commit time"],
|
||||
component: lazyComponent(() => import("./LogSettingsPage").then((m) => m.LogSettingsPage)),
|
||||
});
|
||||
return () => {
|
||||
schemePreview();
|
||||
log();
|
||||
};
|
||||
}
|
||||
@@ -137,6 +137,23 @@
|
||||
color: var(--fg-editor, var(--fg-secondary));
|
||||
opacity: 0.8;
|
||||
}
|
||||
.preview :global([data-math-svg]) {
|
||||
position: relative;
|
||||
}
|
||||
.preview :global([data-math-svg="display"]) {
|
||||
display: block;
|
||||
margin: 1em 0;
|
||||
overflow: auto hidden;
|
||||
padding: 2px 0;
|
||||
text-align: center;
|
||||
}
|
||||
.preview :global(mjx-assistive-mml) {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
user-select: none;
|
||||
}
|
||||
.preview :global(table) {
|
||||
display: block;
|
||||
width: max-content;
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
* screen (Structure's Autoscroll from Source).
|
||||
*/
|
||||
import {
|
||||
Suspense,
|
||||
use,
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
@@ -24,7 +26,7 @@ import { useMarkdownPreviewFontSize, useMarkdownPreviewLayout } from "@/platform
|
||||
import { maybeEditorService, registerFontZoomSurface } from "@/workbench/contributions";
|
||||
import { editorsFor, setShownLine } from "@/editor/api";
|
||||
import { highlightInto } from "@/editor/lsp/markdown";
|
||||
import { FloatingToolbar, SplitGroup, SplitHandle, SplitPanel, selectableText } from "@/ui";
|
||||
import { FloatingToolbar, Spinner, SplitGroup, SplitHandle, SplitPanel, selectableText } from "@/ui";
|
||||
import {
|
||||
FIND_CURRENT_HIGHLIGHT,
|
||||
FIND_HIGHLIGHT,
|
||||
@@ -42,6 +44,7 @@ import { publishPreviewSelection, publishPreviewTop, stepMarkdownPreviewFontZoom
|
||||
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
|
||||
import { hasMermaid, MERMAID_SELECTOR, renderMermaidIn } from "./mermaid";
|
||||
import { renderMath } from "@/editor/lsp/markdownMath";
|
||||
import type { renderMathSvg } from "./mathSvg";
|
||||
import { modeOf, pinMarkdownMode, useMarkdownModes } from "./modes";
|
||||
import { MarkdownLayoutActions } from "./MarkdownLayoutActions";
|
||||
import {
|
||||
@@ -151,7 +154,15 @@ export function MarkdownEditor({
|
||||
{mode === "split" && <SplitHandle aria-label={tx("Resize Markdown preview")} />}
|
||||
{mode !== "editor" && (
|
||||
<SplitPanel id="preview" style={{ overflow: "hidden" }} {...splitBounds}>
|
||||
<MarkdownPreview path={path} sync={mode === "split"} />
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className={styles.preview}>
|
||||
<Spinner label={tx("Loading")} />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<MarkdownPreview path={path} sync={mode === "split"} />
|
||||
</Suspense>
|
||||
</SplitPanel>
|
||||
)}
|
||||
</SplitGroup>
|
||||
@@ -172,6 +183,15 @@ const blocksOf = (root: HTMLElement) =>
|
||||
},
|
||||
}));
|
||||
|
||||
let svgRenderer: Promise<typeof renderMathSvg | null> | undefined;
|
||||
|
||||
function loadSvgRenderer() {
|
||||
return (svgRenderer ??= import("./mathSvg").then(
|
||||
(module) => module.renderMathSvg,
|
||||
() => null,
|
||||
));
|
||||
}
|
||||
|
||||
function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const text = useLiveMarkdown((s) => s[path]?.text);
|
||||
const fontZoom = useLiveMarkdown((s) => s[path]?.fontZoom ?? 0);
|
||||
@@ -187,6 +207,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const deferred = useDeferredValue(text ?? "");
|
||||
const [render] = useState(createMarkdownRenderer);
|
||||
const html = useMemo(() => render(deferred), [render, deferred]);
|
||||
const renderSvg = html.includes(' data-math="') ? use(loadSvgRenderer()) : null;
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const blocks = useRef<ReturnType<typeof blocksOf>>([]);
|
||||
const theme = useSyncExternalStore(subscribeTheme, themeKey, () => "");
|
||||
@@ -213,10 +234,11 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
// Math before the preview index: typesetting changes the blocks' heights.
|
||||
useLayoutEffect(() => {
|
||||
if (!ref.current) return;
|
||||
renderSvg?.(ref.current);
|
||||
renderMath(ref.current);
|
||||
blocks.current = blocksOf(ref.current);
|
||||
invalidatePreviewIndex(ref.current);
|
||||
}, [html]);
|
||||
}, [html, renderSvg]);
|
||||
|
||||
// Mermaid diagrams: before paint, so cached ones don't flash their source.
|
||||
useLayoutEffect(() => {
|
||||
|
||||
@@ -97,7 +97,7 @@ function collectRuns(root: Node): TextRun[] {
|
||||
const el = node as Element;
|
||||
const tag = el.tagName.toUpperCase();
|
||||
if (SKIP_TAGS.has(tag)) return;
|
||||
if (el.classList.contains("katex-mathml")) return;
|
||||
if (tag === "MJX-ASSISTIVE-MML" || el.classList.contains("katex-mathml")) return;
|
||||
if (tag === "PRE" && el.parentElement?.getAttribute("data-mermaid-state") === "ok") return;
|
||||
const isBlock = BLOCK_TAGS.has(tag);
|
||||
if (isBlock) flush();
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { renderMath } from "@/editor/lsp/markdownMath";
|
||||
import { renderMathSvg } from "./mathSvg";
|
||||
import { renderMarkdown } from "./render";
|
||||
|
||||
it("renders inline and display equations as independent SVGs with accessible MathML", () => {
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = renderMarkdown("**$`v_0`$** and $v_0$.\n\n$$\nv_0\n$$");
|
||||
renderMathSvg(root);
|
||||
|
||||
const inline = root.querySelectorAll('[data-math-svg="inline"] > svg');
|
||||
const display = root.querySelectorAll('[data-math-svg="display"] > svg');
|
||||
expect(inline).toHaveLength(2);
|
||||
expect(display).toHaveLength(1);
|
||||
expect(root.querySelector("strong > [data-math-svg] > svg")?.getAttribute("aria-label")).toBe("v_0");
|
||||
expect(root.querySelectorAll("mjx-assistive-mml math")).toHaveLength(3);
|
||||
expect(
|
||||
[...root.querySelectorAll("svg use")].every((use) => {
|
||||
const href = use.getAttribute("xlink:href");
|
||||
return href?.startsWith("#") && use.closest("svg")?.querySelector(`[id="${href.slice(1)}"]`);
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves unsupported formulas for KaTeX without enabling TeX links", () => {
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = renderMarkdown(String.raw`$\href{https://example.com}{x}$`);
|
||||
renderMathSvg(root);
|
||||
expect(root.querySelector('[data-math="inline"]')?.textContent).toBe(String.raw`\href{https://example.com}{x}`);
|
||||
renderMath(root);
|
||||
expect(root.querySelector(".katex")).not.toBeNull();
|
||||
expect(root.querySelector("a")).toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { MathJaxTexFont } from "@mathjax/mathjax-tex-font/js/svg.js";
|
||||
import { AssistiveMmlHandler } from "@mathjax/src/js/a11y/assistive-mml.js";
|
||||
import { browserAdaptor } from "@mathjax/src/js/adaptors/browserAdaptor.js";
|
||||
import { RegisterHTMLHandler } from "@mathjax/src/js/handlers/html.js";
|
||||
import { TeX } from "@mathjax/src/js/input/tex.js";
|
||||
import "@mathjax/src/js/input/tex/ams/AmsConfiguration.js";
|
||||
import "@mathjax/src/js/input/tex/base/BaseConfiguration.js";
|
||||
import "@mathjax/src/js/input/tex/newcommand/NewcommandConfiguration.js";
|
||||
import "@mathjax/src/js/input/tex/textmacros/TextMacrosConfiguration.js";
|
||||
import { mathjax } from "@mathjax/src/js/mathjax.js";
|
||||
import { SVG } from "@mathjax/src/js/output/svg.js";
|
||||
import { SafeHandler } from "@mathjax/src/js/ui/safe/SafeHandler.js";
|
||||
|
||||
function createSvgRenderer() {
|
||||
const handler = RegisterHTMLHandler(browserAdaptor());
|
||||
SafeHandler<HTMLElement, Text, Document>(handler);
|
||||
AssistiveMmlHandler<HTMLElement, Text, Document>(handler);
|
||||
const tex = new TeX<HTMLElement, Text, Document>({
|
||||
packages: ["base", "ams", "newcommand", "textmacros"],
|
||||
formatError: (_jax: unknown, error: unknown) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const math = mathjax.document("", {
|
||||
InputJax: tex,
|
||||
OutputJax: new SVG({ fontData: MathJaxTexFont, fontCache: "local" }),
|
||||
safeOptions: { allow: { URLs: "none", classes: "none", cssIDs: "none", styles: "none" } },
|
||||
});
|
||||
return (source: string, display: boolean) => {
|
||||
tex.reset();
|
||||
return math.convert(source, { display, em: 16, ex: 8, containerWidth: 1280 }) as HTMLElement;
|
||||
};
|
||||
}
|
||||
|
||||
let convert: ReturnType<typeof createSvgRenderer> | undefined;
|
||||
|
||||
export function renderMathSvg(root: HTMLElement) {
|
||||
for (const element of root.querySelectorAll<HTMLElement>("[data-math]")) {
|
||||
const mode = element.getAttribute("data-math");
|
||||
const source = element.textContent?.trim();
|
||||
if (!source || (mode !== "inline" && mode !== "display")) continue;
|
||||
try {
|
||||
convert ??= createSvgRenderer();
|
||||
const output = convert(source, mode === "display");
|
||||
const svg = output.querySelector("svg");
|
||||
if (!svg) continue;
|
||||
svg.setAttribute("aria-label", source);
|
||||
element.setAttribute("data-math-svg", mode);
|
||||
element.removeAttribute("data-math");
|
||||
element.replaceChildren(...output.childNodes);
|
||||
} catch {
|
||||
// Keep unsupported TeX for the existing KaTeX renderer.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ const DEFAULT_GO_BUILD_TAGS: GoBuildTags = {
|
||||
experiments: "",
|
||||
};
|
||||
|
||||
/** An external formatter (Prettier, oxfmt, Ruff) and the languages it formats. */
|
||||
/** An external formatter (Prettier, oxfmt, Biome, Ruff) and the languages it formats. */
|
||||
interface ExternalFormatterValid {
|
||||
path: string;
|
||||
configurationDirectory: string;
|
||||
@@ -58,6 +58,12 @@ const DEFAULT_FORMATTER: ExternalFormatterValid = {
|
||||
runOnSave: false,
|
||||
};
|
||||
|
||||
/** Biome formats these of Prettier's languages (`BIOME_LANGUAGES` in `ide-core`). */
|
||||
const DEFAULT_BIOME_FORMATTER: ExternalFormatterValid = {
|
||||
...DEFAULT_FORMATTER,
|
||||
languages: ["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"],
|
||||
};
|
||||
|
||||
const DEFAULT_RUFF_FORMATTER: ExternalFormatterValid = {
|
||||
...DEFAULT_FORMATTER,
|
||||
languages: ["python"],
|
||||
@@ -201,6 +207,7 @@ export interface LanguagesValid {
|
||||
typescript: { version: string };
|
||||
prettier: ExternalFormatterValid;
|
||||
oxfmt: ExternalFormatterValid;
|
||||
biome: ExternalFormatterValid;
|
||||
ruff: ExternalFormatterValid;
|
||||
java: {
|
||||
jdk: string;
|
||||
@@ -312,6 +319,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = {
|
||||
typescript: { version: "bundled" },
|
||||
prettier: DEFAULT_FORMATTER,
|
||||
oxfmt: DEFAULT_FORMATTER,
|
||||
biome: DEFAULT_BIOME_FORMATTER,
|
||||
ruff: DEFAULT_RUFF_FORMATTER,
|
||||
java: {
|
||||
jdk: "",
|
||||
@@ -486,6 +494,7 @@ export function validateLanguages(raw: unknown): LanguagesValid {
|
||||
typescript: { version: text(ts.version, d.typescript.version) || d.typescript.version },
|
||||
prettier: validateFormatter(l.prettier),
|
||||
oxfmt: validateFormatter(l.oxfmt),
|
||||
biome: validateFormatter(l.biome, DEFAULT_BIOME_FORMATTER),
|
||||
ruff: validateFormatter(l.ruff, DEFAULT_RUFF_FORMATTER),
|
||||
java: {
|
||||
jdk: text(java.jdk, d.java.jdk),
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"Reformat with Biome": "Reformat with Biome",
|
||||
"Biome path": "Biome path",
|
||||
"Biome formats an enabled language instead of Prettier and oxfmt below a Biome configuration file (biome.json, biome.jsonc) or installation, or when it is the selected provider.": "Biome formats an enabled language instead of Prettier and oxfmt below a Biome configuration file (biome.json, biome.jsonc) or installation, or when it is the selected provider.",
|
||||
"Run Biome on save for enabled languages when it is the selected formatting provider.": "Run Biome on save for enabled languages when it is the selected formatting provider.",
|
||||
"Biome formatting failed": "Biome formatting failed",
|
||||
"Biome formatting timed out": "Biome formatting timed out",
|
||||
"$ unchanged lines": "$ unchanged lines",
|
||||
"Expand unchanged lines": "Expand unchanged lines",
|
||||
"Matching scope": "Matching scope",
|
||||
@@ -319,7 +325,11 @@
|
||||
"Changed lines › Inserted": "Changed lines › Inserted",
|
||||
"Folded unchanged fragments › Wave": "Folded unchanged fragments › Wave",
|
||||
"Error stripe mark": "Error stripe mark",
|
||||
"6 unchanged lines": "6 unchanged lines",
|
||||
"Loading preview…": "Loading preview…",
|
||||
"Left": "Left",
|
||||
"Result": "Result",
|
||||
"Right": "Right",
|
||||
"16 unchanged lines": "16 unchanged lines",
|
||||
"Dock Pinned": "Dock Pinned",
|
||||
"Dock Unpinned": "Dock Unpinned",
|
||||
"Undock": "Undock",
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"Reformat with Biome": "使用 Biome 重新格式化",
|
||||
"Biome path": "Biome 路径",
|
||||
"Biome formats an enabled language instead of Prettier and oxfmt below a Biome configuration file (biome.json, biome.jsonc) or installation, or when it is the selected provider.": "在 Biome 配置文件(biome.json、biome.jsonc)或 Biome 安装所在目录及其子目录中,或选择 Biome 作为格式化工具时,Biome 将代替 Prettier 和 oxfmt 格式化已启用的语言。",
|
||||
"Run Biome on save for enabled languages when it is the selected formatting provider.": "对已启用的语言,在选择 Biome 作为格式化工具时于保存时运行。",
|
||||
"Biome formatting failed": "Biome 格式化失败",
|
||||
"Biome formatting timed out": "Biome 格式化超时",
|
||||
"$ unchanged lines": "$ 行未改动",
|
||||
"Expand unchanged lines": "展开未改动的行",
|
||||
"Matching scope": "匹配的代码块",
|
||||
@@ -254,7 +260,8 @@
|
||||
"Changed lines › Inserted": "变更的行 › 已插入",
|
||||
"Folded unchanged fragments › Wave": "折叠的未变更片段 › 波浪线",
|
||||
"Error stripe mark": "错误条标记",
|
||||
"6 unchanged lines": "6 行未变更",
|
||||
"Loading preview…": "正在加载预览…",
|
||||
"16 unchanged lines": "16 行未变更",
|
||||
"Dock Pinned": "停靠固定",
|
||||
"Dock Unpinned": "停靠取消固定",
|
||||
"Undock": "取消停靠",
|
||||
|
||||
@@ -96,6 +96,7 @@ const UNTRANSLATED = new Set<string>([
|
||||
"Flutter",
|
||||
"Prettier",
|
||||
"oxfmt",
|
||||
"Biome",
|
||||
"Ruff",
|
||||
"IntelliJ IDEA",
|
||||
"GitHub",
|
||||
|
||||
+14
-1
@@ -2,7 +2,20 @@
|
||||
width: 340px;
|
||||
max-width: calc(100vw - 12px);
|
||||
padding: 0 0 12px;
|
||||
overflow: hidden;
|
||||
max-height: calc(100vh - 12px);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.opaque .control:global(.react-colorful) {
|
||||
grid-template-rows: minmax(0, 1fr) 54px;
|
||||
}
|
||||
|
||||
.opaque .control :global(.react-colorful__hue) {
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.opaque .fields {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr)) minmax(78px, 1.65fr);
|
||||
}
|
||||
|
||||
.pickerArea {
|
||||
@@ -0,0 +1,279 @@
|
||||
import { useLayoutEffect, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { RgbColorPicker, RgbaColorPicker } from "react-colorful";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { Button, IconButton } from "./Button";
|
||||
import { Popup, type PopupAnchor } from "./Popup";
|
||||
import { T } from "./T";
|
||||
import { fromHex, fromOpaqueHex, toHex6, toHex8, type Rgba } from "./colorPickerValues";
|
||||
import styles from "./ColorPicker.module.css";
|
||||
|
||||
const RECENT_KEY = "openidea.colorPicker.recent.v1";
|
||||
const MAX_RECENT = 20;
|
||||
|
||||
function readRecent(): string[] {
|
||||
try {
|
||||
const value: unknown = JSON.parse(localStorage.getItem(RECENT_KEY) ?? "[]");
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === "string" && fromHex(item) !== null).slice(0, MAX_RECENT)
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberColor(value: Rgba) {
|
||||
const hex = toHex8(value);
|
||||
const recent = [hex, ...readRecent().filter((item) => item.toLowerCase() !== hex)].slice(0, MAX_RECENT);
|
||||
try {
|
||||
localStorage.setItem(RECENT_KEY, JSON.stringify(recent));
|
||||
} catch {
|
||||
// Storage can be unavailable in a restricted WebView.
|
||||
}
|
||||
}
|
||||
|
||||
interface EyeDropperResult {
|
||||
sRGBHex: string;
|
||||
}
|
||||
|
||||
interface EyeDropperInstance {
|
||||
open(): Promise<EyeDropperResult>;
|
||||
}
|
||||
|
||||
type EyeDropperWindow = Window & { EyeDropper?: new () => EyeDropperInstance };
|
||||
|
||||
function Field({
|
||||
label,
|
||||
name,
|
||||
value,
|
||||
maxLength,
|
||||
inputMode,
|
||||
isValid,
|
||||
onValid,
|
||||
}: {
|
||||
label: string;
|
||||
name: string;
|
||||
value: string;
|
||||
maxLength: number;
|
||||
inputMode: "numeric" | "text";
|
||||
isValid: (text: string) => boolean;
|
||||
onValid: (text: string) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
const t = useTx();
|
||||
const shown = draft ?? value;
|
||||
return (
|
||||
<label className={styles.field}>
|
||||
<span>{label}</span>
|
||||
<input
|
||||
aria-label={t(name)}
|
||||
aria-invalid={shown !== "" && !isValid(shown)}
|
||||
inputMode={inputMode}
|
||||
maxLength={maxLength}
|
||||
spellCheck={false}
|
||||
value={shown}
|
||||
onChange={(event) => {
|
||||
const next = event.currentTarget.value;
|
||||
setDraft(next);
|
||||
if (isValid(next)) onValid(next);
|
||||
}}
|
||||
onBlur={() => {
|
||||
if (!shown || isValid(shown)) setDraft(null);
|
||||
}}
|
||||
onFocus={(event) => event.currentTarget.select()}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function ColorPicker({
|
||||
anchor,
|
||||
initial,
|
||||
opaque = false,
|
||||
onChange,
|
||||
onFinish,
|
||||
}: {
|
||||
anchor: PopupAnchor;
|
||||
initial: Rgba;
|
||||
opaque?: boolean;
|
||||
onChange?: (value: Rgba) => void;
|
||||
onFinish: (commit: boolean, value: Rgba) => void;
|
||||
}) {
|
||||
const [value, setValue] = useState<Rgba>(initial);
|
||||
const [recent] = useState(readRecent);
|
||||
const [sampling, setSampling] = useState(false);
|
||||
const mounted = useRef(false);
|
||||
const form = useRef<HTMLFormElement>(null);
|
||||
const t = useTx();
|
||||
const eyeDropper = (window as EyeDropperWindow).EyeDropper;
|
||||
useLayoutEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const update = (next: Rgba) => {
|
||||
if (opaque) next = [next[0], next[1], next[2], 1];
|
||||
setValue(next);
|
||||
onChange?.(next);
|
||||
};
|
||||
const parseHex = opaque ? fromOpaqueHex : fromHex;
|
||||
const finish = (commit: boolean) => onFinish(commit, value);
|
||||
const channel = (index: 0 | 1 | 2, text: string) => {
|
||||
const number = Number(text);
|
||||
const next: Rgba = [...value];
|
||||
next[index] = number;
|
||||
update(next);
|
||||
};
|
||||
const alpha = (text: string) => {
|
||||
const number = Number(text);
|
||||
update([value[0], value[1], value[2], number / 100]);
|
||||
};
|
||||
const hex = (text: string) => {
|
||||
const next = parseHex(text);
|
||||
if (next) update(next);
|
||||
};
|
||||
const numeric = (max: number) => (text: string) => /^\d{1,3}$/.test(text) && Number(text) <= max;
|
||||
const sampleScreen = async () => {
|
||||
if (!eyeDropper || sampling) return;
|
||||
setSampling(true);
|
||||
try {
|
||||
const result = await new eyeDropper().open();
|
||||
const next = fromHex(result.sRGBHex);
|
||||
if (next && mounted.current) update(next);
|
||||
} catch (error) {
|
||||
if (!(error instanceof DOMException && error.name === "AbortError")) console.warn(error);
|
||||
} finally {
|
||||
if (mounted.current) setSampling(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
anchor={anchor}
|
||||
placement="bottom-start"
|
||||
offset={4}
|
||||
onClose={(reason) => finish(reason !== "escape" && !form.current?.querySelector('[aria-invalid="true"]'))}
|
||||
aria-label={t("Color picker")}
|
||||
className={clsx(styles.popup, opaque && styles.opaque)}
|
||||
trapFocus
|
||||
closeOnDeactivate={false}
|
||||
>
|
||||
<form
|
||||
ref={form}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!event.currentTarget.querySelector('[aria-invalid="true"]')) finish(true);
|
||||
}}
|
||||
>
|
||||
<div className={styles.pickerArea}>
|
||||
{opaque ? (
|
||||
<RgbColorPicker
|
||||
className={styles.control}
|
||||
color={{ r: value[0], g: value[1], b: value[2] }}
|
||||
onChange={({ r, g, b }) => update([r, g, b, 1])}
|
||||
/>
|
||||
) : (
|
||||
<RgbaColorPicker
|
||||
className={styles.control}
|
||||
color={{ r: value[0], g: value[1], b: value[2], a: value[3] }}
|
||||
onChange={({ r, g, b, a }) => update([r, g, b, a])}
|
||||
/>
|
||||
)}
|
||||
<div className={styles.sampleRow}>
|
||||
<IconButton
|
||||
icon="eyedropper"
|
||||
title="Pick screen color"
|
||||
size="small"
|
||||
disabled={!eyeDropper || sampling}
|
||||
onClick={() => void sampleScreen()}
|
||||
/>
|
||||
<div className={styles.preview} role="img" aria-label={t("Current color")}>
|
||||
<span style={{ backgroundColor: `rgba(${value.join(", ")})` }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.fields}>
|
||||
<Field
|
||||
label="R"
|
||||
name="Red"
|
||||
value={String(value[0])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(0, v)}
|
||||
/>
|
||||
<Field
|
||||
label="G"
|
||||
name="Green"
|
||||
value={String(value[1])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(1, v)}
|
||||
/>
|
||||
<Field
|
||||
label="B"
|
||||
name="Blue"
|
||||
value={String(value[2])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(2, v)}
|
||||
/>
|
||||
{!opaque && (
|
||||
<Field
|
||||
label="A%"
|
||||
name="Alpha percent"
|
||||
value={String(Math.round(value[3] * 100))}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(100)}
|
||||
onValid={alpha}
|
||||
/>
|
||||
)}
|
||||
<Field
|
||||
label={t("HEX")}
|
||||
name="Hexadecimal"
|
||||
value={(opaque ? toHex6(value) : toHex8(value)).slice(1).toUpperCase()}
|
||||
maxLength={opaque ? 7 : 9}
|
||||
inputMode="text"
|
||||
isValid={(v) => parseHex(v) !== null}
|
||||
onValid={hex}
|
||||
/>
|
||||
</div>
|
||||
{recent.length > 0 && (
|
||||
<div className={styles.recent} role="group" aria-label={t("Recent colors")}>
|
||||
{recent.map((hex) => {
|
||||
const next = fromHex(hex)!;
|
||||
const display = opaque ? toHex6(next) : hex.toLowerCase();
|
||||
return (
|
||||
<button
|
||||
key={hex}
|
||||
type="button"
|
||||
title={display.toUpperCase()}
|
||||
aria-label={`${t("Recent color")} ${display.toUpperCase()}`}
|
||||
aria-pressed={display === (opaque ? toHex6(value) : toHex8(value))}
|
||||
className={styles.recentColor}
|
||||
onClick={() => update(next)}
|
||||
>
|
||||
<span style={{ backgroundColor: display }} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.actions}>
|
||||
<Button size="small" onClick={() => finish(false)}>
|
||||
<T>Cancel</T>
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" size="small">
|
||||
<T>Apply</T>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Popup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/** Red, green, blue 0–255 and alpha 0–1. */
|
||||
export type Rgba = [number, number, number, number];
|
||||
|
||||
export const hex2 = (v: number) =>
|
||||
Math.round(Math.min(255, Math.max(0, v)))
|
||||
.toString(16)
|
||||
.padStart(2, "0");
|
||||
|
||||
/** `#rrggbb` of `rgba`, as `<input type=color>` takes it. */
|
||||
export function toHex6([r, g, b]: Rgba): string {
|
||||
return `#${hex2(r)}${hex2(g)}${hex2(b)}`;
|
||||
}
|
||||
|
||||
export function toHex8(rgba: Rgba): string {
|
||||
return `${toHex6(rgba)}${hex2(rgba[3] * 255)}`;
|
||||
}
|
||||
|
||||
/** Six-digit hex is opaque; eight-digit hex carries its own alpha. */
|
||||
export function fromHex(hex: string): Rgba | null {
|
||||
const m = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i.exec(hex);
|
||||
return m
|
||||
? [
|
||||
Number.parseInt(m[1]!, 16),
|
||||
Number.parseInt(m[2]!, 16),
|
||||
Number.parseInt(m[3]!, 16),
|
||||
m[4] ? Number.parseInt(m[4], 16) / 255 : 1,
|
||||
]
|
||||
: null;
|
||||
}
|
||||
|
||||
export function fromOpaqueHex(hex: string): Rgba | null {
|
||||
const digits = hex.replace(/^#/, "");
|
||||
if (/^[0-9a-f]{3}$/i.test(digits)) return fromHex(digits.replace(/./g, (digit) => digit + digit));
|
||||
return digits.length === 6 && /^[0-9a-f]+$/i.test(digits) ? fromHex(digits) : null;
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача