diff --git a/e2e/imageViewerLayout.spec.ts b/e2e/imageViewerLayout.spec.ts index b2f069a1e..43e0d51ba 100644 --- a/e2e/imageViewerLayout.spec.ts +++ b/e2e/imageViewerLayout.spec.ts @@ -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 = - ''; - 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( + '', + ); + 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(); }); diff --git a/src/features/viewers/ImageViewer.tsx b/src/features/viewers/ImageViewer.tsx index 3145a8bc7..825994b60 100644 --- a/src/features/viewers/ImageViewer.tsx +++ b/src/features/viewers/ImageViewer.tsx @@ -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(null); const [error, setError] = useState(null); const [size, setSize] = useState(null); @@ -75,18 +86,27 @@ export function ImageViewer({ input }: { input: EditorInput }) { const canvasRef = useRef(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(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 }) {
- { - setError(null); - setReload((n) => n + 1); - }} - /> + {!live && ( + { + setError(null); + setReload((n) => n + 1); + }} + /> + )}
@@ -221,7 +244,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
- {svg && ( + {svg && !live && ( )} - {(natural || size !== null || view) && ( + {(natural || shownSize !== null || view) && (
{natural && {`${natural.w} × ${natural.h}`}} - {size !== null && {formatSize(size)}} + {shownSize !== null && {formatSize(shownSize)}} {view && {zoomLabel(z)}}
)} - {error ? ( -
{tx`Cannot show the image: ${error}`}
+ {shownError ? ( +
+ {shownError === INVALID_SVG ? tx("The SVG source is not valid.") : tx`Cannot show the image: ${shownError}`} +
) : (
- {src && ( + {shownSrc && ( {path.slice(path.lastIndexOf("/")= 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"))} /> )}
diff --git a/src/features/viewers/LayoutActions.tsx b/src/features/viewers/LayoutActions.tsx new file mode 100644 index 000000000..1d14ddb18 --- /dev/null +++ b/src/features/viewers/LayoutActions.tsx @@ -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 ( +
+ + + +
+ ); +} diff --git a/src/features/viewers/index.ts b/src/features/viewers/index.ts index 2f37e0b81..4d1fc721d 100644 --- a/src/features/viewers/index.ts +++ b/src/features/viewers/index.ts @@ -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"], diff --git a/src/features/viewers/layoutModes.ts b/src/features/viewers/layoutModes.ts new file mode 100644 index 000000000..2e9972dbc --- /dev/null +++ b/src/features/viewers/layoutModes.ts @@ -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; + /** 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>; + /** 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(() => ({ 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. + } + }, + }; +} diff --git a/src/features/viewers/markdown/MarkdownLayoutActions.tsx b/src/features/viewers/markdown/MarkdownLayoutActions.tsx index aab56690c..31de348ef 100644 --- a/src/features/viewers/markdown/MarkdownLayoutActions.tsx +++ b/src/features/viewers/markdown/MarkdownLayoutActions.tsx @@ -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 ( -
- - - -
- ); + return ; } diff --git a/src/features/viewers/markdown/modes.ts b/src/features/viewers/markdown/modes.ts index 620af5327..ab23b18f9 100644 --- a/src/features/viewers/markdown/modes.ts +++ b/src/features/viewers/markdown/modes.ts @@ -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; - /** Mode of tabs opened since: the last one chosen. */ - fallback: MarkdownMode; -} - -export const useMarkdownModes = create(() => ({ 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; diff --git a/src/features/viewers/svg/SvgEditor.tsx b/src/features/viewers/svg/SvgEditor.tsx new file mode 100644 index 000000000..797792a18 --- /dev/null +++ b/src/features/viewers/svg/SvgEditor.tsx @@ -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 ; +} + +function SvgPreview({ path }: { path: string }) { + const source = useLiveSvg((s) => s[path]) ?? null; + return ; +} + +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(null); + const editorRef = useRef(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 ( +
+ + {/* Hidden but mounted in Preview Only, so the document stays open (see MarkdownEditor). */} + +
+ {children} +
+
+ {mode === "split" && } + {mode !== "editor" && ( + + + + )} +
+ {!actionsInTabs && ( + + + + )} +
+ ); +} diff --git a/src/features/viewers/svg/live.ts b/src/features/viewers/svg/live.ts new file mode 100644 index 000000000..a2343165b --- /dev/null +++ b/src/features/viewers/svg/live.ts @@ -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>(() => ({})); + +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 | 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)] : []), + }); +} diff --git a/src/features/viewers/svg/svgEditor.test.tsx b/src/features/viewers/svg/svgEditor.test.tsx new file mode 100644 index 000000000..2f04357ea --- /dev/null +++ b/src/features/viewers/svg/svgEditor.test.tsx @@ -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(); + 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]: '' }); + }); + + 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
; + } + render( + + + , + ); + 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(); + fireEvent.error(image()); + expect(screen.getByText("The SVG source is not valid.")).toBeInTheDocument(); + const fixed = ''; + rerender(); + 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( + +
+ , + ); + 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(); + } + }); +}); diff --git a/src/features/viewers/viewers.test.ts b/src/features/viewers/viewers.test.ts index 120e8f723..934dd5d36 100644 --- a/src/features/viewers/viewers.test.ts +++ b/src/features/viewers/viewers.test.ts @@ -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(); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 120c3632f..019702e84 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -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." } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 9038744ed..bdc7a16f1 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -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 源代码无效。" } diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index c815d5b1f..2e01b3bc2 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -706,6 +706,8 @@ export async function openFileExternally(path: string): Promise { 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, 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; } /**