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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 7125a2179e feat(viewers): open SVG files as source with a live image preview
SVG files open in the text editor with the image viewer beside it, with the
Editor Only / Editor and Preview / Preview Only switch Markdown has (in the tab
strip, or floating over the editor when tabs are off). The preview is redrawn
from the source as it is typed, shows a readable message for invalid SVG and
recovers once it is valid again; it is drawn as an image, so scripts in the
file never run. The last layout chosen for SVG files is kept apart from
Markdown's. Raster images keep the image viewer alone, and a plugin's editor
for a more specific SVG pattern still wins over this one.

Fixes #6234
2026-11-27 05:32:06 +08:00
14 змінених файлів з 482 додано та 125 видалено

No files matched your search

+34 -8
Переглянути файл
@@ -4,10 +4,11 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
await page.setViewportSize({ width: 1080, height: 700 });
await stubDesktop(page);
await page.evaluate(async () => {
const path = "/dev/acme-api/status.svg";
const path = "/dev/acme-api/status.png";
// A black 128 × 96 PNG.
const image =
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>';
window.__ipc.handlers.fs_read_image = () => "data:image/svg+xml," + encodeURIComponent(image);
"iVBORw0KGgoAAAANSUhEUgAAAIAAAABgCAYAAADVenpJAAAAtklEQVR42u3SQREAAAyDMPyb3oQ0jxjgqDqmiWAADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABkAEA2AADIABMAAGwAAYgAUPjHPSwnYk55QAAAAASUVORK5CYII=";
window.__ipc.handlers.fs_read_image = () => "data:image/png;base64," + image;
window.__ipc.handlers.fs_probe = () => ({ size: 4096, binary: false, tooLarge: false });
const contributions = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ contributions);
@@ -18,9 +19,8 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
const zoomIn = toolbar.getByRole("button", { name: "Zoom In", exact: true });
const actualSize = toolbar.getByRole("button", { name: "Actual Size", exact: true });
const chessboard = toolbar.getByRole("button", { name: "Show Chessboard", exact: true });
const showText = toolbar.getByRole("button", { name: "Open as Text", exact: true });
const dimensions = toolbar.getByText(/128\s*×\s*96/);
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
await expect(page.getByRole("img", { name: "status.png", exact: true })).toBeVisible();
await expect(dimensions).toBeVisible();
const wideHeight = (await toolbar.boundingBox())!.height;
@@ -31,8 +31,7 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
expect((await toolbar.boundingBox())!.height).toBeGreaterThan(wideHeight);
expect((await dimensions.boundingBox())!.y).toBeGreaterThan((await zoomIn.boundingBox())!.y);
await expect(dimensions).toHaveCSS("font-size", "13px");
await expect(showText).toHaveCSS("white-space", "nowrap");
for (const item of [zoomIn, actualSize, chessboard, showText, dimensions]) {
for (const item of [zoomIn, actualSize, chessboard, dimensions]) {
await expect(item).toBeInViewport({ ratio: 1 });
}
await expect(toolbar.getByText("4.0 KB", { exact: true })).toBeVisible();
@@ -43,6 +42,33 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
await expect(toolbar.getByText("100%", { exact: true })).toBeVisible();
await chessboard.click();
await expect(chessboard).toHaveAttribute("aria-pressed", "false");
await showText.click();
});
test("an SVG file opens as its source with the image beside it", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
window.__ipc.handlers.fs_probe = () => ({ size: 96, binary: false, tooLarge: false });
const contributions = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ contributions);
await editorService().openFile("/dev/acme-api/status.svg");
});
const toolbar = page.getByRole("toolbar", { name: "Image viewer", exact: true });
// Not an SVG yet: the preview says so, and draws the source once it is typed.
await expect(page.getByText("The SVG source is not valid.", { exact: true })).toBeVisible();
await page.locator(".cm-content").click();
await page.keyboard.press("ControlOrMeta+A");
await page.keyboard.insertText(
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>',
);
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
await expect(toolbar.getByText(/128\s*×\s*96/)).toBeVisible();
await expect(toolbar.getByRole("button", { name: "Open as Text", exact: true })).toHaveCount(0);
const layout = page.getByRole("toolbar", { name: "SVG editor layout", exact: true });
await layout.getByRole("button", { name: "Preview Only", exact: true }).click();
await expect(page.locator(".cm-content")).toBeHidden();
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
await layout.getByRole("button", { name: "Editor Only", exact: true }).click();
await expect(toolbar).toHaveCount(0);
await expect(page.locator(".cm-content")).toBeVisible();
});
+51 -26
Переглянути файл
@@ -1,7 +1,8 @@
/**
* Image editor kind (IDEA's image viewer): zoom in / out / fit / actual size,
* ⌘/Ctrl+wheel zoom, transparency chessboard, dimensions and file size.
* Images are read by the backend as `data:` URLs (the CSP allows those).
* Images are read by the backend as `data:` URLs (the CSP allows those). As the preview of an SVG
* file it shows the source as typed instead (`source`), drawn as an image so its scripts never run.
*/
import {
useCallback,
@@ -59,9 +60,19 @@ export function toggleChessboard() {
}
const PADDING = 32;
const NO_FOCUS_TARGET = { current: null };
const INVALID_SVG = "invalid-svg";
export function ImageViewer({ input }: { input: EditorInput }) {
/** An SVG source as an image URL. */
export const svgDataUrl = (source: string) => `data:image/svg+xml;charset=utf-8,${encodeURIComponent(source)}`;
/**
* `source`: the SVG text to show instead of the file on disk (the SVG editor's preview); null while
* it isn't known yet.
*/
export function ImageViewer({ input, source }: { input: EditorInput; source?: string | null }) {
const path = input.path!;
const live = source !== undefined;
const [src, setSrc] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [size, setSize] = useState<number | null>(null);
@@ -75,18 +86,27 @@ export function ImageViewer({ input }: { input: EditorInput }) {
const canvasRef = useRef<HTMLDivElement>(null);
useEffect(() => {
let live = true;
if (live) return;
let current = true;
Promise.all([call(commands.fsReadImage(path)), call(commands.fsProbe(path))])
.then(([url, probe]) => {
if (!live) return;
if (!current) return;
setSrc(url);
setSize(probe.size);
})
.catch((e: unknown) => live && setError(e instanceof Error ? e.message : String(e)));
.catch((e: unknown) => current && setError(e instanceof Error ? e.message : String(e)));
return () => {
live = false;
current = false;
};
}, [path, reload]);
}, [path, reload, live]);
// The typed source: each edit is drawn again, so an invalid SVG recovers once it's valid.
const liveSrc = useMemo(() => (source ? svgDataUrl(source) : null), [source]);
const liveSize = useMemo(() => (source ? new TextEncoder().encode(source).length : null), [source]);
const [invalidSrc, setInvalidSrc] = useState<string | null>(null);
const shownSrc = live ? liveSrc : src;
const shownSize = live ? liveSize : size;
const shownError = live ? (invalidSrc !== null && invalidSrc === liveSrc ? INVALID_SVG : null) : error;
const available = useCallback(() => {
const el = canvasRef.current;
@@ -133,7 +153,8 @@ export function ImageViewer({ input }: { input: EditorInput }) {
};
}, [handle]);
useForwardFocus(rootRef);
// Beside the source editor, the preview leaves the editor's focus alone.
useForwardFocus(live ? NO_FOCUS_TARGET : rootRef);
const onLoad = (img: HTMLImageElement) => {
// SVGs without intrinsic size report 0×0; show them at a usable size.
@@ -162,7 +183,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
};
el.addEventListener("wheel", onWheel, { passive: false });
return () => el.removeEventListener("wheel", onWheel);
}, [error, src]);
}, [shownError, shownSrc]);
const onPointerDown = (e: ReactPointerEvent) => {
if (e.button !== 0 && e.button !== 1) return;
@@ -204,15 +225,17 @@ export function ImageViewer({ input }: { input: EditorInput }) {
<div className={styles.imageActions}>
<div className={styles.imageActionGroup}>
<IconButton icon="chessboard" size="small" action="image.toggleChessboard" pressed={chessboard} />
<IconButton
icon="refresh"
size="small"
title="Reload from Disk"
onClick={() => {
setError(null);
setReload((n) => n + 1);
}}
/>
{!live && (
<IconButton
icon="refresh"
size="small"
title="Reload from Disk"
onClick={() => {
setError(null);
setReload((n) => n + 1);
}}
/>
)}
</div>
<div className={styles.imageActionGroup}>
<IconButton icon="zoom-in" size="small" action="image.zoomIn" />
@@ -221,7 +244,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
<IconButton icon="maximize" size="small" action="image.fitToWindow" />
</div>
</div>
{svg && (
{svg && !live && (
<button
type="button"
className={styles.textButton}
@@ -230,16 +253,18 @@ export function ImageViewer({ input }: { input: EditorInput }) {
<T>Open as Text</T>
</button>
)}
{(natural || size !== null || view) && (
{(natural || shownSize !== null || view) && (
<div className={styles.imageInfo}>
{natural && <span>{`${natural.w} × ${natural.h}`}</span>}
{size !== null && <span>{formatSize(size)}</span>}
{shownSize !== null && <span>{formatSize(shownSize)}</span>}
{view && <span>{zoomLabel(z)}</span>}
</div>
)}
</div>
{error ? (
<div className={styles.message}>{tx`Cannot show the image: ${error}`}</div>
{shownError ? (
<div className={styles.message}>
{shownError === INVALID_SVG ? tx("The SVG source is not valid.") : tx`Cannot show the image: ${shownError}`}
</div>
) : (
<div
data-wheel-scroll
@@ -250,9 +275,9 @@ export function ImageViewer({ input }: { input: EditorInput }) {
onPointerUp={endDrag}
onPointerCancel={endDrag}
>
{src && (
{shownSrc && (
<img
src={src}
src={shownSrc}
alt={path.slice(path.lastIndexOf("/") + 1)}
draggable={false}
className={clsx(styles.image, chessboard && styles.chessboard, z >= 4 && styles.pixelated)}
@@ -266,7 +291,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
: { visibility: "hidden" }
}
onLoad={(e) => onLoad(e.currentTarget)}
onError={() => setError("the file is not a valid image")}
onError={() => (live ? setInvalidSrc(shownSrc) : setError("the file is not a valid image"))}
/>
)}
</div>
+38
Переглянути файл
@@ -0,0 +1,38 @@
import { IconButton } from "@/ui";
import type { LayoutMode } from "./layoutModes";
import styles from "./markdown/Markdown.module.css";
/** Editor Only / Editor and Preview / Preview Only buttons of a text editor with a preview. */
export function LayoutActions({ tabId, mode, label }: { tabId: string; mode: LayoutMode; label: string }) {
return (
<div className={styles.layoutActions} role="toolbar" aria-label={label}>
<IconButton
icon="editor-only"
iconSize={16}
size="small"
title="Editor Only"
action="markdown.editorOnly"
actionArg={tabId}
pressed={mode === "editor"}
/>
<IconButton
icon="editor-preview"
iconSize={16}
size="small"
title="Editor and Preview"
action="markdown.editorAndPreview"
actionArg={tabId}
pressed={mode === "split"}
/>
<IconButton
icon="preview-only"
iconSize={16}
size="small"
title="Preview Only"
action="markdown.previewOnly"
actionArg={tabId}
pressed={mode === "preview"}
/>
</div>
);
}
+38 -9
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Non-text editors and the Markdown preview: images open in an image viewer,
* binary and very large files in a read-only hex view (both through file
* editor providers consulted by `openFile`), and Markdown files get IDEA's
* editor providers consulted by `openFile`), and Markdown and SVG files get IDEA's
* Editor / Editor and Preview / Preview layouts around the text editor.
*/
import { registerActions, type Action } from "@/platform/actions";
@@ -29,12 +29,16 @@ import {
imageInput,
isImagePath,
isMarkdownPath,
isSvgPath,
wantsHexView,
} from "./fileKinds";
import { ImageViewer, toggleChessboard, useImageViewers } from "./ImageViewer";
import { HexViewer } from "./HexViewer";
import { registerMarkdownLiveSource } from "./markdown/live";
import { setMarkdownMode, useMarkdownSourceHidden, type MarkdownMode } from "./markdown/modes";
import { setMarkdownMode, useMarkdownModes, useMarkdownSourceHidden } from "./markdown/modes";
import type { LayoutMode } from "./layoutModes";
import { registerSvgLiveSource } from "./svg/live";
import { SvgLayoutActions, svgModes } from "./svg/SvgEditor";
import { MarkdownLayoutActions } from "./markdown/MarkdownLayoutActions";
import { canExtractImages, extractImages, EXTRACT_IMAGES, EXTRACT_IMAGES_TITLE } from "./markdown/extractImages";
@@ -65,19 +69,35 @@ function imageActions(): Action[] {
];
}
/**
* The tab whose layout an Editor Only / Editor and Preview / Preview Only action sets: the one its
* tab button passes, else the focused editor's when it's a Markdown or SVG file.
*/
function layoutTarget(arg: unknown): { tabId: string; set: (tabId: string, mode: LayoutMode) => void } | null {
if (typeof arg === "string") {
return { tabId: arg, set: svgModes.useModes.getState().byTab[arg] ? svgModes.set : setMarkdownMode };
}
const editor = activeEditor();
const path = editor?.ctx.path ?? "";
if (!editor?.tabId) return null;
if (isSvgPath(path)) return { tabId: editor.tabId, set: svgModes.set };
if (isMarkdownPath(path) || useMarkdownModes.getState().byTab[editor.tabId])
return { tabId: editor.tabId, set: setMarkdownMode };
return null;
}
function markdownActions(): Action[] {
const mode = (id: string, title: string, m: MarkdownMode, icon: string): Action => ({
const mode = (id: string, title: string, m: LayoutMode, icon: string): Action => ({
id,
title,
category: "Markdown",
icon,
keywords: ["markdown", "preview", "layout"],
when: "textEditorActive && editorLangId == markdown",
keywords: ["markdown", "svg", "preview", "layout"],
when: "textEditorActive",
enabled: ({ arg }) => !!layoutTarget(arg),
run: ({ arg }) => {
// The tab's layout buttons pass their tab; the keyboard acts on the focused editor's.
const editor = activeEditor();
const tabId = typeof arg === "string" ? arg : isMarkdownPath(editor?.ctx.path ?? "") ? editor?.tabId : undefined;
if (tabId) setMarkdownMode(tabId, m);
const target = layoutTarget(arg);
target?.set(target.tabId, m);
},
});
return [
@@ -143,6 +163,15 @@ export function activate(): () => void {
useSourceHidden: useMarkdownSourceHidden,
}),
registerMarkdownLiveSource(),
registerTextEditorWrapper({
id: "viewers.svg",
fallback: true,
matches: isSvgPath,
component: lazyComponent(() => import("./svg/SvgEditor").then((m) => m.SvgEditor)),
tabActions: SvgLayoutActions,
useSourceHidden: svgModes.useSourceHidden,
}),
registerSvgLiveSource(),
registerMenuGroup({
id: EXTRACT_IMAGES,
menus: ["editor"],
+56
Переглянути файл
@@ -0,0 +1,56 @@
/**
* Layout of a text editor with a preview (IDEA's TextEditorWithPreview): Editor Only / Editor and
* Preview / Preview Only, per editor tab. Split panes showing the same file each keep their own;
* tabs opened later take the layout chosen last for that kind of file.
*/
import { create, type StoreApi, type UseBoundStore } from "zustand";
export type LayoutMode = "editor" | "split" | "preview";
const MODES: readonly LayoutMode[] = ["editor", "split", "preview"];
export interface LayoutModesState {
byTab: Record<string, LayoutMode>;
/** Mode of tabs opened since: the last one chosen. */
fallback: LayoutMode;
}
export const modeOf = (s: LayoutModesState, tabId: string): LayoutMode => s.byTab[tabId] ?? s.fallback;
export interface LayoutModes {
useModes: UseBoundStore<StoreApi<LayoutModesState>>;
/** Preview Only hides the source editor of `tabId`. */
useSourceHidden: (tabId: string) => boolean;
/** Fixes a shown tab's mode, so choosing one in another tab doesn't change it. */
pin: (tabId: string) => void;
set: (tabId: string, mode: LayoutMode) => void;
}
/** The layouts of one kind of file, the last one chosen kept under `storageKey`. */
export function createLayoutModes(storageKey: string): LayoutModes {
const stored = (): LayoutMode => {
try {
const v = localStorage.getItem(storageKey);
return MODES.includes(v as LayoutMode) ? (v as LayoutMode) : "split";
} catch {
return "split";
}
};
const useModes = create<LayoutModesState>(() => ({ byTab: {}, fallback: stored() }));
return {
useModes,
useSourceHidden: (tabId) => useModes((s) => modeOf(s, tabId) === "preview"),
pin: (tabId) => {
if (useModes.getState().byTab[tabId]) return;
useModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: s.fallback } }));
},
set: (tabId, mode) => {
useModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: mode }, fallback: mode }));
try {
localStorage.setItem(storageKey, mode);
} catch {
// Per-viewer convenience only.
}
},
};
}
+2 -33
Переглянути файл
@@ -1,39 +1,8 @@
import { IconButton } from "@/ui";
import { tx } from "@/platform/i18n";
import { LayoutActions } from "../LayoutActions";
import { modeOf, useMarkdownModes } from "./modes";
import styles from "./Markdown.module.css";
export function MarkdownLayoutActions({ tabId }: { path: string; tabId: string }) {
const mode = useMarkdownModes((s) => modeOf(s, tabId));
return (
<div className={styles.layoutActions} role="toolbar" aria-label={tx("Markdown editor layout")}>
<IconButton
icon="editor-only"
iconSize={16}
size="small"
title="Editor Only"
action="markdown.editorOnly"
actionArg={tabId}
pressed={mode === "editor"}
/>
<IconButton
icon="editor-preview"
iconSize={16}
size="small"
title="Editor and Preview"
action="markdown.editorAndPreview"
actionArg={tabId}
pressed={mode === "split"}
/>
<IconButton
icon="preview-only"
iconSize={16}
size="small"
title="Preview Only"
action="markdown.previewOnly"
actionArg={tabId}
pressed={mode === "preview"}
/>
</div>
);
return <LayoutActions tabId={tabId} mode={mode} label={tx("Markdown editor layout")} />;
}
+9 -44
Переглянути файл
@@ -1,47 +1,12 @@
/**
* Markdown editor layout per editor tab: Editor only / Editor and Preview / Preview only. Split
* panes showing the same file each keep their own.
*/
import { create } from "zustand";
/** Markdown editor layout per editor tab: Editor only / Editor and Preview / Preview only. */
import { createLayoutModes, modeOf, type LayoutMode } from "../layoutModes";
export type MarkdownMode = "editor" | "split" | "preview";
export type MarkdownMode = LayoutMode;
export { modeOf };
const DEFAULT_KEY = "openidea.markdown.defaultMode";
const MODES: readonly MarkdownMode[] = ["editor", "split", "preview"];
const markdown = createLayoutModes("openidea.markdown.defaultMode");
function storedDefault(): MarkdownMode {
try {
const v = localStorage.getItem(DEFAULT_KEY);
return MODES.includes(v as MarkdownMode) ? (v as MarkdownMode) : "split";
} catch {
return "split";
}
}
interface ModesState {
byTab: Record<string, MarkdownMode>;
/** Mode of tabs opened since: the last one chosen. */
fallback: MarkdownMode;
}
export const useMarkdownModes = create<ModesState>(() => ({ byTab: {}, fallback: storedDefault() }));
export const modeOf = (s: ModesState, tabId: string): MarkdownMode => s.byTab[tabId] ?? s.fallback;
/** Preview Only hides the source editor of `tabId`. */
export const useMarkdownSourceHidden = (tabId: string) => useMarkdownModes((s) => modeOf(s, tabId) === "preview");
/** Fixes a shown tab's mode, so choosing one in another tab doesn't change it. */
export function pinMarkdownMode(tabId: string) {
if (useMarkdownModes.getState().byTab[tabId]) return;
useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: s.fallback } }));
}
export function setMarkdownMode(tabId: string, mode: MarkdownMode) {
useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: mode }, fallback: mode }));
try {
localStorage.setItem(DEFAULT_KEY, mode);
} catch {
// Per-viewer convenience only.
}
}
export const useMarkdownModes = markdown.useModes;
export const useMarkdownSourceHidden = markdown.useSourceHidden;
export const pinMarkdownMode = markdown.pin;
export const setMarkdownMode = markdown.set;
+95
Переглянути файл
@@ -0,0 +1,95 @@
/**
* SVG files as IDEA opens them: the source with the image viewer beside it (Editor Only / Editor and
* Preview / Preview Only), the preview redrawn from the source as it's typed.
*/
import { useEffect, useRef, type ReactNode } from "react";
import clsx from "clsx";
import { editorsFor } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { FloatingToolbar, SplitGroup, SplitHandle, SplitPanel } from "@/ui";
import { imageInput } from "../fileKinds";
import { ImageViewer } from "../ImageViewer";
import { LayoutActions } from "../LayoutActions";
import { createLayoutModes, modeOf } from "../layoutModes";
import { useLiveSvg } from "./live";
import styles from "../markdown/Markdown.module.css";
export const svgModes = createLayoutModes("openidea.svg.defaultMode");
const SPLIT_STORAGE_KEY = "openidea.svg.split";
const DEFAULT_SPLIT_LAYOUT = { editor: 50, preview: 50 };
export function SvgLayoutActions({ tabId }: { path: string; tabId: string }) {
const mode = svgModes.useModes((s) => modeOf(s, tabId));
return <LayoutActions tabId={tabId} mode={mode} label={tx("SVG editor layout")} />;
}
function SvgPreview({ path }: { path: string }) {
const source = useLiveSvg((s) => s[path]) ?? null;
return <ImageViewer input={imageInput(path)} source={source} />;
}
export function SvgEditor({
path,
tabId,
children,
actionsInTabs = false,
}: {
path: string;
tabId: string;
children: ReactNode;
actionsInTabs?: boolean;
}) {
const mode = svgModes.useModes((s) => modeOf(s, tabId));
useEffect(() => svgModes.pin(tabId), [tabId]);
const ref = useRef<HTMLDivElement>(null);
const editorRef = useRef<HTMLDivElement>(null);
// CodeMirror skips resizes right after a view update; re-measure on drags and mode changes.
useEffect(() => {
const el = editorRef.current;
if (!el || typeof ResizeObserver === "undefined") return;
let width = el.clientWidth;
const ro = new ResizeObserver(() => {
const next = el.clientWidth;
if (next === width) return;
width = next;
if (next <= 0) return;
for (const ed of editorsFor(path)) {
if (!ed.tabId || ed.tabId === tabId) ed.view.requestMeasure();
}
});
ro.observe(el);
return () => ro.disconnect();
}, [path, tabId]);
const splitBounds = mode === "split" ? { minSize: "10%", maxSize: "90%" } : {};
return (
<div ref={ref} className={clsx(styles.split, styles[`mode-${mode}`])}>
<SplitGroup
orientation="horizontal"
className={styles.group}
storageKey={mode === "split" ? SPLIT_STORAGE_KEY : undefined}
defaultLayout={mode === "split" ? DEFAULT_SPLIT_LAYOUT : undefined}
>
{/* Hidden but mounted in Preview Only, so the document stays open (see MarkdownEditor). */}
<SplitPanel id="editor" style={{ overflow: "hidden" }} disabled={mode === "preview"} {...splitBounds}>
<div ref={editorRef} className={styles.editor}>
{children}
</div>
</SplitPanel>
{mode === "split" && <SplitHandle aria-label={tx("Resize SVG preview")} />}
{mode !== "editor" && (
<SplitPanel id="preview" style={{ overflow: "hidden", display: "flex" }} {...splitBounds}>
<SvgPreview path={path} />
</SplitPanel>
)}
</SplitGroup>
{!actionsInTabs && (
<FloatingToolbar targetRef={ref}>
<SvgLayoutActions path={path} tabId={tabId} />
</FloatingToolbar>
)}
</div>
);
}
+38
Переглянути файл
@@ -0,0 +1,38 @@
/** The SVG source as typed, per file, for the preview beside it (redrawn shortly after typing stops). */
import { ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import { create } from "zustand";
import { registerEditorContribution } from "@/editor/api";
import { isSvgPath } from "../fileKinds";
export const useLiveSvg = create<Record<string, string | undefined>>(() => ({}));
const TEXT_DELAY = 300;
const publish = (path: string, text: string) =>
useLiveSvg.getState()[path] === text || useLiveSvg.setState({ [path]: text });
function livePlugin(path: string) {
return ViewPlugin.fromClass(
class {
private timer: ReturnType<typeof setTimeout> | undefined;
constructor(view: EditorView) {
publish(path, view.state.doc.toString());
}
update(u: ViewUpdate) {
if (!u.docChanged) return;
clearTimeout(this.timer);
this.timer = setTimeout(() => publish(path, u.view.state.doc.toString()), TEXT_DELAY);
}
destroy() {
clearTimeout(this.timer);
}
},
);
}
export function registerSvgLiveSource(): () => void {
return registerEditorContribution({
id: "viewers.svgLive",
extensions: (ctx) => (!ctx.virtual && isSvgPath(ctx.path) ? [livePlugin(ctx.path)] : []),
});
}
+98
Переглянути файл
@@ -0,0 +1,98 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { useEffect } from "react";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { setMarkdownMode, useMarkdownModes } from "../markdown/modes";
import { activate as activateViewers } from "../index";
import { ImageViewer, svgDataUrl } from "../ImageViewer";
import { imageInput } from "../fileKinds";
import { useLiveSvg } from "./live";
import { SvgEditor, svgModes } from "./SvgEditor";
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
...real,
call: vi.fn(() => Promise.reject(new Error("no backend"))),
};
});
const PATH = "/p/icon.svg";
// Hidden until it has loaded (jsdom never loads it), so found by tag rather than role.
const image = () => document.querySelector("img")!;
describe("SVG editor", () => {
beforeEach(() => {
localStorage.clear();
svgModes.useModes.setState({ byTab: {}, fallback: "split" });
useMarkdownModes.setState({ byTab: {}, fallback: "split" });
useLiveSvg.setState({ [PATH]: '<svg xmlns="http://www.w3.org/2000/svg" width="4" height="2"/>' });
});
afterEach(() => {
cleanup();
localStorage.clear();
});
it("shows the source and the image side by side, switching layouts without reopening the editor", () => {
let mounts = 0;
function Source() {
useEffect(() => {
mounts++;
}, []);
return <div data-testid="source" />;
}
render(
<SvgEditor path={PATH} tabId="t">
<Source />
</SvgEditor>,
);
expect(screen.getByRole("separator", { name: "Resize SVG preview" })).toBeInTheDocument();
expect(image().src).toBe(svgDataUrl(useLiveSvg.getState()[PATH]!));
// Beside the source the image viewer can't reload from disk or open the file a second time.
expect(screen.queryByRole("button", { name: "Open as Text" })).toBeNull();
expect(screen.queryByRole("button", { name: "Reload from Disk" })).toBeNull();
act(() => svgModes.set("t", "editor"));
expect(document.querySelector("img")).toBeNull();
act(() => svgModes.set("t", "preview"));
expect(image()).toBeInTheDocument();
expect(screen.getByTestId("source")).toBeInTheDocument();
expect(mounts).toBe(1);
});
it("redraws the image as the source is typed, and recovers from invalid SVG", () => {
const { rerender } = render(<ImageViewer input={imageInput(PATH)} source="<svg" />);
fireEvent.error(image());
expect(screen.getByText("The SVG source is not valid.")).toBeInTheDocument();
const fixed = '<svg xmlns="http://www.w3.org/2000/svg"/>';
rerender(<ImageViewer input={imageInput(PATH)} source={fixed} />);
expect(image().src).toBe(svgDataUrl(fixed));
expect(screen.queryByText("The SVG source is not valid.")).toBeNull();
});
it("keeps the SVG layout apart from Markdown's, and the layout actions set the tab's own", async () => {
const off = activateViewers();
setContext("textEditorActive", true);
try {
render(
<SvgEditor path={PATH} tabId="svg-tab">
<div />
</SvgEditor>,
);
setMarkdownMode("md-tab", "preview");
expect(svgModes.useModes.getState().fallback).toBe("split");
await act(() => executeAction("markdown.editorOnly", "svg-tab"));
expect(svgModes.useModes.getState().byTab["svg-tab"]).toBe("editor");
expect(useMarkdownModes.getState().byTab["md-tab"]).toBe("preview");
expect(useMarkdownModes.getState().byTab["svg-tab"]).toBeUndefined();
// The last layout chosen for an SVG is the one the next SVG opens in.
expect(localStorage.getItem("openidea.svg.defaultMode")).toBe("editor");
} finally {
setContext("textEditorActive", false);
off();
}
});
});
+6 -1
Переглянути файл
@@ -84,8 +84,13 @@ describe("file kinds", () => {
component: () => null,
});
try {
expect((await resolveFileEditor("/p/icon.svg"))?.input.kind).toBe("image");
// SVG files open as text with the image viewer beside it; a plugin's wrapper wins over it.
expect(await resolveFileEditor("/p/icon.svg")).toBeNull();
expect(await resolveFileEditor("/p/logo.png").then((r) => r?.input.kind)).toBe("image");
expect(await resolveFileEditor("/p/arch.diagram.svg")).toBeNull();
const wrappers = useTextEditorWrappers.getState().wrappers;
expect(textEditorWrapperFor(wrappers, "/p/icon.svg")?.id).toBe("viewers.svg");
expect(textEditorWrapperFor(wrappers, "/p/arch.diagram.svg")?.id).toBe("plugin.acme.diagram.canvas");
} finally {
offWrapper();
offViewers();
+4 -1
Переглянути файл
@@ -4175,5 +4175,8 @@
"Where Clause": "Where Clause",
"SQL INSERT": "SQL INSERT",
"SQL UPDATE": "SQL UPDATE",
"SQL DELETE": "SQL DELETE"
"SQL DELETE": "SQL DELETE",
"SVG editor layout": "SVG editor layout",
"Resize SVG preview": "Resize SVG preview",
"The SVG source is not valid.": "The SVG source is not valid."
}
+4 -1
Переглянути файл
@@ -10621,5 +10621,8 @@
"SQL INSERT": "SQL INSERT 语句",
"SQL UPDATE": "SQL UPDATE 语句",
"SQL DELETE": "SQL DELETE 语句",
"Column comment": "列注释"
"Column comment": "列注释",
"SVG editor layout": "SVG 编辑器布局",
"Resize SVG preview": "调整 SVG 预览大小",
"The SVG source is not valid.": "SVG 源代码无效。"
}
+9 -2
Переглянути файл
@@ -706,6 +706,8 @@ export async function openFileExternally(path: string): Promise<boolean> {
export interface TextEditorWrapperContribution {
keepAlive?: boolean;
id: string;
/** Yields to any other wrapper matching the file (a plugin's editor for `*.diagram.svg`). */
fallback?: boolean;
matches(path: string): boolean;
component: ComponentType<{ path: string; tabId: string; children: ReactNode; actionsInTabs?: boolean }>;
/** Layout controls in the tab strip; the wrapper supplies a floating fallback when tabs are hidden. */
@@ -733,8 +735,13 @@ export function textEditorWrapperFor(
wrappers: ReadonlyMap<string, TextEditorWrapperContribution>,
path: string,
): TextEditorWrapperContribution | undefined {
for (const w of wrappers.values()) if (w.matches(path)) return w;
return undefined;
let fallback: TextEditorWrapperContribution | undefined;
for (const w of wrappers.values()) {
if (!w.matches(path)) continue;
if (!w.fallback) return w;
fallback ??= w;
}
return fallback;
}
/**