diff --git a/src/features/viewers/ImageViewer.tsx b/src/features/viewers/ImageViewer.tsx index 825994b60..b07b3d5df 100644 --- a/src/features/viewers/ImageViewer.tsx +++ b/src/features/viewers/ImageViewer.tsx @@ -157,9 +157,18 @@ export function ImageViewer({ input, source }: { input: EditorInput; source?: st useForwardFocus(live ? NO_FOCUS_TARGET : rootRef); const onLoad = (img: HTMLImageElement) => { + if (!live) return applyNatural(img.naturalWidth, img.naturalHeight); + // WebKit keeps the old natural size when a sized gets a new SVG src; measure a detached copy. + const loaded = img.src; + const probe = new Image(); + probe.onload = () => img.src === loaded && applyNatural(probe.naturalWidth, probe.naturalHeight); + probe.src = loaded; + }; + + const applyNatural = (naturalW: number, naturalH: number) => { // SVGs without intrinsic size report 0×0; show them at a usable size. - const w = img.naturalWidth || 300; - const h = img.naturalHeight || 150; + const w = naturalW || 300; + const h = naturalH || 150; setNatural({ w, h }); const a = available(); const el = canvasRef.current; diff --git a/src/features/viewers/svg/svgEditor.test.tsx b/src/features/viewers/svg/svgEditor.test.tsx index 2f04357ea..220aa198c 100644 --- a/src/features/viewers/svg/svgEditor.test.tsx +++ b/src/features/viewers/svg/svgEditor.test.tsx @@ -72,6 +72,39 @@ describe("SVG editor", () => { expect(screen.queryByText("The SVG source is not valid.")).toBeNull(); }); + it("measures a retyped SVG's size from a fresh image, not the sized ", () => { + // WebKit reports the previous natural size on the shown ; a detached Image reports the new one. + const probes: { onload: (() => void) | null; src: string; naturalWidth: number; naturalHeight: number }[] = []; + vi.stubGlobal( + "Image", + class { + onload: (() => void) | null = null; + naturalWidth = 360; + naturalHeight = 300; + set src(value: string) { + this._src = value; + probes.push(this); + } + get src() { + return this._src; + } + _src = ""; + }, + ); + try { + const source = ''; + render(); + Object.defineProperty(image(), "naturalWidth", { value: 400 }); + Object.defineProperty(image(), "naturalHeight", { value: 300 }); + fireEvent.load(image()); + expect(probes.map((p) => p.src)).toEqual([svgDataUrl(source)]); + act(() => probes[0]?.onload?.()); + expect(screen.getByText("360 × 300")).toBeInTheDocument(); + } finally { + vi.unstubAllGlobals(); + } + }); + 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);