fix(markdown): open preview links to another file at the linked heading (#5422)

Clicking a link to a heading in another file (e.g. [§5.2](b.md#52-状态机)) in the Markdown preview opened the file at the top. The destination now opens at the heading, in Preview Only and split mode, also when the file wasn't open yet (the preview scrolls once it has rendered). Markdown file-type aliases are honoured and a later link click wins over a slower earlier one.

Co-authored-by: fun90 <13536188+fun90@users.noreply.github.com>
This commit is contained in:
fun90
2026-11-23 21:21:17 +08:00
committed by GitHub
co-authored by fun90
parent db8b553364
commit 261eb03009
6 changed files with 278 additions and 14 deletions
+39
View File
@@ -487,6 +487,45 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
});
for (const mode of ["Preview Only", "Editor and Preview"]) {
test(`Markdown ${mode} reveals a cross-file heading on first open`, async ({ workbench: page }) => {
const path = "/dev/acme-api/linked-heading.md";
const heading = "5.2 状态机";
const spacer = Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.`).join("\n\n");
const target = `# Destination\n\n${spacer}\n\n## ${heading}\n\n${spacer}`;
const editor = await openFromTree(page, "README.md");
await page.evaluate(
async ({ path, target }) => {
const backendModule = "/src/editor/core/backend.ts";
const routeModule = "/src/platform/tauriCore.ts";
const { docBackend } = await import(/* @vite-ignore */ backendModule);
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
docBackend().files.set(path, target);
setInvokeRoute((cmd: string, args?: Record<string, unknown>) =>
cmd === "fs_read_text" && args?.path === path ? Promise.resolve(target) : null,
);
},
{ path, target },
);
await editor.locator(".cm-content").focus();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText("[Linked heading](linked-heading.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA)");
if (mode === "Preview Only") await page.getByRole("button", { name: mode, exact: true }).click();
const destinationTab = page.getByRole("tab", { name: "linked-heading.md", exact: true });
const preview = page.getByRole("document", { name: "Markdown preview" });
await expect(destinationTab).toHaveCount(0);
await preview.getByRole("link", { name: "Linked heading" }).click();
await expect(destinationTab).toHaveAttribute("aria-selected", "true");
await expect(page.getByRole("button", { name: mode, exact: true })).toHaveAttribute("aria-pressed", "true");
await expect(preview.getByRole("heading", { name: heading })).toBeInViewport({ ratio: 1 });
if (mode === "Editor and Preview") {
await expect(editor.locator(".cm-line", { hasText: heading })).toBeInViewport({ ratio: 1 });
}
});
}
test("Markdown preview keeps following find and edits after scrolling the source", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
+6 -4
View File
@@ -10,6 +10,7 @@ export const BINARY_KIND = "binary";
const IMAGE_EXTENSIONS = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "ico", "bmp", "avif"]);
const MARKDOWN_EXTENSIONS = new Set(["md", "markdown", "mdown", "mkd", "mkdn", "mdwn"]);
const MARKDOWN_SOURCE_EXTENSIONS = new Set([...MARKDOWN_EXTENSIONS, "mdx", "ronn", "workbook"]);
function extension(path: string): string {
const name = path.slice(path.lastIndexOf("/") + 1);
@@ -21,12 +22,13 @@ export const isImagePath = (path: string) => IMAGE_EXTENSIONS.has(extension(path
export const isSvgPath = (path: string) => extension(path) === "svg";
/**
* Whether `path` gets the Markdown preview, decided synchronously so a tab never opens
* without it first: Markdown by Settings › File Types.
* Whether `path` gets the Markdown preview under Settings › File Types.
* The source check also includes Markdown extensions that open in the editor alone.
*/
export function isMarkdownPath(path: string): boolean {
export function isMarkdownPath(path: string, mode: "preview" | "source" = "preview"): boolean {
const { settings, project } = useProject.getState();
return hasFileType(path, ["markdown"], MARKDOWN_EXTENSIONS, settings?.files, project?.root ?? null);
const extensions = mode === "source" ? MARKDOWN_SOURCE_EXTENSIONS : MARKDOWN_EXTENSIONS;
return hasFileType(path, ["markdown"], extensions, settings?.files, project?.root ?? null);
}
/** Whether the file's name matches one of `patterns` (`*.xlsx`); Windows/macOS match case-insensitively. */
@@ -50,6 +50,7 @@ import { MarkdownLayoutActions } from "./MarkdownLayoutActions";
import {
ANCHOR_PREFIX,
createMarkdownRenderer,
headingLine,
previewLineAtOffset,
previewOffsetForLine,
resolveLink,
@@ -59,6 +60,7 @@ import { applyImageZoomWidth, svgDataUrlSize } from "@/ui/svgSize";
import styles from "./Markdown.module.css";
import { tx } from "@/platform/i18n";
import { wheelZoomStep } from "@/platform/wheelZoom";
import { isMarkdownPath } from "../fileKinds";
import { attachPanZoom } from "../panZoom";
/** Loaded local images by absolute path (data URLs), shared by all previews. */
@@ -76,6 +78,18 @@ function imageUrl(path: string): Promise<string> {
return p;
}
/**
* Line of the heading `anchor` in the Markdown file `path`, from an open editor's text (unsaved
* edits included) or else the file on disk; undefined when the file is not Markdown, cannot be
* read or has no such heading.
*/
async function anchorLine(path: string, anchor: string): Promise<number | undefined> {
if (!isMarkdownPath(path, "source")) return undefined;
const open = editorsFor(path)[0];
const text = open ? open.view.state.doc.toString() : await call(commands.fsReadText(path)).catch(() => null);
return (text === null ? null : headingLine(text, anchor)) ?? undefined;
}
function openExternal(url: string) {
if (isTauri()) void import("@tauri-apps/plugin-opener").then((m) => m.openUrl(url)).catch(() => {});
else window.open(url, "_blank", "noopener");
@@ -209,6 +223,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
const html = useMemo(() => render(deferred), [render, deferred]);
const renderSvg = html.includes(' data-math="') ? use(loadSvgRenderer()) : null;
const ref = useRef<HTMLDivElement>(null);
const linkRequest = useRef(0);
const blocks = useRef<ReturnType<typeof blocksOf>>([]);
const theme = useSyncExternalStore(subscribeTheme, themeKey, () => "");
const diagrams = useRef<Node[]>([]);
@@ -223,7 +238,12 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
/** `<details>` the reader opened or closed, by position: each edit re-renders them as written. */
const toggled = useRef(new Map<number, boolean>());
useLayoutEffect(() => toggled.current.clear(), [path]);
useLayoutEffect(() => {
toggled.current.clear();
return () => {
linkRequest.current++;
};
}, [path]);
useLayoutEffect(() => {
ref.current?.querySelectorAll("details").forEach((d, i) => {
const open = toggled.current.get(i);
@@ -382,6 +402,8 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
useLayoutEffect(() => {
const root = ref.current;
if (!root || caretSeq === seenCaret.current) return;
// First-open navigation can arrive before the destination's deferred Markdown is rendered.
if (!sync && deferred !== text) return;
seenCaret.current = caretSeq;
if (sync) return;
if (find && find.currentMatchIndex >= 0) {
@@ -403,7 +425,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
restoreRetry.current = null;
}
setShownLine(path, caretLine);
}, [caretSeq, caretLine, sync, path, find]);
}, [caretSeq, caretLine, sync, path, find, deferred, text]);
// Search (⌘F) and selection occurrence highlights in the preview.
useLayoutEffect(() => {
@@ -542,6 +564,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
e.preventDefault();
const target = resolveLink(path, a.getAttribute("href") ?? "");
if (!target) return;
const request = ++linkRequest.current;
const scrollTo = (id: string) => {
const root = ref.current;
if (!root) return;
@@ -555,10 +578,14 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
else if (target.kind === "anchor") scrollTo(target.id);
else if (target.path === path && target.anchor) scrollTo(target.anchor);
else
void maybeEditorService()?.openFile(target.path, {
focus: true,
...(target.line !== undefined ? { selection: { line: target.line, col: 0 } } : {}),
});
void (async () => {
const line = target.line ?? (target.anchor ? await anchorLine(target.path, target.anchor) : undefined);
if (request !== linkRequest.current) return;
await maybeEditorService()?.openFile(target.path, {
focus: true,
...(line !== undefined ? { selection: { line, col: 0 } } : {}),
});
})();
};
return (
@@ -0,0 +1,140 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { _addEditor, _removeEditor, editorContributions, type EditorDocContext } from "@/editor/api";
import { fontZoom } from "@/editor/core/cm/prefs";
import { useContextKeys } from "@/platform/context";
import { useProject } from "@/platform/project";
import type { Settings } from "@/platform/ipc";
import { registerMarkdownLiveSource, useLiveMarkdown } from "./live";
import { MarkdownEditor } from "./MarkdownEditor";
import { useMarkdownModes } from "./modes";
const openFile = vi.fn(async () => {});
const targetText = "# 成交对账\n\n正文\n\n## 5.2 状态机\n";
const disk: Record<string, string | Promise<string>> = {
"/p/b.md": targetText,
"/p/c.txt": targetText,
"/p/alias.mkdn": targetText,
"/p/assigned.txt": targetText,
"/p/plain.md": targetText,
"/p/source.mdx": targetText,
};
vi.mock("@/workbench/contributions", async (importOriginal) => ({
...(await importOriginal<typeof import("@/workbench/contributions")>()),
maybeEditorService: () => ({ openFile }),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const ipc = await importOriginal<typeof import("@/platform/ipc")>();
return {
...ipc,
commands: { ...ipc.commands, fsReadText: (path: string) => ({ readText: path }) },
call: (request: unknown) => {
const path = (request as { readText?: string } | null)?.readText;
if (path === undefined) return ipc.call(request as never);
return path in disk ? Promise.resolve(disk[path]) : Promise.reject(new Error("missing"));
},
};
});
const ctx: EditorDocContext = { doc: 1, path: "/p/a.md", language: "markdown", uiMode: null, readOnly: false };
const doc = [
"[disk](b.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA)",
"[open](d.md#52-状态机)",
"[line](b.md#L3)",
"[none](b.md#missing)",
"[text](c.txt#52-状态机)",
"[alias](alias.mkdn#52-状态机)",
"[assigned](assigned.txt#52-状态机)",
"[plain](plain.md#52-状态机)",
"[source](source.mdx#52-状态机)",
"",
].join("\n\n");
describe("preview links to a heading in another file", () => {
const disposers: Array<() => void> = [];
const views: EditorView[] = [];
beforeEach(() => {
openFile.mockClear();
const settings = useProject.getState().settings;
useProject.setState({
settings: {
files: { fileTypeOverrides: { "/p/assigned.txt": "markdown", "/p/plain.md": "plaintext" } },
} as Settings,
});
disposers.push(() => useProject.setState({ settings }));
disposers.push(registerMarkdownLiveSource());
useContextKeys.setState({ projectOpen: true, textEditorActive: true });
const live = editorContributions().find((c) => c.id === "viewers.markdownLive")!;
const view = new EditorView({ state: EditorState.create({ doc, extensions: [fontZoom, live.extensions(ctx)] }) });
// An open editor's unsaved text wins over the file on disk.
const other = new EditorView({ state: EditorState.create({ doc: "# D\n\nnew line\n\n## 5.2 状态机\n" }) });
views.push(view, other);
for (const handle of [
{ view, ctx },
{ view: other, ctx: { ...ctx, doc: 2, path: "/p/d.md" } },
]) {
_addEditor(handle);
disposers.push(() => _removeEditor(handle));
}
act(() => useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, t: "preview" } })));
});
afterEach(() => {
cleanup();
for (const view of views.splice(0)) view.destroy();
for (const dispose of disposers.splice(0).reverse()) dispose();
useLiveMarkdown.setState({}, true);
useContextKeys.setState({}, true);
});
const renderPreview = async () => {
render(
<MarkdownEditor path={ctx.path} tabId="t">
<div />
</MarkdownEditor>,
);
const preview = screen.getByRole("document", { name: "Markdown preview" });
await waitFor(() => expect(preview.querySelectorAll("a")).toHaveLength(9));
};
it("opens the file at the heading line", async () => {
await renderPreview();
const click = async (name: string) => {
openFile.mockClear();
fireEvent.click(screen.getByText(name));
await waitFor(() => expect(openFile).toHaveBeenCalledTimes(1));
return openFile.mock.calls[0];
};
expect(await click("disk")).toEqual(["/p/b.md", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("open")).toEqual(["/p/d.md", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("line")).toEqual(["/p/b.md", { focus: true, selection: { line: 2, col: 0 } }]);
expect(await click("none")).toEqual(["/p/b.md", { focus: true }]);
expect(await click("text")).toEqual(["/p/c.txt", { focus: true }]);
expect(await click("alias")).toEqual(["/p/alias.mkdn", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("assigned")).toEqual(["/p/assigned.txt", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("plain")).toEqual(["/p/plain.md", { focus: true }]);
expect(await click("source")).toEqual(["/p/source.mdx", { focus: true, selection: { line: 4, col: 0 } }]);
});
it("keeps a slow heading lookup from superseding a newer link", async () => {
await renderPreview();
let resolve!: (text: string) => void;
disk["/p/b.md"] = new Promise<string>((done) => {
resolve = done;
});
try {
fireEvent.click(screen.getByText("disk"));
fireEvent.click(screen.getByText("line"));
await waitFor(() =>
expect(openFile).toHaveBeenCalledExactlyOnceWith("/p/b.md", { focus: true, selection: { line: 2, col: 0 } }),
);
await act(async () => resolve(targetText));
expect(openFile).toHaveBeenCalledTimes(1);
} finally {
disk["/p/b.md"] = targetText;
}
});
});
@@ -5,6 +5,7 @@ import { renderMath } from "@/editor/lsp/markdownMath";
import {
createMarkdownRenderer,
frontMatter,
headingLine,
joinPath,
previewLineAtOffset,
previewOffsetForLine,
@@ -286,6 +287,36 @@ describe("markdown preview rendering", () => {
expect(slugify("Hello, World! v2")).toBe("hello-world-v2");
});
it("finds the source line of a heading anchor, as a link from another file opens there", () => {
const text = [
"---",
"title: x",
"---",
"# 成交对账",
"",
"```md",
"## 5.2 状态机",
"```",
"",
"## 5.2 状态机",
"",
"正文",
"",
"## 5.2 状态机",
"",
"### 4.1 Dubbo(`otcs-t0-server` client)",
].join("\n");
expect(headingLine(text, "成交对账")).toBe(3);
expect(headingLine(text, "52-状态机")).toBe(9);
expect(headingLine(text, "52-状态机-1")).toBe(13);
expect(headingLine(text, "user-content-52-状态机")).toBe(9);
expect(headingLine(text, "41-dubbootcs-t0-server-client")).toBe(15);
const link = resolveLink("/repo/a.md", "b.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA");
expect(link).toEqual({ kind: "file", path: "/repo/b.md", anchor: "52-状态机" });
expect(headingLine(text, "missing")).toBeNull();
expect(headingLine(text, "")).toBeNull();
});
it("resolves links against the file", () => {
const file = "/repo/docs/guide.md";
expect(resolveLink(file, "https://x.dev")).toEqual({ kind: "external", url: "https://x.dev" });
+29 -4
View File
@@ -69,6 +69,14 @@ export function slugify(text: string): string {
.replace(/\s/g, "-");
}
/** The id of the next heading titled `text`, counting repeats in `slugs` as GitHub does (`a`, `a-1`, `a-2`…). */
function headingId(slugs: Map<string, number>, text: string): string {
const base = slugify(text);
const n = slugs.get(base) ?? 0;
slugs.set(base, n + 1);
return n ? `${base}-${n}` : base;
}
const countLines = (s: string) => {
let n = 0;
for (let i = s.indexOf("\n"); i >= 0; i = s.indexOf("\n", i + 1)) n++;
@@ -161,10 +169,8 @@ function blocks(text: string): { line: number; html: string }[] {
const list = Object.assign([token], { links: tokens.links }) as TokensList;
let body = marked.parser(list);
if (token.type === "heading") {
const base = slugify((token as Token & { text: string }).text);
const n = slugs.get(base) ?? 0;
slugs.set(base, n + 1);
body = body.replace(/^<h(\d)>/, `<h$1 id="${ANCHOR_PREFIX}${n ? `${base}-${n}` : base}">`);
const id = headingId(slugs, (token as Token & { text: string }).text);
body = body.replace(/^<h(\d)>/, `<h$1 id="${ANCHOR_PREFIX}${id}">`);
}
group ??= { line: start, html: "" };
group.html += body;
@@ -193,6 +199,25 @@ const wrap = (line: number, html: string) => `<div data-line="${line}">${html}</
const sanitizeWhole = (all: readonly { line: number; html: string }[]) =>
purify().sanitize(all.map((b) => wrap(b.line, b.html)).join(""), SANITIZE);
/**
* 0-based source line of the heading the preview gives the anchor `anchor` (with or without
* {@link ANCHOR_PREFIX}), or null when no heading has it. Lets a link to another file open at
* that heading.
*/
export function headingLine(text: string, anchor: string): number | null {
const want = slugify(anchor.startsWith(ANCHOR_PREFIX) ? anchor.slice(ANCHOR_PREFIX.length) : anchor);
if (!want) return null;
const front = frontMatter(text);
const body = front ? text.split("\n").slice(front.lines).join("\n") : text;
const slugs = new Map<string, number>();
let line = front?.lines ?? 0;
for (const token of marked.lexer(body)) {
if (token.type === "heading" && headingId(slugs, (token as Token & { text: string }).text) === want) return line;
line += countLines(token.raw);
}
return null;
}
export function renderMarkdown(text: string): string {
return sanitizeWhole(blocks(text));
}