дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 21:12:34 +02:00
fix(markdown): keep large previews responsive when scrolling and switching tabs (#5249)
Fast scrolling could leave either pane of a Markdown split blank, and large previews were rebuilt on every tab switch. - The source draws newly visible lines before painting a large scroll jump; the preview follows wrapped lines and table rows, handles trackpad gestures from their first wheel event, and updates its position while the scrollbar thumb is dragged (the Git log's scrollbar, resized as content grows). - Recent Markdown tabs stay mounted while hidden (text editor wrappers can now opt into keepAlive); the hidden source view is detached as before and the preview is moved off screen on its own layer. - Edits reuse unchanged equation and Mermaid SVGs, including diagrams with math labels; changing a TeX macro refreshes the equations that use it. - Long embedded image payloads are folded in the source, and the Markdown parser skips the payload bytes of standalone images. On a 5.85 MB document in WebKit, first open went from 22.9 s to 3.25 s and returning to the tab from 14.4 s to 0.24 s. Co-authored-by: faysou <[email protected]>
Цей коміт міститься в:
1 джерело
13e27f0133
коміт
fc4e4fa39a
25 files changed
+1061
-187
No files matched your search
@@ -568,6 +568,80 @@ test("Markdown preview keeps following find and edits after scrolling the source
|
||||
await expect(preview.locator("strong [data-math-svg] > svg")).toHaveAttribute("aria-label", "v_0");
|
||||
});
|
||||
|
||||
test("drags the Markdown preview scrollbar through a document after it grows", async ({ workbench: page }) => {
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
await content.click();
|
||||
await page.keyboard.press("Meta+a");
|
||||
await page.keyboard.insertText("Short");
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
await expect(preview).toHaveText("Short");
|
||||
await content.press("Meta+a");
|
||||
await page.keyboard.insertText(Array.from({ length: 180 }, (_, i) => `Paragraph ${i}`).join("\n\n"));
|
||||
await expect(preview).toContainText("Paragraph 179");
|
||||
const thumb = preview.locator("..").locator(":scope > [aria-hidden=true] > div");
|
||||
await expect(thumb).toBeVisible();
|
||||
const thumbBox = (await thumb.boundingBox())!;
|
||||
const box = (await preview.boundingBox())!;
|
||||
const x = thumbBox.x + thumbBox.width / 2;
|
||||
await page.mouse.move(x, thumbBox.y + thumbBox.height / 2);
|
||||
await page.mouse.down();
|
||||
try {
|
||||
for (const end of [true, false, true]) {
|
||||
await page.mouse.move(x, box.y + (end ? box.height - 1 : 0), { steps: 3 });
|
||||
expect(await preview.evaluate((el) => Math.round(el.scrollTop))).toBe(
|
||||
end ? await preview.evaluate((el) => el.scrollHeight - el.clientHeight) : 0,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await page.mouse.up();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps diagrams and their math labels when editing or switching Markdown tabs", async ({ workbench: page }) => {
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
await content.click();
|
||||
await page.keyboard.press("Meta+a");
|
||||
const source = [
|
||||
"An equation $x^2$ and [a link](#title).",
|
||||
'```mermaid\nflowchart LR\n A["$$x^2$$"] --> B\n```',
|
||||
"Text to edit",
|
||||
].join("\n\n");
|
||||
await page.keyboard.insertText(source);
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
const diagram = preview.locator(".mermaid-output .pan-zoom-content > svg");
|
||||
await expect(diagram.locator("foreignObject math")).toHaveCount(1);
|
||||
const original = await diagram.elementHandle();
|
||||
const formula = preview.locator("[data-math-svg] > svg").first();
|
||||
const equation = await formula.elementHandle();
|
||||
await content.press("Control+End");
|
||||
await page.keyboard.insertText(" here");
|
||||
await expect(preview).toContainText("Text to edit here");
|
||||
expect(await diagram.evaluate((svg, old) => svg === old, original)).toBe(true);
|
||||
expect(await formula.evaluate((svg, old) => svg === old, equation)).toBe(true);
|
||||
|
||||
await content.press("Meta+a");
|
||||
await page.keyboard.insertText(source.replace("$$x^2$$", () => "$$z^3$$"));
|
||||
await expect(diagram.locator("foreignObject math mi")).toHaveText("z");
|
||||
const edited = await diagram.elementHandle();
|
||||
expect(await diagram.evaluate((svg, old) => svg === old, original)).toBe(false);
|
||||
expect(await formula.evaluate((svg, old) => svg === old, equation)).toBe(true);
|
||||
|
||||
const other = await openFromTree(page, "settings.gradle.kts");
|
||||
await expect(other.locator(".cm-content")).toBeVisible();
|
||||
await expect(preview).toHaveCount(0);
|
||||
expect(await edited!.evaluate((svg) => svg.isConnected)).toBe(true);
|
||||
const hiddenLink = page.locator('a[href="#title"]');
|
||||
await expect(hiddenLink).toBeHidden();
|
||||
await hiddenLink.evaluate((el) => el.focus());
|
||||
await expect(hiddenLink).not.toBeFocused();
|
||||
await page.getByRole("tab", { name: /README/ }).click();
|
||||
await expect(preview).toBeVisible();
|
||||
expect(await diagram.evaluate((svg, old) => svg === old, edited)).toBe(true);
|
||||
await expect(diagram.locator("foreignObject math")).toHaveCount(1);
|
||||
});
|
||||
|
||||
test("Markdown preview aligns Mermaid diagrams to their container align attribute", async ({ workbench: page }) => {
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
foldChipWidth,
|
||||
foldSelectionEffects,
|
||||
foldsFromRanges,
|
||||
markdownImageFolds,
|
||||
foldingExtension,
|
||||
foldToExpand,
|
||||
setBackendFolds,
|
||||
@@ -459,3 +460,24 @@ describe("foldChipWidth", () => {
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
it("folds long embedded image payloads without changing the Markdown source", () => {
|
||||
const data = "abcd".repeat(100);
|
||||
const url = "data:image/png;base64," + data;
|
||||
const first = ``;
|
||||
const second = `<img alt="b" src="${url}">`;
|
||||
const source = [first, second, "```md", first, "```", ""].join("\n");
|
||||
const state = EditorState.create({ doc: source, extensions: codeFolding() });
|
||||
const folded = state.update({ effects: markdownImageFolds(state) }).state;
|
||||
const ranges: number[][] = [];
|
||||
foldedRanges(folded).between(0, source.length, (from, to) => {
|
||||
ranges.push([from, to]);
|
||||
});
|
||||
const a = first.indexOf(data),
|
||||
b = first.length + 1 + second.indexOf(data);
|
||||
expect(ranges).toEqual([
|
||||
[a, a + data.length],
|
||||
[b, b + data.length],
|
||||
]);
|
||||
expect(folded.doc.toString()).toBe(source);
|
||||
});
|
||||
@@ -481,6 +481,28 @@ export function foldChipWidth(el: HTMLElement): number {
|
||||
return Math.round(chip.getBoundingClientRect().width);
|
||||
}
|
||||
|
||||
// Long image payloads would occupy thousands of soft-wrapped rows before the first editor measure.
|
||||
export function markdownImageFolds(state: EditorState) {
|
||||
const effects = [];
|
||||
const destination =
|
||||
/(?:\]\(\s*<?|<img\b[^>]*?\ssrc\s*=\s*["'])data:image\/[\w.+-]+;base64,([A-Za-z0-9+/]{256,}={0,2})(?=[>\s)"'])/gi;
|
||||
let offset = 0;
|
||||
let fence = "";
|
||||
for (const line of state.doc.iterLines()) {
|
||||
const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
|
||||
if (marker && !fence) fence = marker;
|
||||
else if (marker && marker.startsWith(fence) && !line.trim().slice(marker.length).trim()) fence = "";
|
||||
else if (!fence && line.length >= 256) {
|
||||
for (const match of line.matchAll(destination)) {
|
||||
const to = offset + match.index + match[0].length;
|
||||
effects.push(foldEffect.of({ from: to - match[1]!.length, to }));
|
||||
}
|
||||
}
|
||||
offset += line.length + 1;
|
||||
}
|
||||
return effects;
|
||||
}
|
||||
|
||||
export function foldingExtension(showOutline = true, visibility: FoldingOutlineVisibility = "hover"): Extension {
|
||||
return [
|
||||
// The chevron column sits right of contributed icon gutters (IDEA new UI).
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
} from "@/editor/api";
|
||||
import { showContextMenu } from "@/ui";
|
||||
import { baseExtensions, compartments, contributionExtensions } from "../cm/setup";
|
||||
import { markdownImageFolds } from "../cm/folding";
|
||||
import { gutterMenuItems, inGutterMenuArea } from "../gutterMenu";
|
||||
import { offerMakeWritable } from "../fileAttributes";
|
||||
import type { DocModel } from "./document";
|
||||
@@ -142,6 +143,10 @@ export class EditorSlot {
|
||||
}),
|
||||
],
|
||||
});
|
||||
if (model.ctx().language === "markdown") {
|
||||
const effects = markdownImageFolds(this.stored);
|
||||
if (effects.length) this.stored = this.stored.update({ effects }).state;
|
||||
}
|
||||
this.contributionsVersion = model.manager.contributionsVersion;
|
||||
if (source?.view) this.scroll = source.view.scrollSnapshot();
|
||||
else if (source) this.scroll = source.scroll;
|
||||
@@ -155,7 +160,7 @@ export class EditorSlot {
|
||||
}
|
||||
|
||||
/** The visible or kept view: the one holding the tab's state. */
|
||||
private get live(): EditorView | null {
|
||||
get live(): EditorView | null {
|
||||
return this.view ?? this.kept;
|
||||
}
|
||||
|
||||
|
||||
@@ -69,6 +69,28 @@
|
||||
content-visibility: visible;
|
||||
opacity: 0;
|
||||
}
|
||||
/* Keep the typeset page on its own layer. Hiding every glyph invalidates WebKit's text layout. */
|
||||
.keptText {
|
||||
will-change: transform;
|
||||
transform: translateZ(0);
|
||||
}
|
||||
.keptText.keptHidden {
|
||||
content-visibility: visible;
|
||||
transform: translate3d(-100vw, 0, 0);
|
||||
}
|
||||
.keptText.keptHidden
|
||||
:is(
|
||||
:any-link,
|
||||
:enabled,
|
||||
summary,
|
||||
iframe,
|
||||
audio[controls],
|
||||
video[controls],
|
||||
[tabindex]:not([tabindex="-1"]),
|
||||
[contenteditable]:not([contenteditable="false"])
|
||||
) {
|
||||
visibility: hidden;
|
||||
}
|
||||
.host {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
useTextEditorWrappers,
|
||||
type EditorInput,
|
||||
type EditorKindContribution,
|
||||
useEditorShown,
|
||||
type TextEditorWrapperContribution,
|
||||
} from "@/workbench/contributions";
|
||||
import { useDistractionFree } from "@/workbench/distractionFree";
|
||||
@@ -186,6 +187,7 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
const isActivePane = useTabs((s) => s.activePane === paneId);
|
||||
const multiPane = useTabs((s) => s.layout.kind === "split");
|
||||
const kinds = useContributions((s) => s.editorKinds);
|
||||
const wrappers = useTextEditorWrappers((s) => s.wrappers);
|
||||
const titleRevision = useEditorTabTitles((s) => s.revision);
|
||||
const tabs = useMemo(() => pane?.tabs ?? [], [pane]);
|
||||
const paths = tabs.map((t) => t.input.path ?? "");
|
||||
@@ -344,7 +346,7 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
|
||||
if (!pane) return null;
|
||||
const active = pane.tabs.find((t) => t.id === pane.active) ?? null;
|
||||
const kept = keptTabs(pane.tabs, pane.mru, kinds);
|
||||
const kept = keptTabs(pane.tabs, pane.mru, kinds, wrappers);
|
||||
|
||||
const onFocus = () => {
|
||||
setContext("editorFocus", true);
|
||||
@@ -431,7 +433,13 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
ref={contentRef}
|
||||
>
|
||||
{kept.map((tab) => (
|
||||
<KindEditor key={tab.id} tab={tab} shown={tab === active} kept />
|
||||
<EditorSurface key={tab.id} tab={tab} shown={tab === active} kept>
|
||||
{isTextInput(tab.input) ? (
|
||||
<PaneContent paneId={paneId} tab={tab} tabsVisible={!hidden} />
|
||||
) : (
|
||||
<KindEditor tab={tab} />
|
||||
)}
|
||||
</EditorSurface>
|
||||
))}
|
||||
{!active ? (
|
||||
<EmptyEditor />
|
||||
@@ -492,20 +500,22 @@ function PaneBreadcrumbs({
|
||||
}
|
||||
|
||||
function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; tabsVisible: boolean }) {
|
||||
const crumbs = !useDistractionFree((s) => s.active);
|
||||
const shown = useEditorShown();
|
||||
const crumbs = !useDistractionFree((s) => s.active) && shown;
|
||||
const wrappers = useTextEditorWrappers((s) => s.wrappers);
|
||||
if (isTextInput(tab.input)) {
|
||||
const virtual = tab.input.kind === "virtual" ? virtualData(tab.input) : undefined;
|
||||
const wrapper = tab.input.kind === "file" ? textEditorWrapperFor(wrappers, tab.input.path) : undefined;
|
||||
const host = <TextEditorHost key={tab.id} tabId={tab.id} />;
|
||||
const host = shown && <TextEditorHost key={tab.id} tabId={tab.id} />;
|
||||
return (
|
||||
<>
|
||||
{virtual ? (
|
||||
<VirtualBanner path={tab.input.path!} decompiled={virtual.decompiled} description={virtual.description} />
|
||||
) : (
|
||||
<EditorBanners path={tab.input.path} />
|
||||
)}
|
||||
<FindBar paneId={paneId} />
|
||||
{shown &&
|
||||
(virtual ? (
|
||||
<VirtualBanner path={tab.input.path!} decompiled={virtual.decompiled} description={virtual.description} />
|
||||
) : (
|
||||
<EditorBanners path={tab.input.path} />
|
||||
))}
|
||||
{shown && <FindBar paneId={paneId} />}
|
||||
{crumbs && (
|
||||
<PaneBreadcrumbs
|
||||
key={`top:${wrapper?.id}`}
|
||||
@@ -539,16 +549,32 @@ function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; t
|
||||
</>
|
||||
);
|
||||
}
|
||||
return <KindEditor key={tab.id} tab={tab} shown />;
|
||||
return (
|
||||
<EditorSurface key={tab.id} tab={tab} shown>
|
||||
<KindEditor tab={tab} />
|
||||
</EditorSurface>
|
||||
);
|
||||
}
|
||||
|
||||
/** Tabs of a pane kept mounted while hidden: the most recently used ones of `keepAlive` kinds. */
|
||||
const KEPT_TABS = 5;
|
||||
|
||||
function keptTabs(tabs: Tab[], mru: string[], kinds: Map<string, EditorKindContribution>): Tab[] {
|
||||
function keptTabs(
|
||||
tabs: Tab[],
|
||||
mru: string[],
|
||||
kinds: Map<string, EditorKindContribution>,
|
||||
wrappers: ReadonlyMap<string, TextEditorWrapperContribution>,
|
||||
): Tab[] {
|
||||
const recent = mru
|
||||
.map((id) => tabs.find((t) => t.id === id))
|
||||
.filter((t): t is Tab => !!t && !!kinds.get(t.input.kind)?.keepAlive)
|
||||
.filter(
|
||||
(t): t is Tab =>
|
||||
!!t &&
|
||||
(!!kinds.get(t.input.kind)?.keepAlive ||
|
||||
(t.input.kind === "file" &&
|
||||
t.input.path !== undefined &&
|
||||
!!textEditorWrapperFor(wrappers, t.input.path)?.keepAlive)),
|
||||
)
|
||||
.slice(0, KEPT_TABS);
|
||||
// In tab order, so switching tabs doesn't move their DOM (which would lose scroll offsets).
|
||||
return tabs.filter((t) => recent.includes(t));
|
||||
@@ -559,7 +585,17 @@ function keptTabs(tabs: Tab[], mru: string[], kinds: Map<string, EditorKindContr
|
||||
* keeps its layout (content-visibility), so showing it again needn't lay it out from scratch;
|
||||
* its content can't be focused or hit while skipped.
|
||||
*/
|
||||
function KindEditor({ tab, shown, kept = false }: { tab: Tab; shown: boolean; kept?: boolean }) {
|
||||
function EditorSurface({
|
||||
tab,
|
||||
shown,
|
||||
kept = false,
|
||||
children,
|
||||
}: {
|
||||
tab: Tab;
|
||||
shown: boolean;
|
||||
kept?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useSelectionVisibility(ref, kept);
|
||||
useLayoutEffect(() => {
|
||||
@@ -571,27 +607,34 @@ function KindEditor({ tab, shown, kept = false }: { tab: Tab; shown: boolean; ke
|
||||
sel.removeAllRanges();
|
||||
}
|
||||
}, [kept, shown]);
|
||||
const kinds = useContributions((s) => s.editorKinds);
|
||||
const kind = kinds.get(tab.input.kind);
|
||||
if (!kind) return <EmptyState icon="file" title={tx`No editor for “${tab.input.kind}”`} />;
|
||||
const Component = kind.component;
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={clsx(styles.kind, kept && styles.kept, !shown && styles.keptHidden)}
|
||||
data-editor-focus={shown ? "" : undefined}
|
||||
className={clsx(
|
||||
styles.kind,
|
||||
kept && styles.kept,
|
||||
kept && isTextInput(tab.input) && styles.keptText,
|
||||
!shown && styles.keptHidden,
|
||||
)}
|
||||
data-editor-focus={shown && !isTextInput(tab.input) ? "" : undefined}
|
||||
tabIndex={-1}
|
||||
aria-hidden={shown ? undefined : true}
|
||||
>
|
||||
<EditorTabIdProvider value={tab.id}>
|
||||
<EditorShownProvider value={shown}>
|
||||
<Component input={tab.input} />
|
||||
</EditorShownProvider>
|
||||
<EditorShownProvider value={shown}>{children}</EditorShownProvider>
|
||||
</EditorTabIdProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function KindEditor({ tab }: { tab: Tab }) {
|
||||
const kinds = useContributions((s) => s.editorKinds);
|
||||
const kind = kinds.get(tab.input.kind);
|
||||
if (!kind) return <EmptyState icon="file" title={tx`No editor for “${tab.input.kind}”`} />;
|
||||
const Component = kind.component;
|
||||
return <Component input={tab.input} />;
|
||||
}
|
||||
|
||||
/** Actions at the right end of the tab row (IDEA: split, tab actions ⋮). */
|
||||
function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) {
|
||||
const ctrl = editorController();
|
||||
|
||||
@@ -13,7 +13,7 @@ import { EditorAreaView } from "./EditorArea";
|
||||
|
||||
vi.mock("../controller", async (original) => ({
|
||||
...(await original<object>()),
|
||||
editorController: () => ({ publishContext: vi.fn(), tabMenu: () => [] }),
|
||||
editorController: () => ({ publishContext: vi.fn(), tabMenu: () => [], slotFor: () => null }),
|
||||
}));
|
||||
vi.mock("./TextEditorHost", () => ({ TextEditorHost: () => <input aria-label="Source" /> }));
|
||||
vi.mock("./FindBar", () => ({ FindBar: () => null }));
|
||||
@@ -45,6 +45,7 @@ beforeEach(() => {
|
||||
disposers = [
|
||||
registerTextEditorWrapper({
|
||||
id: "test.markdown",
|
||||
keepAlive: true,
|
||||
matches: (path) => path.endsWith(".md"),
|
||||
component: MarkdownEditor,
|
||||
tabActions: MarkdownLayoutActions,
|
||||
|
||||
@@ -21,6 +21,9 @@ interface MathToken extends Tokens.Generic {
|
||||
const escapeHtml = (s: string) =>
|
||||
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
export const declaresMathMacros = (source: string) =>
|
||||
/\\(?:(?:re)?new(?:command|environment)|def|let|DeclareMathOperator)\b/.test(source);
|
||||
|
||||
export function mathPlaceholder(tex: string, display: boolean, block = display): string {
|
||||
const tag = block ? "div" : "span";
|
||||
const mode = display ? "display" : "inline";
|
||||
@@ -129,26 +132,22 @@ function matchBlockMath(src: string): { raw: string; text: string } | null {
|
||||
|
||||
/** Masks math spans with `a`s (preserving newlines) so `*` and `_` inside math never trigger emphasis. */
|
||||
function maskInlineMath(src: string): string {
|
||||
const delimiters = /[$\\]/g;
|
||||
let out = "";
|
||||
let i = 0;
|
||||
while (i < src.length) {
|
||||
let start = 0;
|
||||
for (let at = delimiters.exec(src); at; at = delimiters.exec(src)) {
|
||||
const i = at.index;
|
||||
if (src[i] === "\\" && src[i + 1] !== "(" && src[i + 1] !== "[") {
|
||||
out += src.slice(i, i + 2);
|
||||
i += 2;
|
||||
delimiters.lastIndex++;
|
||||
continue;
|
||||
}
|
||||
if (src[i] === "$" || (src[i] === "\\" && (src[i + 1] === "(" || src[i + 1] === "["))) {
|
||||
const m = matchInlineMath(src.slice(i), MASKED_PROTECTED_INLINE_DOLLAR);
|
||||
if (m) {
|
||||
out += m.raw.replace(/[^\r\n]/g, "a");
|
||||
i += m.raw.length;
|
||||
continue;
|
||||
}
|
||||
const math = matchInlineMath(src.slice(i), MASKED_PROTECTED_INLINE_DOLLAR);
|
||||
if (math) {
|
||||
out += src.slice(start, i) + math.raw.replace(/[^\r\n]/g, "a");
|
||||
start = delimiters.lastIndex = i + math.raw.length;
|
||||
}
|
||||
out += src[i]!;
|
||||
i++;
|
||||
}
|
||||
return out;
|
||||
return start ? out + src.slice(start) : src;
|
||||
}
|
||||
|
||||
export function mathExtension(): MarkedExtension {
|
||||
|
||||
@@ -124,6 +124,7 @@ export function activate(): () => void {
|
||||
}),
|
||||
registerTextEditorWrapper({
|
||||
id: "viewers.markdown",
|
||||
keepAlive: true,
|
||||
matches: isMarkdownPath,
|
||||
component: lazyComponent(() => import("./markdown/MarkdownEditor").then((m) => m.MarkdownEditor), {
|
||||
prefetch: true,
|
||||
|
||||
@@ -42,7 +42,15 @@
|
||||
height: var(--h-floating-toolbar-button);
|
||||
}
|
||||
|
||||
.previewPane {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.preview {
|
||||
contain: strict;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
|
||||
@@ -20,13 +20,25 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import clsx from "clsx";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { editorController } from "@/editor/core/controller";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { editorPrefs, useEditorPrefs } from "@/platform/editorSettings";
|
||||
import { useMarkdownPreviewFontSize, useMarkdownPreviewLayout } from "@/platform/languageSettings";
|
||||
import { maybeEditorService, registerFontZoomSurface } from "@/workbench/contributions";
|
||||
import { maybeEditorService, registerFontZoomSurface, useEditorShown } from "@/workbench/contributions";
|
||||
import { editorsFor, setShownLine } from "@/editor/api";
|
||||
import { highlightInto } from "@/editor/lsp/markdown";
|
||||
import { FloatingToolbar, Spinner, SplitGroup, SplitHandle, SplitPanel, selectableText } from "@/ui";
|
||||
import {
|
||||
FloatingToolbar,
|
||||
Scrollbar,
|
||||
Spinner,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
hideNativeScrollbar,
|
||||
selectableText,
|
||||
} from "@/ui";
|
||||
import {
|
||||
FIND_CURRENT_HIGHLIGHT,
|
||||
FIND_HIGHLIGHT,
|
||||
@@ -40,10 +52,17 @@ import {
|
||||
selectionMatchesInNode,
|
||||
setPreviewHighlight,
|
||||
} from "./highlight";
|
||||
import { publishPreviewSelection, publishPreviewTop, stepMarkdownPreviewFontZoom, useLiveMarkdown } from "./live";
|
||||
import { followMarkdownSource } from "./splitScroll";
|
||||
import {
|
||||
installMarkdownSourceScroll,
|
||||
publishPreviewSelection,
|
||||
publishPreviewTop,
|
||||
stepMarkdownPreviewFontZoom,
|
||||
useLiveMarkdown,
|
||||
} from "./live";
|
||||
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
|
||||
import { hasMermaid, MERMAID_SELECTOR, renderMermaidIn } from "./mermaid";
|
||||
import { renderMath } from "@/editor/lsp/markdownMath";
|
||||
import { declaresMathMacros, renderMath } from "@/editor/lsp/markdownMath";
|
||||
import type { renderMathSvg } from "./mathSvg";
|
||||
import { modeOf, pinMarkdownMode, useMarkdownModes } from "./modes";
|
||||
import { MarkdownLayoutActions } from "./MarkdownLayoutActions";
|
||||
@@ -127,6 +146,10 @@ export function MarkdownEditor({
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const editorRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === "split" && editorRef.current) return installMarkdownSourceScroll(editorRef.current);
|
||||
}, [mode]);
|
||||
|
||||
// CodeMirror's internal ResizeObserver skips resizes within 75ms of a view update
|
||||
// and debounces by 50ms; re-measure immediately on drag and mode transitions.
|
||||
useEffect(() => {
|
||||
@@ -174,7 +197,7 @@ export function MarkdownEditor({
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<MarkdownPreview path={path} sync={mode === "split"} />
|
||||
<MarkdownPreview path={path} tabId={tabId} sync={mode === "split"} />
|
||||
</Suspense>
|
||||
</SplitPanel>
|
||||
)}
|
||||
@@ -188,13 +211,45 @@ export function MarkdownEditor({
|
||||
);
|
||||
}
|
||||
|
||||
const blocksOf = (root: HTMLElement) =>
|
||||
[...root.querySelectorAll<HTMLElement>(":scope > [data-preview-blocks] > [data-line]")].map((el) => ({
|
||||
line: Number(el.dataset.line),
|
||||
get top() {
|
||||
return el.offsetTop;
|
||||
},
|
||||
}));
|
||||
function blocksOf(root: HTMLElement) {
|
||||
const blocks = [];
|
||||
for (const el of root.querySelectorAll<HTMLElement>(":scope > [data-preview-blocks] > [data-line]")) {
|
||||
const line = Number(el.dataset.line);
|
||||
const endLine = Number(el.dataset.endLine);
|
||||
const table = el.firstElementChild;
|
||||
if (
|
||||
table instanceof HTMLTableElement &&
|
||||
table.hasAttribute("data-markdown-table") &&
|
||||
table.rows.length + 1 === endLine - line
|
||||
) {
|
||||
for (const [i, row] of Array.from(table.rows).entries()) {
|
||||
const start = i === 0 ? line : line + i + 1;
|
||||
blocks.push({
|
||||
line: start,
|
||||
endLine: i === 0 ? line + 2 : start + 1,
|
||||
get top() {
|
||||
return row.getBoundingClientRect().top - root.getBoundingClientRect().top + root.scrollTop;
|
||||
},
|
||||
get bottom() {
|
||||
return row.getBoundingClientRect().bottom - root.getBoundingClientRect().top + root.scrollTop;
|
||||
},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
blocks.push({
|
||||
line,
|
||||
endLine,
|
||||
get top() {
|
||||
return el.offsetTop;
|
||||
},
|
||||
get bottom() {
|
||||
return el.offsetTop + el.offsetHeight;
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
let svgRenderer: Promise<typeof renderMathSvg | null> | undefined;
|
||||
|
||||
@@ -205,21 +260,61 @@ function loadSvgRenderer() {
|
||||
));
|
||||
}
|
||||
|
||||
function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
let lastParse: { source: Text; html: string } | undefined;
|
||||
const parkedPreviews = new WeakMap<EditorView, { source: Text; root: HTMLElement; html: string }>();
|
||||
const previewGraphics = new WeakMap<HTMLElement, Map<string, HTMLElement[]>>();
|
||||
|
||||
function previewMarkup(source: Text, render: (text: string) => string, view: EditorView | null | undefined) {
|
||||
const parked = view && parkedPreviews.get(view);
|
||||
if (parked?.source === source) return parked.html;
|
||||
if (lastParse?.source !== source) lastParse = { source, html: render(source.toString()) };
|
||||
return lastParse.html;
|
||||
}
|
||||
|
||||
function typesetPreview(content: HTMLElement, previous: HTMLElement, svg: typeof renderMathSvg | null) {
|
||||
const inputs = [...content.querySelectorAll<HTMLElement>("[data-math], [data-mermaid]")];
|
||||
// A declaration can change the meaning of a later formula with identical source.
|
||||
const declaresMacros = inputs.some((el) => el.hasAttribute("data-math") && declaresMathMacros(el.textContent ?? ""));
|
||||
const available = previewGraphics.get(previous);
|
||||
const rendered = new Map<string, HTMLElement[]>();
|
||||
for (const input of inputs) {
|
||||
if (input.hasAttribute("data-math") && (declaresMacros || input.childElementCount)) continue;
|
||||
const key = input.outerHTML;
|
||||
const found = available?.get(key)?.pop();
|
||||
if (found) input.replaceWith(found);
|
||||
const copies = rendered.get(key);
|
||||
if (copies) copies.push(found ?? input);
|
||||
else rendered.set(key, [found ?? input]);
|
||||
}
|
||||
for (const copies of rendered.values()) copies.reverse();
|
||||
svg?.(content);
|
||||
renderMath(content);
|
||||
return rendered;
|
||||
}
|
||||
|
||||
function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; sync: boolean }) {
|
||||
const shown = useEditorShown();
|
||||
const text = useLiveMarkdown((s) => s[path]?.text);
|
||||
const fontZoom = useLiveMarkdown((s) => s[path]?.fontZoom ?? 0);
|
||||
const fontSize = useMarkdownPreviewFontSize();
|
||||
const zoomScale = Number((Math.max(4, fontSize + fontZoom) / fontSize).toFixed(4));
|
||||
const topLine = useLiveMarkdown((s) => s[path]?.topLine ?? 0);
|
||||
const scrollSeq = useLiveMarkdown((s) => s[path]?.scrollSeq ?? 0);
|
||||
const follower = useRef<ReturnType<typeof followMarkdownSource> | null>(null);
|
||||
const caretLine = useLiveMarkdown((s) => s[path]?.caretLine ?? 0);
|
||||
const caretSeq = useLiveMarkdown((s) => s[path]?.caretSeq ?? 0);
|
||||
const find = useLiveMarkdown((s) => s[path]?.find ?? null);
|
||||
const editorSelection = useLiveMarkdown((s) => s[path]?.editorSelection ?? "");
|
||||
const highlightSelection = useEditorPrefs().codeEditing.highlightSelection;
|
||||
const deferred = useDeferredValue(text ?? "");
|
||||
const deferred = useDeferredValue(text ?? Text.empty);
|
||||
const [render] = useState(createMarkdownRenderer);
|
||||
const html = useMemo(() => render(deferred), [render, deferred]);
|
||||
const slot = editorController().slotFor(tabId);
|
||||
const html = useMemo(() => previewMarkup(deferred, render, slot?.live), [render, deferred, slot]);
|
||||
const sourceOffsets = useMemo(() => {
|
||||
if (!sync) return undefined;
|
||||
const offsets = [0];
|
||||
for (let n = 2; n <= deferred.lines; n++) offsets.push(deferred.line(n).from);
|
||||
offsets.push(deferred.length);
|
||||
return offsets;
|
||||
}, [deferred, sync]);
|
||||
const renderSvg = html.includes(' data-math="') ? use(loadSvgRenderer()) : null;
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const linkRequest = useRef(0);
|
||||
@@ -227,6 +322,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const theme = useSyncExternalStore(subscribeTheme, themeKey, () => "");
|
||||
const diagrams = useRef<Node[]>([]);
|
||||
const [diagramsDrawn, setDiagramsDrawn] = useState(0);
|
||||
const [contentHeight, setContentHeight] = useState(0);
|
||||
const seenCaret = useRef(caretSeq);
|
||||
const seenFindMatch = useRef<number | null>(null);
|
||||
/** scrollTop set by navigation, whose scroll event isn't the user's. */
|
||||
@@ -239,25 +335,43 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
|
||||
useLayoutEffect(() => {
|
||||
toggled.current.clear();
|
||||
return () => {
|
||||
linkRequest.current++;
|
||||
};
|
||||
}, [path]);
|
||||
useLayoutEffect(
|
||||
() => () => {
|
||||
linkRequest.current++;
|
||||
},
|
||||
[path, shown],
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
ref.current?.querySelectorAll("details").forEach((d, i) => {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
const view = slot?.live;
|
||||
const parked = view && parkedPreviews.get(view);
|
||||
if (view) parkedPreviews.delete(view);
|
||||
const cached = parked?.html === html ? parked.root : null;
|
||||
if (cached !== root) {
|
||||
if (cached) {
|
||||
root.replaceChildren(...cached.children);
|
||||
const graphics = previewGraphics.get(cached);
|
||||
if (graphics) previewGraphics.set(root, graphics);
|
||||
} else {
|
||||
const content = document.createElement("div");
|
||||
content.dataset.previewBlocks = "";
|
||||
content.innerHTML = html;
|
||||
previewGraphics.set(root, typesetPreview(content, parked?.root ?? root, renderSvg));
|
||||
root.replaceChildren(content);
|
||||
}
|
||||
}
|
||||
root.querySelectorAll("details").forEach((d, i) => {
|
||||
const open = toggled.current.get(i);
|
||||
if (open !== undefined) d.open = open;
|
||||
});
|
||||
}, [html]);
|
||||
|
||||
// Math before the preview index: typesetting changes the blocks' heights.
|
||||
useLayoutEffect(() => {
|
||||
if (!ref.current) return;
|
||||
renderSvg?.(ref.current);
|
||||
renderMath(ref.current);
|
||||
blocks.current = blocksOf(ref.current);
|
||||
invalidatePreviewIndex(ref.current);
|
||||
}, [html, renderSvg]);
|
||||
blocks.current = blocksOf(root);
|
||||
invalidatePreviewIndex(root);
|
||||
return () => {
|
||||
if (view) parkedPreviews.set(view, { source: deferred, html, root });
|
||||
};
|
||||
}, [html, deferred, slot, renderSvg]);
|
||||
|
||||
// Mermaid diagrams: before paint, so cached ones don't flash their source.
|
||||
useLayoutEffect(() => {
|
||||
@@ -294,7 +408,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
}
|
||||
};
|
||||
img.src = url;
|
||||
if (img.getAttribute("src") !== url) img.src = url;
|
||||
if (!img.hasAttribute("data-natural-width") && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||
size(img, { w: img.naturalWidth, h: img.naturalHeight });
|
||||
}
|
||||
@@ -332,27 +446,22 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
};
|
||||
}, [html, path]);
|
||||
|
||||
// Scroll sync: editor → preview.
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root || !sync) return;
|
||||
root.scrollTop = topLine <= 0 ? 0 : previewOffsetForLine(blocks.current, topLine, root.scrollHeight);
|
||||
}, [html, topLine, scrollSeq, sync, diagramsDrawn, fontZoom, fontSize]);
|
||||
if (!root || !sync || !shown) return;
|
||||
const follow = followMarkdownSource(path, root, (line) =>
|
||||
line <= 0 ? 0 : previewOffsetForLine(blocks.current, line, root.scrollHeight, sourceOffsets),
|
||||
);
|
||||
follower.current = follow;
|
||||
return () => {
|
||||
follow.dispose();
|
||||
follower.current = null;
|
||||
};
|
||||
}, [path, shown, sync, sourceOffsets]);
|
||||
|
||||
// Keep the split preview anchored to `topLine` as dragging the divider or resizing the window reflows text.
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root || !sync || typeof ResizeObserver === "undefined") return;
|
||||
let width = root.clientWidth;
|
||||
const ro = new ResizeObserver(() => {
|
||||
if (root.clientWidth === width) return;
|
||||
width = root.clientWidth;
|
||||
const top = useLiveMarkdown.getState()[path]?.topLine ?? 0;
|
||||
root.scrollTop = top <= 0 ? 0 : previewOffsetForLine(blocks.current, top, root.scrollHeight);
|
||||
});
|
||||
ro.observe(root);
|
||||
return () => ro.disconnect();
|
||||
}, [path, sync]);
|
||||
useLayoutEffect(() => {
|
||||
follower.current?.align();
|
||||
}, [path, sync, html, sourceOffsets, diagramsDrawn, fontZoom, fontSize]);
|
||||
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
@@ -371,15 +480,17 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
let timer: number | undefined;
|
||||
const apply = () => {
|
||||
if (!width || width === settled) return;
|
||||
const follow = follower.current;
|
||||
const top = root.scrollTop;
|
||||
const atBottom = top > 0 && top + root.clientHeight >= root.scrollHeight - 1;
|
||||
const line = top > 0 ? previewLineAtOffset(blocks.current, top) : -1;
|
||||
const line = !follow && top > 0 ? previewLineAtOffset(blocks.current, top) : -1;
|
||||
const block = line >= 0 ? blocks.current.find((b) => b.line === line) : undefined;
|
||||
const within = block ? top - block.top : 0;
|
||||
settled = width;
|
||||
root.removeAttribute("data-constrain-blocks");
|
||||
root.style.setProperty("--markdown-block-width", `${width}px`);
|
||||
if (atBottom) root.scrollTop = root.scrollHeight;
|
||||
if (follow) follow.align();
|
||||
else if (atBottom) root.scrollTop = root.scrollHeight;
|
||||
else if (block) root.scrollTop = block.top + within;
|
||||
};
|
||||
const schedule = () => {
|
||||
@@ -412,9 +523,16 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
};
|
||||
}, [html]);
|
||||
|
||||
// The preview's own scroll offset: tab switches and mode toggles unmount the
|
||||
// preview, so Preview Only would otherwise start over at the top. Writes made
|
||||
// by the split sync above are captured too — the last visible position wins.
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
const measure = () => setContentHeight(root.scrollHeight);
|
||||
measure();
|
||||
root.addEventListener("toggle", measure, true);
|
||||
return () => root.removeEventListener("toggle", measure, true);
|
||||
}, [html, diagramsDrawn, fontZoom, fontSize]);
|
||||
|
||||
// Restore Preview Only after a mode change or eviction from the kept tabs.
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
@@ -458,7 +576,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
// Preview only: go where the hidden editor's caret was sent (Structure, Go to Symbol…).
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root || caretSeq === seenCaret.current) return;
|
||||
if (!root || !shown || 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;
|
||||
@@ -482,12 +600,12 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
restoreRetry.current = null;
|
||||
}
|
||||
setShownLine(path, caretLine);
|
||||
}, [caretSeq, caretLine, sync, path, find, deferred, text]);
|
||||
}, [caretSeq, caretLine, shown, sync, path, find, deferred, text]);
|
||||
|
||||
// Search (⌘F) and selection occurrence highlights in the preview.
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
if (!root || !shown) return;
|
||||
const applyFind = () => {
|
||||
if (!find) {
|
||||
seenFindMatch.current = null;
|
||||
@@ -552,7 +670,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
document.removeEventListener("selectionchange", applySelection);
|
||||
root.removeEventListener("toggle", applyAll, true);
|
||||
};
|
||||
}, [html, path, sync, find, editorSelection, highlightSelection]);
|
||||
}, [html, path, shown, sync, find, editorSelection, highlightSelection]);
|
||||
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
@@ -578,10 +696,40 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
e.stopPropagation();
|
||||
if (zoom) stepMarkdownPreviewFontZoom(path, root, zoom);
|
||||
};
|
||||
const onPreviewWheel = (e: WheelEvent) => {
|
||||
if (
|
||||
e.defaultPrevented ||
|
||||
!e.cancelable ||
|
||||
e.ctrlKey ||
|
||||
e.metaKey ||
|
||||
e.altKey ||
|
||||
e.shiftKey ||
|
||||
e.deltaMode !== WheelEvent.DOM_DELTA_PIXEL ||
|
||||
!e.deltaY ||
|
||||
Math.abs(e.deltaY) < Math.abs(e.deltaX)
|
||||
)
|
||||
return;
|
||||
const max = root.scrollHeight - root.clientHeight;
|
||||
if (max <= root.clientHeight || (e.deltaY > 0 ? root.scrollTop >= max : root.scrollTop <= 0)) return;
|
||||
for (let el = e.target instanceof Element ? e.target : null; el && el !== root; el = el.parentElement) {
|
||||
if (el.scrollHeight <= el.clientHeight && (!e.deltaX || el.scrollWidth <= el.clientWidth)) continue;
|
||||
const style = getComputedStyle(el);
|
||||
if (
|
||||
(el.scrollHeight > el.clientHeight && /^(auto|scroll)$/.test(style.overflowY)) ||
|
||||
(e.deltaX && el.scrollWidth > el.clientWidth && /^(auto|scroll)$/.test(style.overflowX))
|
||||
)
|
||||
return;
|
||||
}
|
||||
// WebKit decides on the first wheel event whether it can scroll ahead of paint for the entire gesture.
|
||||
e.preventDefault();
|
||||
root.scrollBy(e.deltaX, e.deltaY);
|
||||
};
|
||||
root.addEventListener("wheel", onPreviewWheel, { passive: false });
|
||||
root.addEventListener("wheel", onWheel, { capture: true, passive: false });
|
||||
const release = registerFontZoomSurface(root, (delta) => stepMarkdownPreviewFontZoom(path, root, delta));
|
||||
return () => {
|
||||
root.removeEventListener("wheel", onWheel, { capture: true });
|
||||
root.removeEventListener("wheel", onPreviewWheel);
|
||||
release();
|
||||
};
|
||||
}, [path]);
|
||||
@@ -590,10 +738,10 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
// cleared when the editor is back or the preview goes away.
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root || sync) return;
|
||||
if (!root || sync || !shown) return;
|
||||
setShownLine(path, previewLineAtOffset(blocks.current, root.scrollTop));
|
||||
return () => setShownLine(path, null);
|
||||
}, [sync, path]);
|
||||
}, [sync, path, shown]);
|
||||
useEffect(() => () => cancelAnimationFrame(scrollFrame.current), []);
|
||||
|
||||
const onScroll = () => {
|
||||
@@ -646,23 +794,24 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={clsx(styles.preview, selectableText)}
|
||||
style={
|
||||
{
|
||||
"--markdown-preview-font-size": `${fontSize}px`,
|
||||
"--markdown-font-zoom": `${fontZoom}px`,
|
||||
"--markdown-zoom-scale": String(zoomScale),
|
||||
} as CSSProperties
|
||||
}
|
||||
tabIndex={-1}
|
||||
role="document"
|
||||
aria-label={tx("Markdown preview")}
|
||||
onClick={onClick}
|
||||
onScroll={onScroll}
|
||||
>
|
||||
<div data-preview-blocks="" dangerouslySetInnerHTML={{ __html: html }} />
|
||||
<div className={styles.previewPane}>
|
||||
<div
|
||||
ref={ref}
|
||||
className={clsx(styles.preview, hideNativeScrollbar, selectableText)}
|
||||
style={
|
||||
{
|
||||
"--markdown-preview-font-size": `${fontSize}px`,
|
||||
"--markdown-font-zoom": `${fontZoom}px`,
|
||||
"--markdown-zoom-scale": String(zoomScale),
|
||||
} as CSSProperties
|
||||
}
|
||||
tabIndex={-1}
|
||||
role="document"
|
||||
aria-label={tx("Markdown preview")}
|
||||
onClick={onClick}
|
||||
onScroll={onScroll}
|
||||
/>
|
||||
<Scrollbar target={ref} contentHeight={contentHeight} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { BlockType, EditorView, type BlockInfo } from "@codemirror/view";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { editorContributions, type EditorDocContext } from "@/editor/api";
|
||||
import { installMarkdownSourceScroll, registerMarkdownLiveSource, useLiveMarkdown } from "./live";
|
||||
|
||||
const ctx: EditorDocContext = { doc: 1, path: "/p/README.md", language: "markdown", uiMode: null, readOnly: false };
|
||||
|
||||
describe("Markdown source scroll", () => {
|
||||
let view: EditorView;
|
||||
let unregister: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
unregister = registerMarkdownLiveSource();
|
||||
const contribution = editorContributions().find((item) => item.id === "viewers.markdownLive")!;
|
||||
view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "# Title\nA wrapped line\nMore text",
|
||||
extensions: contribution.extensions(ctx),
|
||||
}),
|
||||
});
|
||||
Object.defineProperties(view.scrollDOM, {
|
||||
clientHeight: { value: 100 },
|
||||
scrollHeight: { value: 500 },
|
||||
});
|
||||
vi.spyOn(view.scrollDOM, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 100, 400, 100));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
view.destroy();
|
||||
unregister();
|
||||
useLiveMarkdown.setState({}, true);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function sourceBlock(lineNumber: number, top: number, height: number): BlockInfo {
|
||||
const { from, to, length } = view.state.doc.line(lineNumber);
|
||||
return {
|
||||
from,
|
||||
to,
|
||||
length,
|
||||
top,
|
||||
height,
|
||||
bottom: top + height,
|
||||
type: BlockType.Text,
|
||||
widget: null,
|
||||
widgetLineBreaks: 0,
|
||||
};
|
||||
}
|
||||
|
||||
it("publishes progress within the visible line and tracks the source bottom", () => {
|
||||
vi.spyOn(view, "requestMeasure").mockImplementation((request) => {
|
||||
if (request) request.write?.(request.read(view), view);
|
||||
});
|
||||
vi.spyOn(view, "documentTop", "get").mockReturnValue(30);
|
||||
vi.spyOn(view, "lineBlockAtHeight").mockReturnValue(sourceBlock(2, 50, 40));
|
||||
const scroller = view.scrollDOM;
|
||||
const position = () => useLiveMarkdown.getState()[ctx.path];
|
||||
|
||||
scroller.scrollTop = 75;
|
||||
scroller.dispatchEvent(new Event("scroll"));
|
||||
expect(view.lineBlockAtHeight).toHaveBeenCalledWith(70);
|
||||
expect(position()).toMatchObject({ topLine: 1.5, sourceAtEnd: false, scrollSeq: 1 });
|
||||
|
||||
scroller.scrollTop = 399.5;
|
||||
scroller.dispatchEvent(new Event("scroll"));
|
||||
expect(position()).toMatchObject({ topLine: 1.5, sourceAtEnd: true, scrollSeq: 2 });
|
||||
|
||||
scroller.scrollTop = 75;
|
||||
scroller.dispatchEvent(new Event("scroll"));
|
||||
expect(position()).toMatchObject({ topLine: 1.5, sourceAtEnd: false, scrollSeq: 3 });
|
||||
});
|
||||
|
||||
it("weights the top visual row by the source characters in that wrap", () => {
|
||||
vi.spyOn(view, "requestMeasure").mockImplementation((request) => {
|
||||
if (request) request.write?.(request.read(view), view);
|
||||
});
|
||||
vi.spyOn(view, "inView", "get").mockReturnValue(true);
|
||||
vi.spyOn(view, "documentTop", "get").mockReturnValue(35);
|
||||
vi.spyOn(view, "lineWrapping", "get").mockReturnValue(true);
|
||||
vi.spyOn(view, "defaultLineHeight", "get").mockReturnValue(10);
|
||||
vi.spyOn(view, "lineBlockAtHeight").mockReturnValue(sourceBlock(2, 50, 30));
|
||||
const line = view.state.doc.line(2);
|
||||
vi.spyOn(view, "posAtCoords")
|
||||
.mockReturnValueOnce(line.from + 7)
|
||||
.mockReturnValueOnce(line.from + 9);
|
||||
view.scrollDOM.dispatchEvent(new Event("scroll"));
|
||||
expect(useLiveMarkdown.getState()[ctx.path]?.topLine).toBeCloseTo(1 + 8 / (line.length + 1));
|
||||
});
|
||||
|
||||
it("measures a wheel jump that would expose an unrendered part of the source", () => {
|
||||
const block = sourceBlock(1, 0, 140);
|
||||
vi.spyOn(view, "documentTop", "get").mockReturnValue(100);
|
||||
vi.spyOn(view, "viewport", "get").mockReturnValue({ from: block.from, to: block.to });
|
||||
vi.spyOn(view, "viewportLineBlocks", "get").mockReturnValue([block]);
|
||||
const measure = vi.spyOn(view, "requestMeasure").mockImplementation(() => {});
|
||||
const lineAtHeight = vi.spyOn(view, "lineBlockAtHeight").mockReturnValue(block);
|
||||
const scrollBy = vi.fn();
|
||||
Object.defineProperty(view.scrollDOM, "scrollBy", { value: scrollBy });
|
||||
const dispose = installMarkdownSourceScroll(view.dom);
|
||||
const wheel = (init: WheelEventInit) =>
|
||||
view.contentDOM.dispatchEvent(new WheelEvent("wheel", { bubbles: true, cancelable: true, ...init }));
|
||||
|
||||
try {
|
||||
expect(wheel({ deltaY: 10 })).toBe(true);
|
||||
expect(wheel({ deltaY: 100, ctrlKey: true })).toBe(true);
|
||||
expect(wheel({ deltaX: 100, deltaY: 10 })).toBe(true);
|
||||
expect(wheel({ deltaX: 3, deltaY: 100 })).toBe(false);
|
||||
expect(scrollBy).toHaveBeenCalledExactlyOnceWith(3, 100);
|
||||
expect(measure).toHaveBeenCalledTimes(1);
|
||||
expect(lineAtHeight).toHaveBeenCalledExactlyOnceWith(100);
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,10 @@
|
||||
/**
|
||||
* Live Markdown source for the preview: an editor contribution on Markdown
|
||||
* files publishes the document text (debounced while typing), the first
|
||||
* visible line of the editor (for scroll sync) and caret moves (so a Preview
|
||||
* only preview follows navigation in its hidden editor), per path.
|
||||
* files publishes the text, scroll position, and caret moves per path.
|
||||
* Preview Only follows navigation in the hidden editor.
|
||||
*/
|
||||
import { StateEffect, type EditorState } from "@codemirror/state";
|
||||
import { Decoration, ViewPlugin, type DecorationSet, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { StateEffect, Text, type EditorState } from "@codemirror/state";
|
||||
import { Decoration, Direction, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import { SearchCursor, getSearchQuery } from "@codemirror/search";
|
||||
import { create } from "zustand";
|
||||
import { registerEditorContribution, useEditorRegistry } from "@/editor/api";
|
||||
@@ -26,9 +25,11 @@ export interface LiveMarkdownFind {
|
||||
}
|
||||
|
||||
export interface LiveMarkdown {
|
||||
text: string;
|
||||
/** 0-based first visible source line of the editor that scrolled last. */
|
||||
text: Text;
|
||||
/** 0-based source line at the top of the editor, including progress through the line. */
|
||||
topLine: number;
|
||||
/** Whether the scrolling editor has reached its bottom. */
|
||||
sourceAtEnd: boolean;
|
||||
/** Bumped when the editor scrolls, so equal lines still resync. */
|
||||
scrollSeq: number;
|
||||
/** The editor's font zoom in px; the preview scales its text by the same amount. */
|
||||
@@ -56,8 +57,9 @@ const previewSelectionMark = Decoration.mark({ class: "cm-selectionMatch" });
|
||||
function publish(path: string, patch: Partial<LiveMarkdown>) {
|
||||
useLiveMarkdown.setState((s) => {
|
||||
const prev = s[path] ?? {
|
||||
text: "",
|
||||
text: Text.empty,
|
||||
topLine: 0,
|
||||
sourceAtEnd: false,
|
||||
scrollSeq: 0,
|
||||
fontZoom: 0,
|
||||
caretLine: 0,
|
||||
@@ -152,9 +154,93 @@ function previewSelectionDecorations(view: EditorView, query: string): Decoratio
|
||||
return Decoration.set(ranges);
|
||||
}
|
||||
|
||||
function topLineOf(view: EditorView): number {
|
||||
const block = view.lineBlockAtHeight(view.scrollDOM.scrollTop);
|
||||
return view.state.doc.lineAt(block.from).number - 1;
|
||||
function sourcePositionOf(view: EditorView) {
|
||||
const scroller = view.scrollDOM;
|
||||
if (!view.inView || !scroller.clientHeight) return null;
|
||||
const y = Math.max(0, sourceViewportTop(view));
|
||||
const block = view.lineBlockAtHeight(y);
|
||||
const line = view.state.doc.lineAt(block.from);
|
||||
let fraction = block.height > 0 ? Math.max(0, Math.min(1, (y - block.top) / block.height)) : 0;
|
||||
const rowHeight = view.defaultLineHeight;
|
||||
if (
|
||||
view.lineWrapping &&
|
||||
rowHeight > 0 &&
|
||||
block.height > rowHeight * 1.5 &&
|
||||
block.from === line.from &&
|
||||
block.to === line.to
|
||||
) {
|
||||
// Interpolate between the source offsets of the visible wrapped row and the following row.
|
||||
const row = Math.floor((y - block.top) / rowHeight);
|
||||
const rowTop = block.top + row * rowHeight;
|
||||
const rect = view.contentDOM.getBoundingClientRect();
|
||||
const x = view.textDirectionAt(line.from) === Direction.LTR ? rect.left + 1 : rect.right - 1;
|
||||
const middle = view.documentTop + rowTop + rowHeight / 2;
|
||||
const start = view.posAtCoords({ x, y: middle });
|
||||
const next =
|
||||
rowTop + rowHeight >= block.bottom - 0.5 ? line.to + 1 : view.posAtCoords({ x, y: middle + rowHeight });
|
||||
if (start !== null && next !== null && start >= line.from && next >= start && next <= line.to + 1) {
|
||||
const withinRow = Math.max(0, Math.min(1, (y - rowTop) / rowHeight));
|
||||
const span = line.length + Number(line.number < view.state.doc.lines);
|
||||
if (span) fraction = Math.min(1, (start - line.from + withinRow * (next - start)) / span);
|
||||
}
|
||||
}
|
||||
const topLine = line.number - 1 + fraction;
|
||||
const sourceAtEnd = scroller.scrollTop > 0 && scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop <= 1;
|
||||
return { topLine, sourceAtEnd };
|
||||
}
|
||||
|
||||
/** Redraws the split source before paint when a wheel jump passes its rendered lines. */
|
||||
export function installMarkdownSourceScroll(root: HTMLElement): () => void {
|
||||
const onWheel = (event: WheelEvent) => {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
!event.cancelable ||
|
||||
event.ctrlKey ||
|
||||
event.metaKey ||
|
||||
event.shiftKey ||
|
||||
event.altKey ||
|
||||
event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL ||
|
||||
!event.deltaY ||
|
||||
Math.abs(event.deltaX) > Math.abs(event.deltaY) ||
|
||||
!(event.target instanceof Element)
|
||||
)
|
||||
return;
|
||||
|
||||
const scroller = event.target.closest<HTMLElement>(".cm-scroller");
|
||||
const view = scroller && EditorView.findFromDOM(scroller);
|
||||
if (!scroller || !view) return;
|
||||
|
||||
const current = scroller.scrollTop;
|
||||
const height = scroller.clientHeight;
|
||||
const max = scroller.scrollHeight - height;
|
||||
const target = Math.min(max, Math.max(0, current + event.deltaY));
|
||||
if (max <= 0 || target === current) return;
|
||||
|
||||
const scale = view.scaleY;
|
||||
const nextTop = sourceViewportTop(view) + (target - current) * scale;
|
||||
const blocks = view.viewportLineBlocks;
|
||||
const first = blocks[0];
|
||||
const last = blocks.at(-1);
|
||||
if (!first || !last) return;
|
||||
if (
|
||||
(view.viewport.from === 0 || nextTop >= first.top) &&
|
||||
(view.viewport.to === view.state.doc.length || nextTop + height * scale <= last.bottom)
|
||||
)
|
||||
return;
|
||||
|
||||
// A native jump can expose a virtual gap before CodeMirror redraws. Move and measure together.
|
||||
event.preventDefault();
|
||||
scroller.scrollBy(event.deltaX, target - current);
|
||||
view.requestMeasure();
|
||||
view.lineBlockAtHeight(nextTop);
|
||||
};
|
||||
root.addEventListener("wheel", onWheel, { passive: false });
|
||||
return () => root.removeEventListener("wheel", onWheel);
|
||||
}
|
||||
|
||||
function sourceViewportTop(view: EditorView): number {
|
||||
const scroller = view.scrollDOM;
|
||||
return scroller.getBoundingClientRect().top + scroller.clientTop * view.scaleY - view.documentTop;
|
||||
}
|
||||
|
||||
function livePlugin(path: string) {
|
||||
@@ -162,16 +248,25 @@ function livePlugin(path: string) {
|
||||
class {
|
||||
decorations: DecorationSet = Decoration.none;
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
private frame = 0;
|
||||
private scrolled = false;
|
||||
private destroyed = false;
|
||||
private previewSel = "";
|
||||
private unsubscribe: () => void;
|
||||
private readonly measureSource = {
|
||||
read: sourcePositionOf,
|
||||
write: (position: ReturnType<typeof sourcePositionOf>) => {
|
||||
const scrolled = this.scrolled;
|
||||
this.scrolled = false;
|
||||
if (this.destroyed || !position) return;
|
||||
const prev = useLiveMarkdown.getState()[path];
|
||||
if (scrolled || position.topLine !== prev?.topLine || position.sourceAtEnd !== prev?.sourceAtEnd) {
|
||||
publish(path, { ...position, scrollSeq: (prev?.scrollSeq ?? 0) + Number(scrolled) });
|
||||
}
|
||||
},
|
||||
};
|
||||
private readonly onScroll = () => {
|
||||
if (this.frame) return;
|
||||
this.frame = requestAnimationFrame(() => {
|
||||
this.frame = 0;
|
||||
const seq = (useLiveMarkdown.getState()[path]?.scrollSeq ?? 0) + 1;
|
||||
publish(path, { topLine: topLineOf(this.view), scrollSeq: seq });
|
||||
});
|
||||
this.scrolled = true;
|
||||
this.view.requestMeasure(this.measureSource);
|
||||
};
|
||||
|
||||
constructor(private view: EditorView) {
|
||||
@@ -179,7 +274,7 @@ function livePlugin(path: string) {
|
||||
this.previewSel = current?.previewSelection ?? "";
|
||||
this.decorations = previewSelectionDecorations(view, this.previewSel);
|
||||
publish(path, {
|
||||
text: view.state.doc.toString(),
|
||||
text: view.state.doc,
|
||||
fontZoom: view.state.field(fontZoom, false) ?? 0,
|
||||
find: findStateOf(view.state),
|
||||
editorSelection: editorSelectionOf(view.state),
|
||||
@@ -235,30 +330,22 @@ function livePlugin(path: string) {
|
||||
this.decorations = previewSelectionDecorations(u.view, this.previewSel);
|
||||
}
|
||||
|
||||
if (u.geometryChanged) u.view.requestMeasure(this.measureSource);
|
||||
if (!u.docChanged) {
|
||||
if (u.geometryChanged && u.view.scrollDOM.scrollTop > 0) {
|
||||
u.view.requestMeasure({
|
||||
key: this,
|
||||
read: topLineOf,
|
||||
write: (topLine) => {
|
||||
if (topLine !== useLiveMarkdown.getState()[path]?.topLine) publish(path, { topLine });
|
||||
},
|
||||
});
|
||||
}
|
||||
if (u.selectionSet) this.publishCaret();
|
||||
return;
|
||||
}
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => publish(path, { text: this.view.state.doc.toString() }), TEXT_DELAY);
|
||||
this.timer = setTimeout(() => publish(path, { text: this.view.state.doc }), TEXT_DELAY);
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
clearTimeout(this.timer);
|
||||
cancelAnimationFrame(this.frame);
|
||||
this.unsubscribe();
|
||||
this.view.scrollDOM.removeEventListener("scroll", this.onScroll);
|
||||
// Flush the latest edit for a preview that outlives this view.
|
||||
publish(path, { text: this.view.state.doc.toString() });
|
||||
publish(path, { text: this.view.state.doc });
|
||||
}
|
||||
},
|
||||
{ decorations: (v) => v.decorations },
|
||||
|
||||
@@ -14,12 +14,9 @@ it("renders inline and display equations as independent SVGs with accessible Mat
|
||||
expect(display).toHaveLength(1);
|
||||
expect(root.querySelector("strong > [data-math-svg] > svg")?.getAttribute("aria-label")).toBe("v_0");
|
||||
expect(root.querySelectorAll("mjx-assistive-mml math")).toHaveLength(3);
|
||||
expect(
|
||||
[...root.querySelectorAll("svg use")].every((use) => {
|
||||
const href = use.getAttribute("xlink:href");
|
||||
return href?.startsWith("#") && use.closest("svg")?.querySelector(`[id="${href.slice(1)}"]`);
|
||||
}),
|
||||
).toBe(true);
|
||||
expect([...inline, ...display].every((svg) => svg.querySelector("path[d]"))).toBe(true);
|
||||
expect(inline[0]!.innerHTML).toBe(inline[1]!.innerHTML);
|
||||
expect(inline[0]!.firstChild).not.toBe(inline[1]!.firstChild);
|
||||
});
|
||||
|
||||
it("leaves unsupported formulas for KaTeX without enabling TeX links", () => {
|
||||
|
||||
@@ -11,6 +11,8 @@ import { mathjax } from "@mathjax/src/js/mathjax.js";
|
||||
import { SVG } from "@mathjax/src/js/output/svg.js";
|
||||
import { SafeHandler } from "@mathjax/src/js/ui/safe/SafeHandler.js";
|
||||
|
||||
import { declaresMathMacros } from "@/editor/lsp/markdownMath";
|
||||
|
||||
function createSvgRenderer() {
|
||||
const handler = RegisterHTMLHandler(browserAdaptor());
|
||||
SafeHandler<HTMLElement, Text, Document>(handler);
|
||||
@@ -23,7 +25,7 @@ function createSvgRenderer() {
|
||||
});
|
||||
const math = mathjax.document("", {
|
||||
InputJax: tex,
|
||||
OutputJax: new SVG({ fontData: MathJaxTexFont, fontCache: "local" }),
|
||||
OutputJax: new SVG({ fontData: MathJaxTexFont, fontCache: "none" }),
|
||||
safeOptions: { allow: { URLs: "none", classes: "none", cssIDs: "none", styles: "none" } },
|
||||
});
|
||||
return (source: string, display: boolean) => {
|
||||
@@ -35,11 +37,21 @@ function createSvgRenderer() {
|
||||
let convert: ReturnType<typeof createSvgRenderer> | undefined;
|
||||
|
||||
export function renderMathSvg(root: HTMLElement) {
|
||||
for (const element of root.querySelectorAll<HTMLElement>("[data-math]")) {
|
||||
const inputs = [...root.querySelectorAll<HTMLElement>("[data-math]")];
|
||||
const copies = inputs.some((el) => declaresMathMacros(el.textContent ?? "")) ? null : new Map<string, HTMLElement>();
|
||||
for (const element of inputs) {
|
||||
const mode = element.getAttribute("data-math");
|
||||
const source = element.textContent?.trim();
|
||||
if (!source || (mode !== "inline" && mode !== "display")) continue;
|
||||
try {
|
||||
const key = mode + ":" + source;
|
||||
const cached = copies?.get(key);
|
||||
if (cached) {
|
||||
element.replaceChildren(...Array.from(cached.childNodes, (node) => node.cloneNode(true)));
|
||||
element.setAttribute("data-math-svg", mode);
|
||||
element.removeAttribute("data-math");
|
||||
continue;
|
||||
}
|
||||
convert ??= createSvgRenderer();
|
||||
const output = convert(source, mode === "display");
|
||||
const svg = output.querySelector("svg");
|
||||
@@ -48,6 +60,7 @@ export function renderMathSvg(root: HTMLElement) {
|
||||
element.setAttribute("data-math-svg", mode);
|
||||
element.removeAttribute("data-math");
|
||||
element.replaceChildren(...output.childNodes);
|
||||
if (copies && !element.querySelector("[id]")) copies.set(key, element);
|
||||
} catch {
|
||||
// Keep unsupported TeX for the existing KaTeX renderer.
|
||||
}
|
||||
|
||||
@@ -151,6 +151,16 @@ describe("mermaid in the markdown preview", () => {
|
||||
expect(root.querySelector("svg")).toBe(svg);
|
||||
});
|
||||
|
||||
it("renders repeated diagrams with math labels once in the same pass", async () => {
|
||||
const diagram = '```mermaid\nflowchart LR\n A["$$x^2$$"] --> B\n```\n';
|
||||
const root = preview([diagram, diagram, diagram.replace("x^2", "x^3")].join("\n"));
|
||||
await renderMermaidIn(root).done;
|
||||
const drawings = [...root.querySelectorAll(".mermaid-output svg")];
|
||||
expect(m.render).toHaveBeenCalledTimes(2);
|
||||
expect(drawings).toHaveLength(3);
|
||||
expect(new Set(drawings.map((drawing) => drawing.id)).size).toBe(3);
|
||||
});
|
||||
|
||||
it("applies a cached diagram with fresh SVG ids so copies don't share markers", async () => {
|
||||
const first = preview(SEQ);
|
||||
await renderMermaidIn(first, []).done;
|
||||
|
||||
@@ -217,7 +217,15 @@ async function renderOne(source: string, key: string): Promise<Result> {
|
||||
|
||||
/** Resolves `null` when the pass was superseded before its turn came. */
|
||||
function enqueue(source: string, key: string, live: () => boolean): Promise<Result | null> {
|
||||
const p = queue.then(() => (live() ? renderOne(source, key) : null));
|
||||
const k = `${key}\n${source}`;
|
||||
const p = queue.then(async () => {
|
||||
if (!live()) return null;
|
||||
const cached = cache.get(k);
|
||||
if (cached) return cached;
|
||||
const result = await renderOne(source, key);
|
||||
remember(k, result);
|
||||
return result;
|
||||
});
|
||||
queue = p.catch(() => undefined);
|
||||
return p;
|
||||
}
|
||||
@@ -289,6 +297,7 @@ export function renderMermaidIn(root: HTMLElement, previous: Node[] = []): Merma
|
||||
if (!blocks.length) return { async: false, done: Promise.resolve(), cancel: () => {} };
|
||||
const key = themeKey();
|
||||
const pending: Promise<void>[] = [];
|
||||
const rendering = new Map<string, Promise<Result | null>>();
|
||||
blocks.forEach((block, i) => {
|
||||
const source = (block.querySelector("code")?.textContent ?? "").replace(/\n+$/, "");
|
||||
const k = `${key}\n${source}`;
|
||||
@@ -310,11 +319,14 @@ export function renderMermaidIn(root: HTMLElement, previous: Node[] = []): Merma
|
||||
}
|
||||
drawn.delete(block);
|
||||
show(block, null, previous[i]);
|
||||
let result = rendering.get(k);
|
||||
if (!result) {
|
||||
result = enqueue(source, key, () => live);
|
||||
rendering.set(k, result);
|
||||
}
|
||||
pending.push(
|
||||
enqueue(source, key, () => live).then((r) => {
|
||||
if (!r) return;
|
||||
remember(k, r);
|
||||
if (!live) return;
|
||||
result.then((r) => {
|
||||
if (!live || !r) return;
|
||||
show(block, r);
|
||||
drawn.set(block, k);
|
||||
keep();
|
||||
|
||||
@@ -11,6 +11,7 @@ let activeSlot: Partial<EditorSlot> | null = null;
|
||||
vi.mock("@/editor/core/controller", async (importOriginal) => ({
|
||||
...(await importOriginal<object>()),
|
||||
editorController: () => ({
|
||||
slotFor: () => activeSlot,
|
||||
get activeSlot() {
|
||||
return activeSlot;
|
||||
},
|
||||
@@ -38,7 +39,7 @@ describe("preview-only scroll position", () => {
|
||||
views.push(view);
|
||||
return view;
|
||||
};
|
||||
const activate = (view: EditorView) => (activeSlot = { view, disposed: false });
|
||||
const activate = (view: EditorView) => (activeSlot = { view, live: view, disposed: false });
|
||||
|
||||
beforeEach(() => {
|
||||
disposers.push(registerMarkdownLiveSource());
|
||||
@@ -80,6 +81,92 @@ describe("preview-only scroll position", () => {
|
||||
second.unmount();
|
||||
});
|
||||
|
||||
it("handles a long preview gesture from its first pixel and leaves nested scrolling native", () => {
|
||||
open(mdCtx);
|
||||
act(() => useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, t: "preview" } })));
|
||||
render(
|
||||
<MarkdownEditor path={mdCtx.path} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
Object.defineProperties(preview, {
|
||||
clientHeight: { value: 400 },
|
||||
scrollHeight: { value: 2000, configurable: true },
|
||||
});
|
||||
const scrollBy = vi.fn();
|
||||
preview.scrollBy = scrollBy;
|
||||
const nested = document.createElement("pre");
|
||||
nested.style.overflowY = "auto";
|
||||
Object.defineProperties(nested, { clientHeight: { value: 30 }, scrollHeight: { value: 120 } });
|
||||
preview.appendChild(nested);
|
||||
const wheel = (target: Element, init: WheelEventInit) =>
|
||||
target.dispatchEvent(
|
||||
new WheelEvent("wheel", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
...init,
|
||||
}),
|
||||
);
|
||||
expect(wheel(preview, { deltaY: 1 })).toBe(false);
|
||||
expect(wheel(preview, { deltaY: -300 })).toBe(true);
|
||||
expect(wheel(preview, { deltaY: 300, deltaMode: 1 })).toBe(true);
|
||||
expect(wheel(preview, { deltaY: 300, deltaX: 400 })).toBe(true);
|
||||
expect(wheel(nested, { deltaY: 300 })).toBe(true);
|
||||
expect(wheel(preview, { deltaY: 300, deltaX: 1 })).toBe(false);
|
||||
Object.defineProperty(preview, "scrollHeight", { value: 650 });
|
||||
expect(wheel(preview, { deltaY: 1 })).toBe(true);
|
||||
expect(scrollBy.mock.calls).toEqual([
|
||||
[0, 1],
|
||||
[1, 300],
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps unchanged equations across edits and tab switches", async () => {
|
||||
const view = open(mdCtx);
|
||||
activate(view);
|
||||
const source = "$x$ and $y$.";
|
||||
act(() => view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: source } }));
|
||||
const preview = () =>
|
||||
render(
|
||||
<MarkdownEditor path={mdCtx.path} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
const nodes = () => [...screen.getByRole("document").querySelectorAll("[data-math-svg] > svg")];
|
||||
const first = preview();
|
||||
await vi.waitFor(() => expect(nodes()).toHaveLength(2));
|
||||
const [x, y] = nodes();
|
||||
const at = source.indexOf("y");
|
||||
act(() => view.dispatch({ changes: { from: at, to: at + 1, insert: "z" } }));
|
||||
await vi.waitFor(() => expect(nodes().map((n) => n.getAttribute("aria-label"))).toEqual(["x", "z"]));
|
||||
const [sameX, z] = nodes();
|
||||
expect(sameX).toBe(x);
|
||||
expect(z).not.toBe(y);
|
||||
first.unmount();
|
||||
preview();
|
||||
expect(nodes()[0]).toBe(x);
|
||||
expect(nodes()[1]).toBe(z);
|
||||
});
|
||||
|
||||
it("refreshes dependent equations after a TeX macro changes", async () => {
|
||||
const view = open(mdCtx);
|
||||
activate(view);
|
||||
const text = String.raw`$\def\previewletter{a}\previewletter$ and $\previewletter$`;
|
||||
act(() => view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } }));
|
||||
render(
|
||||
<MarkdownEditor path={mdCtx.path} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
const letters = () =>
|
||||
[...screen.getByRole("document").querySelectorAll("mjx-assistive-mml mi")].map((el) => el.textContent);
|
||||
await vi.waitFor(() => expect(letters()).toEqual(["a", "a"]));
|
||||
const at = text.indexOf("{a}") + 1;
|
||||
act(() => view.dispatch({ changes: { from: at, to: at + 1, insert: "b" } }));
|
||||
await vi.waitFor(() => expect(letters()).toEqual(["b", "b"]));
|
||||
});
|
||||
|
||||
it("re-applies a restore that clamped to not-yet-drawn content", async () => {
|
||||
open(mdCtx);
|
||||
activate(views[0]!);
|
||||
|
||||
@@ -131,6 +131,19 @@ describe("markdown preview rendering", () => {
|
||||
expect(root.querySelector("h1")?.id).toBe("user-content-title");
|
||||
});
|
||||
|
||||
it("keeps embedded image destinations and code samples intact", () => {
|
||||
const url = "data:image/png;base64," + "abcd".repeat(100);
|
||||
const line = ``;
|
||||
const render = createMarkdownRenderer();
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = render([line, "", "## Next", "", line].join("\n"));
|
||||
expect([...root.querySelectorAll("img")].map((img) => img.dataset.src)).toEqual([url, url]);
|
||||
expect(root.querySelector("h2")?.parentElement?.dataset.line).toBe("2");
|
||||
root.innerHTML = render([line, "", "```md", line, "```"].join("\n"));
|
||||
expect(root.querySelector("code")?.textContent?.trimEnd()).toBe(line);
|
||||
expect(root.querySelector("img")?.dataset.src).toBe(url);
|
||||
});
|
||||
|
||||
it("sanitizes and defers image loading", () => {
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = renderMarkdown(
|
||||
@@ -362,6 +375,28 @@ describe("markdown preview rendering", () => {
|
||||
expect(previewOffsetForLine([], 3, 400)).toBe(0);
|
||||
});
|
||||
|
||||
it("tracks table rows across the delimiter and excludes trailing blank lines from a block", () => {
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = renderMarkdown("| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n\nNext");
|
||||
const table = root.querySelector("table[data-markdown-table]")!;
|
||||
expect(table.querySelectorAll("tr")).toHaveLength(3);
|
||||
expect(table.parentElement?.dataset).toMatchObject({ line: "0", endLine: "4" });
|
||||
expect(root.lastElementChild?.getAttribute("data-line")).toBe("5");
|
||||
});
|
||||
|
||||
it("follows source characters inside a wrapped block and crosses the gap below its rendered box", () => {
|
||||
const blocks = [
|
||||
{ line: 0, endLine: 2, top: 10, bottom: 110 },
|
||||
{ line: 4, endLine: 5, top: 130, bottom: 160 },
|
||||
];
|
||||
const sourceOffsets = [0, 80, 100, 101, 102, 110];
|
||||
expect(previewOffsetForLine(blocks, 0.5, 400, sourceOffsets)).toBe(50);
|
||||
expect(previewOffsetForLine(blocks, 1, 400, sourceOffsets)).toBe(90);
|
||||
expect(previewOffsetForLine(blocks, 2, 400, sourceOffsets)).toBe(110);
|
||||
expect(previewOffsetForLine(blocks, 3, 400, sourceOffsets)).toBe(120);
|
||||
expect(previewOffsetForLine(blocks, 4, 400, sourceOffsets)).toBe(130);
|
||||
});
|
||||
|
||||
it("finds the block at the top of a scrolled preview", () => {
|
||||
const blocks = [
|
||||
{ line: 2, top: 0 },
|
||||
|
||||
@@ -150,29 +150,61 @@ function trackContainers(raw: string, open: string[]) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The preview's blocks: each top-level block, or run of blocks inside one HTML container, as unsanitized HTML. */
|
||||
function blocks(text: string): { line: number; html: string }[] {
|
||||
type MarkdownBlock = { line: number; endLine: number; html: string };
|
||||
|
||||
function lexBlocks(body: string): TokensList {
|
||||
// Marked repeatedly scans the remaining input for block boundaries. Keep the bytes of
|
||||
// standalone embedded images out of those scans and restore their URLs before rendering.
|
||||
const prefix = "openidea-embedded-image-";
|
||||
if (!body.includes(";base64,") || body.includes(prefix)) return marked.lexer(body);
|
||||
const urls: string[] = [];
|
||||
const compact = body.replace(
|
||||
/^!\[\]\((data:image\/[\w.+-]+;base64,[A-Za-z0-9+/]{256,}={0,2})\)(?=[ \t]*\r?$)/gm,
|
||||
(_, url: string) => {
|
||||
urls.push(url);
|
||||
return ``;
|
||||
},
|
||||
);
|
||||
const tokens = marked.lexer(compact);
|
||||
let restored = 0;
|
||||
for (const token of tokens) {
|
||||
if (restored === urls.length) break;
|
||||
if (!token.raw.includes(prefix)) continue;
|
||||
const image = token.type === "paragraph" && token.tokens?.length === 1 && token.tokens[0];
|
||||
if (!image || image.type !== "image" || image.href !== prefix + restored || token.raw.trimEnd() !== image.raw)
|
||||
return marked.lexer(body);
|
||||
image.href = urls[restored++]!;
|
||||
}
|
||||
return restored === urls.length ? tokens : marked.lexer(body);
|
||||
}
|
||||
|
||||
/** Top-level source ranges; an open HTML container groups its enclosed blocks. */
|
||||
function blocks(text: string): MarkdownBlock[] {
|
||||
const front = frontMatter(text);
|
||||
const body = front ? text.split("\n").slice(front.lines).join("\n") : text;
|
||||
const tokens = marked.lexer(body);
|
||||
const tokens = lexBlocks(body);
|
||||
const slugs = new Map<string, number>();
|
||||
let line = front?.lines ?? 0;
|
||||
const out = front ? [{ line: 0, html: frontMatterTable(front.fields) }] : [];
|
||||
const out = front ? [{ line: 0, endLine: front.lines, html: frontMatterTable(front.fields) }] : [];
|
||||
// Blocks inside an HTML container left open (`<details>`, `<div>`…) share its wrapper up to
|
||||
// the close: a wrapper per block would end the container early and spill its content out.
|
||||
const open: string[] = [];
|
||||
let group: { line: number; html: string } | null = null;
|
||||
let group: MarkdownBlock | null = null;
|
||||
for (const token of tokens) {
|
||||
const start = line;
|
||||
line += countLines(token.raw);
|
||||
if (token.type === "space" || token.type === "footnoteDefinition") continue;
|
||||
const list = Object.assign([token], { links: tokens.links }) as TokensList;
|
||||
let body = marked.parser(list);
|
||||
if (token.type === "table") {
|
||||
body = body.replace(/^<table>/, '<table data-markdown-table="">');
|
||||
}
|
||||
if (token.type === "heading") {
|
||||
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 ??= { line: start, endLine: start, html: "" };
|
||||
group.endLine = start + countLines(token.raw.trimEnd()) + 1;
|
||||
group.html += body;
|
||||
if (token.type === "html") trackContainers(token.raw, open);
|
||||
if (open.length) continue;
|
||||
@@ -181,23 +213,24 @@ function blocks(text: string): { line: number; html: string }[] {
|
||||
}
|
||||
if (group) out.push(group);
|
||||
const footnotes = renderFootnotes(marked, tokens);
|
||||
if (footnotes) out.push({ line: countLines(text), html: footnotes });
|
||||
if (footnotes) out.push({ line: countLines(text), endLine: countLines(text) + 1, html: footnotes });
|
||||
return out;
|
||||
}
|
||||
|
||||
const SANITIZE = {
|
||||
USE_PROFILES: { html: true },
|
||||
ADD_ATTR: ["data-src", "data-line", "data-front-matter", "data-math"],
|
||||
ADD_ATTR: ["data-src", "data-line", "data-end-line", "data-markdown-table", "data-front-matter", "data-math"],
|
||||
// The preview shares the IDE's document: a `<style>` in a file would restyle the whole IDE.
|
||||
// `srcset` and `<source>` would pick an image past the one the preview loads.
|
||||
FORBID_TAGS: ["style", "form", "source"],
|
||||
FORBID_ATTR: ["style", "srcset"],
|
||||
};
|
||||
|
||||
const wrap = (line: number, html: string) => `<div data-line="${line}">${html}</div>`;
|
||||
const wrap = (line: number, endLine: number, html: string) =>
|
||||
`<div data-line="${line}" data-end-line="${endLine}">${html}</div>`;
|
||||
|
||||
const sanitizeWhole = (all: readonly { line: number; html: string }[]) =>
|
||||
purify().sanitize(all.map((b) => wrap(b.line, b.html)).join(""), SANITIZE);
|
||||
const sanitizeWhole = (all: readonly MarkdownBlock[]) =>
|
||||
purify().sanitize(all.map((b) => wrap(b.line, b.endLine, b.html)).join(""), SANITIZE);
|
||||
|
||||
/**
|
||||
* 0-based source line of the heading the preview gives the anchor `anchor` (with or without
|
||||
@@ -242,11 +275,11 @@ export function createMarkdownRenderer(): (text: string) => string {
|
||||
cache = kept;
|
||||
const parts = all.map((b) => cache.get(b.html));
|
||||
if (parts.some((part) => typeof part !== "string")) return sanitizeWhole(all);
|
||||
return all.map((b, i) => wrap(b.line, parts[i]!)).join("");
|
||||
return all.map((b, i) => wrap(b.line, b.endLine, parts[i]!)).join("");
|
||||
};
|
||||
}
|
||||
|
||||
const WRAPPER_OPEN = '<div data-line="0">';
|
||||
const WRAPPER_OPEN = '<div data-line="0" data-end-line="1">';
|
||||
// Tags that change how the parser reads the blocks after them without moving the markers.
|
||||
const PARSER_STATE = /<(?:form|frameset)(?=[\s/>]|$)/i;
|
||||
|
||||
@@ -280,7 +313,7 @@ function sanitizeApart(blocks: readonly string[], cache: Map<string, string | nu
|
||||
p.addHook("beforeSanitizeElements", checkParse);
|
||||
let html: string;
|
||||
try {
|
||||
html = p.sanitize(blocks.map((b) => wrap(0, b) + marker).join(""), SANITIZE);
|
||||
html = p.sanitize(blocks.map((b) => wrap(0, 1, b) + marker).join(""), SANITIZE);
|
||||
} finally {
|
||||
p.removeHook("beforeSanitizeElements", checkParse);
|
||||
}
|
||||
@@ -340,20 +373,37 @@ export function resolveLink(file: string, href: string): LinkTarget | null {
|
||||
* between the blocks around it (`blocks` sorted by line, with their offsets).
|
||||
*/
|
||||
export function previewOffsetForLine(
|
||||
blocks: ReadonlyArray<{ line: number; top: number }>,
|
||||
blocks: ReadonlyArray<{ line: number; top: number; endLine?: number; bottom?: number }>,
|
||||
line: number,
|
||||
end: number,
|
||||
sourceOffsets?: readonly number[],
|
||||
): number {
|
||||
if (!blocks.length) return 0;
|
||||
let i = 0;
|
||||
while (i + 1 < blocks.length && blocks[i + 1]!.line <= line) i++;
|
||||
const a = blocks[i]!;
|
||||
let lo = 0,
|
||||
hi = blocks.length;
|
||||
while (lo < hi) {
|
||||
const mid = lo + Math.floor((hi - lo) / 2);
|
||||
if (blocks[mid]!.line <= line) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
const a = blocks[Math.max(0, lo - 1)]!;
|
||||
if (line <= a.line) return a.top;
|
||||
const b = blocks[i + 1];
|
||||
const nextLine = b?.line ?? a.line + 1;
|
||||
const nextTop = b?.top ?? end;
|
||||
const t = Math.min(1, (line - a.line) / Math.max(1, nextLine - a.line));
|
||||
return a.top + t * (nextTop - a.top);
|
||||
const b = blocks[lo];
|
||||
const endLine = a.endLine ?? b?.line ?? a.line + 1;
|
||||
const bottom = a.bottom ?? b?.top ?? end;
|
||||
if (line < endLine) {
|
||||
let progress = (line - a.line) / Math.max(1, endLine - a.line);
|
||||
if (sourceOffsets && endLine < sourceOffsets.length) {
|
||||
const row = Math.floor(line);
|
||||
const start = sourceOffsets[a.line]!;
|
||||
const length = sourceOffsets[endLine]! - start;
|
||||
const offset = sourceOffsets[row]! + (line - row) * (sourceOffsets[row + 1]! - sourceOffsets[row]!);
|
||||
if (length > 0) progress = (offset - start) / length;
|
||||
}
|
||||
return a.top + progress * (bottom - a.top);
|
||||
}
|
||||
if (!b || b.line <= endLine) return bottom;
|
||||
return bottom + ((line - endLine) / (b.line - endLine)) * (b.top - bottom);
|
||||
}
|
||||
|
||||
/** Source line of the block at the top of a preview scrolled to `offset`: the first one if none is above it. */
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { useLiveMarkdown } from "./live";
|
||||
import { followMarkdownSource } from "./splitScroll";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
useLiveMarkdown.setState({}, true);
|
||||
});
|
||||
|
||||
it("retargets one animation, settles exactly, and yields to manual scrolling", () => {
|
||||
const root = document.createElement("div");
|
||||
Object.defineProperties(root, { scrollHeight: { value: 900 }, clientHeight: { value: 100 } });
|
||||
let callback: FrameRequestCallback | undefined;
|
||||
let now = 0;
|
||||
vi.spyOn(performance, "now").mockImplementation(() => now);
|
||||
const schedule = vi.fn((cb: FrameRequestCallback) => {
|
||||
callback = cb;
|
||||
return 1;
|
||||
});
|
||||
vi.stubGlobal("requestAnimationFrame", schedule);
|
||||
vi.stubGlobal("cancelAnimationFrame", () => {
|
||||
callback = undefined;
|
||||
});
|
||||
const tick = (dt: number) => {
|
||||
const cb = callback;
|
||||
callback = undefined;
|
||||
now += dt;
|
||||
cb?.(now);
|
||||
};
|
||||
const move = (topLine: number, sourceAtEnd = false) =>
|
||||
useLiveMarkdown.setState((s) => ({
|
||||
doc: { ...s.doc!, topLine, sourceAtEnd, scrollSeq: (s.doc?.scrollSeq ?? 0) + 1 },
|
||||
}));
|
||||
const follow = followMarkdownSource("doc", root, (line) => line * 10);
|
||||
try {
|
||||
move(10);
|
||||
move(40);
|
||||
expect(schedule).toHaveBeenCalledTimes(1);
|
||||
tick(40);
|
||||
expect(root.scrollTop).toBeCloseTo(400 * (1 - Math.exp(-1)));
|
||||
move(50, true);
|
||||
for (let i = 0; i < 10; i++) tick(40);
|
||||
expect(root.scrollTop).toBe(800);
|
||||
expect(callback).toBeUndefined();
|
||||
move(5);
|
||||
tick(16);
|
||||
root.scrollTop = 350;
|
||||
tick(16);
|
||||
expect(root.scrollTop).toBe(350);
|
||||
expect(callback).toBeUndefined();
|
||||
move(20);
|
||||
root.dispatchEvent(new Event("wheel"));
|
||||
expect(callback).toBeUndefined();
|
||||
} finally {
|
||||
follow.dispose();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useLiveMarkdown } from "./live";
|
||||
|
||||
/** Keep one follower per split. A new editor position retargets the frame already in flight. */
|
||||
export function followMarkdownSource(path: string, root: HTMLElement, offsetForLine: (line: number) => number) {
|
||||
let frame = 0;
|
||||
let lastTime = 0;
|
||||
let position = root.scrollTop;
|
||||
let applied = position;
|
||||
const reducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)");
|
||||
const target = () => {
|
||||
const state = useLiveMarkdown.getState()[path];
|
||||
const max = Math.max(0, root.scrollHeight - root.clientHeight);
|
||||
return state?.sourceAtEnd ? max : Math.min(max, Math.max(0, offsetForLine(state?.topLine ?? 0)));
|
||||
};
|
||||
const stop = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = 0;
|
||||
};
|
||||
const align = () => {
|
||||
stop();
|
||||
root.scrollTop = target();
|
||||
};
|
||||
const step = (time: number) => {
|
||||
frame = 0;
|
||||
if (Math.abs(root.scrollTop - applied) > 1) return;
|
||||
const destination = target();
|
||||
const elapsed = Math.max(0, Math.min(time - lastTime, 100));
|
||||
lastTime = time;
|
||||
position += (destination - position) * -Math.expm1(-elapsed / 40);
|
||||
if (Math.abs(position - destination) < 0.5 || reducedMotion?.matches) {
|
||||
root.scrollTop = destination;
|
||||
return;
|
||||
}
|
||||
root.scrollTop = position;
|
||||
applied = root.scrollTop;
|
||||
frame = requestAnimationFrame(step);
|
||||
};
|
||||
const off = useLiveMarkdown.subscribe((next, prev) => {
|
||||
const a = next[path],
|
||||
b = prev[path];
|
||||
if (!a || (a.topLine === b?.topLine && a.scrollSeq === b?.scrollSeq && a.sourceAtEnd === b?.sourceAtEnd)) return;
|
||||
if (reducedMotion?.matches) return align();
|
||||
if (frame) return;
|
||||
applied = position = root.scrollTop;
|
||||
lastTime = performance.now();
|
||||
frame = requestAnimationFrame(step);
|
||||
});
|
||||
root.addEventListener("wheel", stop, { passive: true });
|
||||
root.addEventListener("touchstart", stop, { passive: true });
|
||||
return {
|
||||
align,
|
||||
dispose() {
|
||||
stop();
|
||||
off();
|
||||
root.removeEventListener("wheel", stop);
|
||||
root.removeEventListener("touchstart", stop);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -19,6 +19,7 @@ let activeSlot: Partial<EditorSlot> | null = null;
|
||||
vi.mock("@/editor/core/controller", async (importOriginal) => ({
|
||||
...(await importOriginal<object>()),
|
||||
editorController: () => ({
|
||||
slotFor: () => activeSlot,
|
||||
get activeSlot() {
|
||||
return activeSlot;
|
||||
},
|
||||
@@ -47,7 +48,7 @@ describe("editor font size actions", () => {
|
||||
views.push(view);
|
||||
return view;
|
||||
};
|
||||
const activate = (view: EditorView) => (activeSlot = { view, disposed: false });
|
||||
const activate = (view: EditorView) => (activeSlot = { view, live: view, disposed: false });
|
||||
const zoom = (view: EditorView) => view.state.field(fontZoom);
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* the user select and copy text in the Markdown preview, documentation popups,
|
||||
* message dialogs and notifications, while chrome stays unselectable.
|
||||
*/
|
||||
import { Text } from "@codemirror/state";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { renderCode, renderMarkup } from "@/editor/lsp/markdown";
|
||||
@@ -23,8 +24,9 @@ describe("selectable read-only surfaces", () => {
|
||||
act(() =>
|
||||
useLiveMarkdown.setState({
|
||||
"/p/README.md": {
|
||||
text: "# Title\n\nSome *text*",
|
||||
text: Text.of(["# Title", "", "Some *text*"]),
|
||||
topLine: 0,
|
||||
sourceAtEnd: false,
|
||||
scrollSeq: 0,
|
||||
fontZoom: 0,
|
||||
caretLine: 0,
|
||||
|
||||
@@ -644,6 +644,7 @@ export async function openFileExternally(path: string): Promise<boolean> {
|
||||
* view stays alive.
|
||||
*/
|
||||
export interface TextEditorWrapperContribution {
|
||||
keepAlive?: boolean;
|
||||
id: string;
|
||||
matches(path: string): boolean;
|
||||
component: ComponentType<{ path: string; tabId: string; children: ReactNode; actionsInTabs?: boolean }>;
|
||||
|
||||
Reference in new issue
Заблокувати користувача