дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-01 06:42:54 +02:00
fix(viewers): reload preview images when files change on disk (#6952)
Preview image data URLs were cached by path forever. The cache now drops entries on fsChanged and open Markdown and reStructuredText previews reload the affected images. Co-authored-by: zhiai007 <[email protected]>
Цей коміт міститься в:
1 джерело
edd6746439
коміт
08249ca5fd
4 files changed
+445
-29
No files matched your search
@@ -85,7 +85,7 @@ import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
import { iconNode } from "@/ui/iconNode";
|
||||
import { isMarkdownPath } from "../fileKinds";
|
||||
import { attachPanZoom } from "../panZoom";
|
||||
import { imageUrl } from "../previewImages";
|
||||
import { createPreviewImageLoader } from "../previewImages";
|
||||
|
||||
/**
|
||||
* Line of the heading `anchor` in the Markdown file `path`, from an open editor's text (unsaved
|
||||
@@ -480,7 +480,18 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
let live = true;
|
||||
const size = (img: HTMLImageElement, intrinsic?: { w: number; h: number } | null) =>
|
||||
applyImageZoomWidth(img, intrinsic, img.closest<HTMLElement>(`.${IMAGE_ZOOM}`) ?? img);
|
||||
const resetImageSize = (img: HTMLImageElement) => {
|
||||
const box = img.closest<HTMLElement>(`.${IMAGE_ZOOM}`) ?? img;
|
||||
delete img.dataset.naturalWidth;
|
||||
delete box.dataset.naturalWidth;
|
||||
box.style.removeProperty("--image-width");
|
||||
};
|
||||
const bindImageUrl = (img: HTMLImageElement, url: string, asyncLoad: boolean) => {
|
||||
const changed = img.getAttribute("src") !== url;
|
||||
if (changed && img.hasAttribute("src")) {
|
||||
resetImageSize(img);
|
||||
size(img);
|
||||
}
|
||||
const svgSize = svgDataUrlSize(url);
|
||||
if (svgSize && size(img, svgSize) && asyncLoad) {
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
@@ -495,11 +506,31 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
}
|
||||
};
|
||||
if (img.getAttribute("src") !== url) img.src = url;
|
||||
if (!img.hasAttribute("data-natural-width") && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||
if (changed) img.src = url;
|
||||
// Only trust synchronous naturalWidth when `src` did not change: right after assigning a new `src`,
|
||||
// browsers still report the previous image's `complete` / `naturalWidth` until the new decode finishes.
|
||||
if (
|
||||
!changed &&
|
||||
!img.hasAttribute("data-natural-width") &&
|
||||
img.complete &&
|
||||
img.naturalWidth > 0 &&
|
||||
img.naturalHeight > 0
|
||||
) {
|
||||
size(img, { w: img.naturalWidth, h: img.naturalHeight });
|
||||
}
|
||||
};
|
||||
const images = createPreviewImageLoader(
|
||||
(img, url) => {
|
||||
img.classList.remove(styles.blocked!);
|
||||
bindImageUrl(img, url, true);
|
||||
},
|
||||
(img) => {
|
||||
resetImageSize(img);
|
||||
img.removeAttribute("src");
|
||||
img.classList.add(styles.blocked!);
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
},
|
||||
);
|
||||
const imgs = [...root.querySelectorAll<HTMLImageElement>("img[data-src]")];
|
||||
imgs.forEach((img) => {
|
||||
attachImagePanZoom(img);
|
||||
@@ -515,10 +546,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
img.title = "Remote images are not loaded";
|
||||
return;
|
||||
}
|
||||
imageUrl(target.path).then(
|
||||
(url) => live && bindImageUrl(img, url, true),
|
||||
() => live && img.classList.add(styles.blocked!),
|
||||
);
|
||||
images.load(img, target.path);
|
||||
});
|
||||
root.querySelectorAll<HTMLElement>("pre > code").forEach((code) => {
|
||||
const pre = code.parentElement!;
|
||||
@@ -531,6 +559,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
images.dispose();
|
||||
for (const img of imgs) img.onload = null;
|
||||
};
|
||||
}, [html, path]);
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||
import { Text } from "@codemirror/state";
|
||||
import * as ipc from "@/platform/ipc";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { useLiveMarkdown } from "./markdown/live";
|
||||
import { MarkdownEditor } from "./markdown/MarkdownEditor";
|
||||
import { useMarkdownModes } from "./markdown/modes";
|
||||
import { imageUrl } from "./previewImages";
|
||||
import { useLiveRst } from "./rst/live";
|
||||
import { RstEditor } from "./rst/RstEditor";
|
||||
import { rstModes } from "./rst/RstLayoutActions";
|
||||
|
||||
const svgUrl = (width: number, height: number) =>
|
||||
`data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}"></svg>`)}`;
|
||||
|
||||
const liveDoc = (lines: string[]) => ({
|
||||
text: Text.of(lines),
|
||||
topLine: 0,
|
||||
sourceAtEnd: false,
|
||||
scrollSeq: 0,
|
||||
fontZoom: 0,
|
||||
previewTop: 0,
|
||||
caretLine: 0,
|
||||
caretSeq: 0,
|
||||
});
|
||||
|
||||
describe("preview image disk refresh", () => {
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useMarkdownModes.setState({ byTab: {}, fallback: "split" });
|
||||
rstModes.useModes.setState({ byTab: {}, fallback: "split" });
|
||||
useLiveMarkdown.setState({}, true);
|
||||
useLiveRst.setState({}, true);
|
||||
});
|
||||
|
||||
it("evicts cached image URLs on file and parent-directory fsChanged without dropping unrelated paths", async () => {
|
||||
let version = 1;
|
||||
const fsReadImage = vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => ({
|
||||
status: "ok",
|
||||
data: `data:image/png;base64,${path}:v${version}`,
|
||||
}));
|
||||
|
||||
const a1 = await imageUrl("/p/cache/a.png");
|
||||
const b1 = await imageUrl("/p/cache/b.png");
|
||||
const dirImg1 = await imageUrl("/p/cache/assets/diagram.png");
|
||||
expect(await imageUrl("/p/cache/a.png")).toBe(a1);
|
||||
expect(fsReadImage).toHaveBeenCalledTimes(3);
|
||||
|
||||
version = 2;
|
||||
emitLocalIdeEvent({
|
||||
type: "fsChanged",
|
||||
created: [],
|
||||
modified: ["/p/cache/a.png"],
|
||||
removed: [],
|
||||
});
|
||||
|
||||
expect(await imageUrl("/p/cache/a.png")).toBe("data:image/png;base64,/p/cache/a.png:v2");
|
||||
expect(await imageUrl("/p/cache/b.png")).toBe(b1);
|
||||
expect(fsReadImage).toHaveBeenCalledTimes(4);
|
||||
|
||||
version = 3;
|
||||
emitLocalIdeEvent({
|
||||
type: "fsChanged",
|
||||
created: ["/p/cache/assets"],
|
||||
modified: [],
|
||||
removed: [],
|
||||
});
|
||||
|
||||
expect(await imageUrl("/p/cache/assets/diagram.png")).toBe("data:image/png;base64,/p/cache/assets/diagram.png:v3");
|
||||
expect(dirImg1).toBe("data:image/png;base64,/p/cache/assets/diagram.png:v1");
|
||||
expect(await imageUrl("/p/cache/b.png")).toBe(b1);
|
||||
});
|
||||
|
||||
it("keeps a newer reload when an earlier in-flight read rejects or resolves late", async () => {
|
||||
const imgPath = "/p/md-race/shot.png";
|
||||
const mdPath = "/p/md-race/README.md";
|
||||
const resolvers: Array<{ resolve: (v: { status: "ok"; data: string }) => void; reject: (e: Error) => void }> = [];
|
||||
|
||||
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve, reject) => {
|
||||
resolvers.push({ resolve, reject });
|
||||
}),
|
||||
);
|
||||
|
||||
useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" });
|
||||
useLiveMarkdown.setState({ [mdPath]: liveDoc([""]) });
|
||||
|
||||
render(
|
||||
<MarkdownEditor path={mdPath} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(resolvers).toHaveLength(1));
|
||||
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
|
||||
});
|
||||
await waitFor(() => expect(resolvers).toHaveLength(2));
|
||||
|
||||
act(() => {
|
||||
resolvers[1]!.resolve({ status: "ok", data: "data:image/png;base64,FRESH" });
|
||||
});
|
||||
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Shot"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,FRESH",
|
||||
);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
resolvers[0]!.reject(new Error("stale read failed"));
|
||||
});
|
||||
await act(async () => {});
|
||||
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Shot"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,FRESH",
|
||||
);
|
||||
expect(await imageUrl(imgPath)).toBe("data:image/png;base64,FRESH");
|
||||
});
|
||||
|
||||
it("reloads Markdown preview images on fsChanged, updates dimensions, and recovers after removal", async () => {
|
||||
const imgPath = "/p/md-reload/diagram.svg";
|
||||
const mdPath = "/p/md-reload/README.md";
|
||||
let current: string | null = svgUrl(320, 180);
|
||||
|
||||
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => {
|
||||
if (path === imgPath && current !== null) return { status: "ok", data: current };
|
||||
return { status: "error", error: { kind: "notFound", message: path } } as never;
|
||||
});
|
||||
|
||||
useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" });
|
||||
useLiveMarkdown.setState({ [mdPath]: liveDoc([""]) });
|
||||
|
||||
render(
|
||||
<MarkdownEditor path={mdPath} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
await waitFor(() => {
|
||||
const img = preview.querySelector<HTMLImageElement>('img[alt="Diagram"]');
|
||||
expect(img?.getAttribute("src")).toBe(svgUrl(320, 180));
|
||||
});
|
||||
|
||||
const img = preview.querySelector<HTMLImageElement>('img[alt="Diagram"]')!;
|
||||
const box = img.closest<HTMLElement>(".image-zoom") ?? img;
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("320px");
|
||||
|
||||
current = svgUrl(640, 240);
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(img.getAttribute("src")).toBe(svgUrl(640, 240));
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("640px");
|
||||
});
|
||||
|
||||
current = null;
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [imgPath] });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(img.getAttribute("src")).toBeNull();
|
||||
expect(img.hasAttribute("data-natural-width")).toBe(false);
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("");
|
||||
});
|
||||
|
||||
current = svgUrl(480, 200);
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [imgPath], modified: [], removed: [] });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(img.getAttribute("src")).toBe(svgUrl(480, 200));
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("480px");
|
||||
});
|
||||
});
|
||||
|
||||
it("updates raster image width on reload even when old naturalWidth is still reported synchronously", async () => {
|
||||
const imgPath = "/p/md-raster/shot.png";
|
||||
const mdPath = "/p/md-raster/README.md";
|
||||
let current = "data:image/png;base64,V1";
|
||||
|
||||
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => {
|
||||
if (path === imgPath) return { status: "ok", data: current };
|
||||
return { status: "error", error: { kind: "notFound", message: path } } as never;
|
||||
});
|
||||
|
||||
useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" });
|
||||
useLiveMarkdown.setState({ [mdPath]: liveDoc([""]) });
|
||||
|
||||
render(
|
||||
<MarkdownEditor path={mdPath} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Shot"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,V1",
|
||||
);
|
||||
});
|
||||
|
||||
const img = preview.querySelector<HTMLImageElement>('img[alt="Shot"]')!;
|
||||
const box = img.closest<HTMLElement>(".image-zoom") ?? img;
|
||||
let naturalWidth = 960;
|
||||
let naturalHeight = 600;
|
||||
Object.defineProperty(img, "complete", { get: () => true, configurable: true });
|
||||
Object.defineProperty(img, "naturalWidth", { get: () => naturalWidth, configurable: true });
|
||||
Object.defineProperty(img, "naturalHeight", { get: () => naturalHeight, configurable: true });
|
||||
act(() => {
|
||||
img.dispatchEvent(new Event("load"));
|
||||
});
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("960px");
|
||||
|
||||
// Simulate HTML spec: right after `img.src = newUrl`, `complete` is still true and `naturalWidth` is still 960
|
||||
// until the new image decodes and fires `load`.
|
||||
current = "data:image/png;base64,V2";
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(img.getAttribute("src")).toBe("data:image/png;base64,V2");
|
||||
});
|
||||
expect(img.hasAttribute("data-natural-width")).toBe(false);
|
||||
|
||||
naturalWidth = 420;
|
||||
naturalHeight = 280;
|
||||
act(() => {
|
||||
img.dispatchEvent(new Event("load"));
|
||||
});
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("420px");
|
||||
});
|
||||
|
||||
it("reloads reStructuredText preview images when modified on disk", async () => {
|
||||
const rstPath = "/p/rst-reload/index.rst";
|
||||
const imgPath = "/p/rst-reload/chart.png";
|
||||
let current: string | null = "data:image/png;base64,OLD";
|
||||
|
||||
vi.spyOn(ipc.commands, "rstPreview").mockResolvedValue({
|
||||
status: "ok",
|
||||
data: '<main><img alt="Chart" src="chart.png" /></main>',
|
||||
});
|
||||
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => {
|
||||
if (path === imgPath && current !== null) return { status: "ok", data: current };
|
||||
return { status: "error", error: { kind: "notFound", message: path } } as never;
|
||||
});
|
||||
|
||||
useLiveRst.setState({ [rstPath]: "Title\n=====\n" });
|
||||
render(
|
||||
<RstEditor path={rstPath} tabId="t">
|
||||
<div />
|
||||
</RstEditor>,
|
||||
);
|
||||
|
||||
const preview = document.querySelector<HTMLElement>('[aria-label="reStructuredText preview"]')!;
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,OLD",
|
||||
);
|
||||
});
|
||||
|
||||
current = "data:image/png;base64,NEW";
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,NEW",
|
||||
);
|
||||
});
|
||||
|
||||
current = null;
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [imgPath] });
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBeNull();
|
||||
});
|
||||
|
||||
current = "data:image/png;base64,RESTORED";
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [imgPath], modified: [], removed: [] });
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,RESTORED",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,97 @@
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
|
||||
/** Loaded local images by absolute path (data URLs), shared by all previews. */
|
||||
const imageCache = new Map<string, Promise<string>>();
|
||||
const IMAGE_CACHE_LIMIT = 64;
|
||||
|
||||
type ImageChangeListener = (changed: readonly string[]) => void;
|
||||
const listeners = new Set<ImageChangeListener>();
|
||||
let offFs: (() => void) | null = null;
|
||||
|
||||
function matchesChanged(path: string, changed: readonly string[]): boolean {
|
||||
return changed.some((entry) => isSameOrInside(path, entry));
|
||||
}
|
||||
|
||||
function ensureWatching(): void {
|
||||
offFs ??= onIdeEvent("fsChanged", (e) => {
|
||||
const changed = [...e.created, ...e.modified, ...e.removed];
|
||||
if (!changed.length) return;
|
||||
for (const cached of [...imageCache.keys()]) {
|
||||
if (matchesChanged(cached, changed)) imageCache.delete(cached);
|
||||
}
|
||||
for (const listener of [...listeners]) listener(changed);
|
||||
});
|
||||
}
|
||||
|
||||
export function imageUrl(path: string): Promise<string> {
|
||||
let p = imageCache.get(path);
|
||||
if (!p) {
|
||||
p = call(commands.fsReadImage(path));
|
||||
p.catch(() => imageCache.delete(path));
|
||||
ensureWatching();
|
||||
let pending = imageCache.get(path);
|
||||
if (!pending) {
|
||||
const request = call(commands.fsReadImage(path));
|
||||
request.catch(() => {
|
||||
if (imageCache.get(path) === request) imageCache.delete(path);
|
||||
});
|
||||
if (imageCache.size >= IMAGE_CACHE_LIMIT) imageCache.delete(imageCache.keys().next().value!);
|
||||
imageCache.set(path, p);
|
||||
imageCache.set(path, request);
|
||||
pending = request;
|
||||
}
|
||||
return p;
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Loads local preview images and reloads them whenever their disk paths change. */
|
||||
export function createPreviewImageLoader(
|
||||
onLoad: (img: HTMLImageElement, url: string) => void,
|
||||
onError: (img: HTMLImageElement) => void,
|
||||
) {
|
||||
let active = true;
|
||||
const groups = new Map<string, { imgs: HTMLImageElement[]; gen: number }>();
|
||||
let off: (() => void) | null = null;
|
||||
|
||||
const apply = (
|
||||
path: string,
|
||||
group: { imgs: HTMLImageElement[]; gen: number },
|
||||
targets: readonly HTMLImageElement[],
|
||||
) => {
|
||||
const gen = group.gen;
|
||||
imageUrl(path).then(
|
||||
(url) => {
|
||||
if (!active || group.gen !== gen) return;
|
||||
for (const img of targets) onLoad(img, url);
|
||||
},
|
||||
() => {
|
||||
if (!active || group.gen !== gen) return;
|
||||
for (const img of targets) onError(img);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
load(img: HTMLImageElement, path: string) {
|
||||
let group = groups.get(path);
|
||||
if (!group) {
|
||||
group = { imgs: [], gen: 0 };
|
||||
groups.set(path, group);
|
||||
if (!off) {
|
||||
ensureWatching();
|
||||
const onChanged: ImageChangeListener = (changed) => {
|
||||
for (const [watchedPath, watchedGroup] of groups) {
|
||||
if (!matchesChanged(watchedPath, changed)) continue;
|
||||
watchedGroup.gen++;
|
||||
apply(watchedPath, watchedGroup, watchedGroup.imgs);
|
||||
}
|
||||
};
|
||||
listeners.add(onChanged);
|
||||
off = () => listeners.delete(onChanged);
|
||||
}
|
||||
}
|
||||
group.imgs.push(img);
|
||||
apply(path, group, [img]);
|
||||
},
|
||||
dispose() {
|
||||
active = false;
|
||||
off?.();
|
||||
groups.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import { maybeEditorService } from "@/workbench/contributions";
|
||||
import { EmptyState, FloatingToolbar, Spinner, SplitGroup, SplitHandle, SplitPanel, selectableText } from "@/ui";
|
||||
import { modeOf } from "../layoutModes";
|
||||
import { ANCHOR_PREFIX, resolveLink, sanitizePreviewHtml } from "../markdown/render";
|
||||
import { imageUrl } from "../previewImages";
|
||||
import { createPreviewImageLoader } from "../previewImages";
|
||||
import { useLiveRst } from "./live";
|
||||
import { RstLayoutActions, rstModes } from "./RstLayoutActions";
|
||||
import styles from "../markdown/Markdown.module.css";
|
||||
@@ -25,10 +25,20 @@ const DEFAULT_SPLIT_LAYOUT = { editor: 50, preview: 50 };
|
||||
type Rendered = { html: string } | { error: string };
|
||||
|
||||
/** Puts docutils' `html` into `root`: sanitized, local images loaded, code highlighted. */
|
||||
function fill(root: HTMLElement, html: string, path: string, isLive: () => boolean) {
|
||||
function fill(root: HTMLElement, html: string, path: string) {
|
||||
const template = document.createElement("template");
|
||||
template.innerHTML = sanitizePreviewHtml(html);
|
||||
root.replaceChildren(template.content);
|
||||
const images = createPreviewImageLoader(
|
||||
(img, url) => {
|
||||
img.classList.remove(styles.blocked!);
|
||||
if (img.getAttribute("src") !== url) img.src = url;
|
||||
},
|
||||
(img) => {
|
||||
img.removeAttribute("src");
|
||||
img.classList.add(styles.blocked!);
|
||||
},
|
||||
);
|
||||
root.querySelectorAll<HTMLImageElement>("img[data-src]").forEach((img) => {
|
||||
const src = img.dataset.src ?? "";
|
||||
if (/^data:image\//i.test(src)) {
|
||||
@@ -41,19 +51,13 @@ function fill(root: HTMLElement, html: string, path: string, isLive: () => boole
|
||||
img.title = tx("Remote images are not loaded");
|
||||
return;
|
||||
}
|
||||
imageUrl(target.path).then(
|
||||
(url) => {
|
||||
if (isLive()) img.src = url;
|
||||
},
|
||||
() => {
|
||||
if (isLive()) img.classList.add(styles.blocked!);
|
||||
},
|
||||
);
|
||||
images.load(img, target.path);
|
||||
});
|
||||
root.querySelectorAll<HTMLElement>("pre.code > code").forEach((code) => {
|
||||
const lang = [...code.parentElement!.classList].find((c) => c !== "code" && c !== "literal-block") ?? null;
|
||||
void highlightInto(code, code.textContent ?? "", lang);
|
||||
});
|
||||
return () => images.dispose();
|
||||
}
|
||||
|
||||
function RstPreview({ path }: { path: string }) {
|
||||
@@ -84,11 +88,7 @@ function RstPreview({ path }: { path: string }) {
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root || html === null) return;
|
||||
let live = true;
|
||||
fill(root, html, path, () => live);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
return fill(root, html, path);
|
||||
}, [html, path]);
|
||||
|
||||
const scrollTo = (id: string) =>
|
||||
|
||||
Reference in new issue
Заблокувати користувача