дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
feat(markdown): record preview clicks in navigation history for Back/Forward (#8172)
Back/Forward now walk through positions in Markdown previews. In Preview Only mode a click records the clicked source line (the preview keeps its scroll) and Back/Forward scroll to the remembered line with a short highlight (none under reduced motion). Same-file #anchor links record their origin and destination in both Preview Only and Split mode; a link to another file records the link line first. In Split mode a plain click in the preview leaves the source editor's caret alone. A clicked position is no longer overwritten by the passive shown-line update, and the Live MDX preview forwards the Back/Forward shortcuts from its iframe. Co-authored-by: dengliu <[email protected]>
Цей коміт міститься в:
1 джерело
66b90e3ee8
коміт
8a301dad86
12 files changed
+885
-26
No files matched your search
@@ -208,6 +208,36 @@ describe("EditorController", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves explicitly clicked Markdown preview lines over subsequent passive shownLine scroll updates", async () => {
|
||||
const text = Array.from({ length: 80 }, (_, i) => `line ${i}`).join("\n");
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.md": text }));
|
||||
ctrl.start();
|
||||
await ctrl.openFile("/p/a.md", { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
const view = slot.mount(host);
|
||||
try {
|
||||
setShownLine("/p/a.md", 15);
|
||||
view.dispatch({
|
||||
selection: EditorSelection.cursor(view.state.doc.line(21).from),
|
||||
userEvent: "select.pointer",
|
||||
});
|
||||
setShownLine("/p/a.md", 50);
|
||||
view.dispatch({
|
||||
selection: EditorSelection.cursor(view.state.doc.line(56).from),
|
||||
userEvent: "select.pointer",
|
||||
});
|
||||
// Passive scroll after clicking must not overwrite the clicked entry on Back/Forward.
|
||||
setShownLine("/p/a.md", 50);
|
||||
await ctrl.back();
|
||||
expect(slot.caret().line).toBe(20);
|
||||
await ctrl.forward();
|
||||
expect(slot.caret().line).toBe(55);
|
||||
} finally {
|
||||
setShownLine("/p/a.md", null);
|
||||
}
|
||||
});
|
||||
|
||||
it("goes back to the file whose last tab was just closed, then to the place before it", async () => {
|
||||
const text = Array.from({ length: 50 }, (_, i) => `line ${i}`).join("\n");
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/x.ts": "x\n", "/p/a.ts": text }));
|
||||
|
||||
@@ -331,6 +331,8 @@ export class EditorController implements SlotHost {
|
||||
readonly nav = new NavigationHistory();
|
||||
readonly edits = new EditHistory();
|
||||
private navSuppress = 0;
|
||||
/** Caret explicitly placed by a user click/navigation, protected from passive `shownLine` scroll overwrites. */
|
||||
private pinnedNavCaret: { slot: EditorSlot; line: number } | null = null;
|
||||
activeSlot: EditorSlot | null = null;
|
||||
private statusScheduled = false;
|
||||
private disposers: Array<() => void> = [];
|
||||
@@ -495,6 +497,7 @@ export class EditorController implements SlotHost {
|
||||
this.closeCommitted = false;
|
||||
this.preparedDocuments.clear();
|
||||
this.nav.clear();
|
||||
this.pinnedNavCaret = null;
|
||||
this.edits.clear();
|
||||
this.restoredTabs.clear();
|
||||
this.restoredViews.clear();
|
||||
@@ -565,6 +568,7 @@ export class EditorController implements SlotHost {
|
||||
this.closeSession = null;
|
||||
this.closeCommitted = false;
|
||||
this.preparedDocuments.clear();
|
||||
this.pinnedNavCaret = null;
|
||||
for (const slot of this.slots.values()) slot.dispose();
|
||||
this.slots.clear();
|
||||
clearBreadcrumbOverrides();
|
||||
@@ -897,6 +901,7 @@ export class EditorController implements SlotHost {
|
||||
|
||||
private setActiveSlot(slot: EditorSlot | null, nonTextTab: Tab | null = null) {
|
||||
const changed = slot !== this.activeSlot;
|
||||
if (changed) this.pinnedNavCaret = null;
|
||||
this.activeSlot = slot;
|
||||
_setActiveEditor(slot?.handle ?? null);
|
||||
if (changed) {
|
||||
@@ -948,7 +953,8 @@ export class EditorController implements SlotHost {
|
||||
// The place left behind is where the caret was right before the navigation.
|
||||
const paneId = this.locateTab(slot.tabId)?.paneId;
|
||||
this.nav.update({ path: slot.model.path, ...navigatedFrom, ...(paneId ? { paneId } : {}) });
|
||||
this.recordNav(slot, true);
|
||||
this.pinnedNavCaret = { slot, line: slot.caret().line };
|
||||
this.recordNav(slot, true, true);
|
||||
}
|
||||
// The status bar reflects the view state synchronously (programmatic and
|
||||
// synthetic selection changes included); events / history are throttled.
|
||||
@@ -1225,19 +1231,21 @@ export class EditorController implements SlotHost {
|
||||
|
||||
// --- navigation history --------------------------------------------------------------
|
||||
|
||||
private slotLocation(slot: EditorSlot): Omit<NavigationLocation, "time"> {
|
||||
private slotLocation(slot: EditorSlot, preferCaret = false): Omit<NavigationLocation, "time"> {
|
||||
const c = slot.caret();
|
||||
// A view standing in for the editor (Markdown Preview only) is where the reader is.
|
||||
const shown = shownLine(slot.model.path);
|
||||
const pinned = this.pinnedNavCaret?.slot === slot && this.pinnedNavCaret.line === c.line;
|
||||
// A view standing in for the editor (Markdown Preview only) is where the reader is,
|
||||
// unless the user explicitly clicked/navigated the caret to a specific line.
|
||||
const shown = preferCaret || pinned ? null : shownLine(slot.model.path);
|
||||
const loc = shown === null || shown === c.line ? { line: c.line, col: c.col } : { line: shown, col: 0 };
|
||||
const paneId = this.locateTab(slot.tabId)?.paneId;
|
||||
return { path: slot.model.path, ...loc, ...(paneId ? { paneId } : {}) };
|
||||
}
|
||||
|
||||
/** `navigation`: the caret got here by a navigation (see NavigationHistory.update). */
|
||||
private recordNav(slot: EditorSlot, navigation = false) {
|
||||
private recordNav(slot: EditorSlot, navigation = false, preferCaret = false) {
|
||||
if (this.navSuppress > 0 || slot.disposed) return;
|
||||
this.nav.update(this.slotLocation(slot), navigation);
|
||||
this.nav.update(this.slotLocation(slot, preferCaret), navigation);
|
||||
}
|
||||
|
||||
private recordInput(input: EditorInput, paneId: string | undefined, navigation = true) {
|
||||
@@ -1250,10 +1258,10 @@ export class EditorController implements SlotHost {
|
||||
);
|
||||
}
|
||||
|
||||
private recordActiveEditor(navigation = true) {
|
||||
private recordActiveEditor(navigation = true, preferCaret = false) {
|
||||
if (this.navSuppress > 0) return;
|
||||
if (this.activeSlot && !this.activeSlot.disposed) {
|
||||
this.recordNav(this.activeSlot, navigation);
|
||||
this.recordNav(this.activeSlot, navigation, preferCaret);
|
||||
return;
|
||||
}
|
||||
const input = this.activeInput();
|
||||
@@ -1327,7 +1335,10 @@ export class EditorController implements SlotHost {
|
||||
});
|
||||
} finally {
|
||||
this.navSuppress--;
|
||||
if (gen === this.navGeneration && this.activeSlot) this.recordNav(this.activeSlot);
|
||||
if (gen === this.navGeneration && this.activeSlot) {
|
||||
this.pinnedNavCaret = loc.input ? null : { slot: this.activeSlot, line: this.activeSlot.caret().line };
|
||||
this.recordNav(this.activeSlot, false, !loc.input);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1730,7 +1741,10 @@ export class EditorController implements SlotHost {
|
||||
}
|
||||
} finally {
|
||||
this.navSuppress--;
|
||||
if (this.navSuppress === 0 && this.isCurrentOpening(generation)) this.recordActiveEditor(true);
|
||||
if (this.navSuppress === 0 && this.isCurrentOpening(generation)) {
|
||||
this.pinnedNavCaret = null;
|
||||
this.recordActiveEditor(true, Boolean(o.selection));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -405,6 +405,28 @@
|
||||
color: var(--fg-search-match, inherit);
|
||||
}
|
||||
|
||||
@keyframes navPulse {
|
||||
0% {
|
||||
background-color: color-mix(in srgb, var(--accent) 18%, transparent);
|
||||
box-shadow: 0 0 0 4px color-mix(in srgb, var(--accent) 18%, transparent);
|
||||
}
|
||||
100% {
|
||||
background-color: transparent;
|
||||
box-shadow: 0 0 0 4px transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.navPulse {
|
||||
border-radius: var(--radius-small);
|
||||
animation: navPulse 900ms ease-out;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.navPulse {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Static MDX documentation tags rendered safely through DOMPurify */
|
||||
.preview :global(aside[data-mdx-callout]) {
|
||||
margin: 0 0 1em;
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import clsx from "clsx";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { EditorSelection, Text } from "@codemirror/state";
|
||||
import { editorController } from "@/editor/core/controller";
|
||||
import { Direction, EditorView } from "@codemirror/view";
|
||||
import { call, commands, isTauri, onIdeEvent, type ProjectInfo } from "@/platform/ipc";
|
||||
@@ -65,11 +65,13 @@ import {
|
||||
import { followMarkdownSource } from "./splitScroll";
|
||||
import {
|
||||
installMarkdownSourceScroll,
|
||||
previewClickNavigation,
|
||||
publishPreviewSelection,
|
||||
publishPreviewTop,
|
||||
stepMarkdownPreviewFontZoom,
|
||||
useLiveMarkdown,
|
||||
} from "./live";
|
||||
import { previewLineAtClick, pulsePreviewLine } from "./previewNavigation";
|
||||
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
|
||||
import { hasMermaid, MERMAID_SELECTOR, renderMermaidIn } from "./mermaid";
|
||||
import { declaresMathMacros } from "@/editor/lsp/markdownMath";
|
||||
@@ -730,6 +732,7 @@ function MarkdownPreview({
|
||||
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 navSeq = useLiveMarkdown((s) => s[path]?.navSeq ?? 0);
|
||||
const find = useLiveMarkdown((s) => s[path]?.find ?? null);
|
||||
const editorSelection = useLiveMarkdown((s) => s[path]?.editorSelection ?? "");
|
||||
const highlightSelection = useEditorPrefs().codeEditing.highlightSelection;
|
||||
@@ -789,6 +792,8 @@ function MarkdownPreview({
|
||||
const [diagramsDrawn, setDiagramsDrawn] = useState(0);
|
||||
const [contentHeight, setContentHeight] = useState(0);
|
||||
const seenCaret = useRef(caretSeq);
|
||||
const seenNav = useRef(navSeq);
|
||||
const cancelPulse = useRef<(() => void) | null>(null);
|
||||
const seenFindMatch = useRef<number | null>(null);
|
||||
/** scrollTop set by navigation, whose scroll event isn't the user's. */
|
||||
const scrolledTo = useRef<number | null>(null);
|
||||
@@ -1277,13 +1282,15 @@ function MarkdownPreview({
|
||||
if (root.scrollTop >= saved) restoreRetry.current = null;
|
||||
}, [markup, diagramsDrawn, fontZoom, fontSize, path, sync]);
|
||||
|
||||
// Preview only: go where the hidden editor's caret was sent (Structure, Go to Symbol…).
|
||||
// Preview only: go where the hidden editor's caret was sent (Structure, Go to Symbol, Back/Forward…).
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root || !shown || caretSeq === seenCaret.current) return;
|
||||
// First-open navigation can arrive before the destination’s Markdown is rendered.
|
||||
if (!sync && renderedSource !== text) return;
|
||||
seenCaret.current = caretSeq;
|
||||
const navigated = navSeq !== seenNav.current;
|
||||
seenNav.current = navSeq;
|
||||
if (sync) return;
|
||||
if (find && find.currentMatchIndex >= 0) {
|
||||
const { current } = findPreviewMatches(root, find);
|
||||
@@ -1304,7 +1311,8 @@ function MarkdownPreview({
|
||||
restoreRetry.current = null;
|
||||
}
|
||||
setShownLine(path, caretLine);
|
||||
}, [caretSeq, caretLine, shown, sync, path, find, renderedSource, text]);
|
||||
if (navigated) cancelPulse.current = pulsePreviewLine(root, caretLine, styles.navPulse ?? "");
|
||||
}, [caretSeq, caretLine, navSeq, shown, sync, path, find, renderedSource, text]);
|
||||
|
||||
// Search (⌘F) and selection occurrence highlights in the preview.
|
||||
useLayoutEffect(() => {
|
||||
@@ -1379,6 +1387,8 @@ function MarkdownPreview({
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
return () => {
|
||||
cancelPulse.current?.();
|
||||
cancelPulse.current = null;
|
||||
if (root) {
|
||||
clearPreviewHighlights(root);
|
||||
invalidatePreviewIndex(root);
|
||||
@@ -1470,13 +1480,38 @@ function MarkdownPreview({
|
||||
});
|
||||
};
|
||||
|
||||
const recordPreviewLine = (line: number, userEvent: "select.pointer" | "select.reveal", revealEditor: boolean) => {
|
||||
const view =
|
||||
slot?.live ?? editorsFor(path).find((ed) => ed.tabId === tabId)?.view ?? editorsFor(path)[0]?.view ?? null;
|
||||
if (!view) return false;
|
||||
const targetLine = Math.max(0, Math.min(view.state.doc.lines - 1, Math.floor(line)));
|
||||
const pos = view.state.doc.line(targetLine + 1).from;
|
||||
if (!sync) setShownLine(path, targetLine);
|
||||
view.dispatch({
|
||||
selection: EditorSelection.cursor(pos),
|
||||
...(sync && revealEditor ? { effects: EditorView.scrollIntoView(pos, { y: "center" }) } : {}),
|
||||
userEvent,
|
||||
annotations: previewClickNavigation.of(true),
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
const onClick = (e: MouseEvent) => {
|
||||
const a = (e.target as Element).closest("a");
|
||||
if (e.defaultPrevented || e.button !== 0) return;
|
||||
const root = ref.current;
|
||||
const el = e.target instanceof Element ? e.target : e.target instanceof Node ? e.target.parentElement : null;
|
||||
const a = el?.closest<HTMLAnchorElement>("a[href]") ?? null;
|
||||
if (!a) {
|
||||
const details = (e.target as Element).closest("summary")?.parentElement;
|
||||
if (details instanceof HTMLDetailsElement && ref.current) {
|
||||
toggled.current.set([...ref.current.querySelectorAll("details")].indexOf(details), !details.open);
|
||||
const details = el?.closest("summary")?.parentElement;
|
||||
if (details instanceof HTMLDetailsElement && root) {
|
||||
toggled.current.set([...root.querySelectorAll("details")].indexOf(details), !details.open);
|
||||
return;
|
||||
}
|
||||
if (!root || e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
|
||||
// In Split mode the source editor keeps its own caret: a click in the preview is reading, not navigating.
|
||||
if (sync) return;
|
||||
const clickedLine = previewLineAtClick(root, blocks.current, el, e.clientY, renderedSource.lines);
|
||||
if (clickedLine !== null) recordPreviewLine(clickedLine, "select.pointer", true);
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
@@ -1484,19 +1519,33 @@ function MarkdownPreview({
|
||||
const target = resolveLink(filePath, rawHref);
|
||||
if (!target) return;
|
||||
const request = ++linkRequest.current;
|
||||
const originLine = root ? previewLineAtClick(root, blocks.current, a, e.clientY, renderedSource.lines) : null;
|
||||
const scrollTo = (id: string) => {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
const anchor =
|
||||
root.querySelector(`[id="${CSS.escape(id)}"]`) ??
|
||||
root.querySelector(`[id="${CSS.escape(ANCHOR_PREFIX + slugify(id))}"]`);
|
||||
root.querySelector<HTMLElement>(`[id="${CSS.escape(id)}"]`) ??
|
||||
root.querySelector<HTMLElement>(`[id="${CSS.escape(ANCHOR_PREFIX + slugify(id))}"]`);
|
||||
if (originLine !== null) recordPreviewLine(originLine, "select.pointer", false);
|
||||
anchor?.scrollIntoView();
|
||||
if (!sync) {
|
||||
scrolledTo.current = root.scrollTop;
|
||||
restoreRetry.current = null;
|
||||
}
|
||||
const destLine =
|
||||
(anchor
|
||||
? previewLineAtClick(root, blocks.current, anchor, anchor.getBoundingClientRect().top, renderedSource.lines)
|
||||
: null) ?? headingLine(renderedSource.toString(), id);
|
||||
if (destLine !== null) {
|
||||
recordPreviewLine(destLine, "select.reveal", true);
|
||||
if (!sync) cancelPulse.current = pulsePreviewLine(root, destLine, styles.navPulse ?? "");
|
||||
}
|
||||
};
|
||||
if (target.kind === "external") openExternal(target.url);
|
||||
else if (target.kind === "anchor") scrollTo(target.id);
|
||||
else if (target.path === filePath && target.anchor) scrollTo(target.anchor);
|
||||
else
|
||||
void (async () => {
|
||||
if (originLine !== null) recordPreviewLine(originLine, "select.pointer", false);
|
||||
const docsTarget =
|
||||
isMdxPath(filePath) && rawHref.trim().startsWith("/")
|
||||
? await resolveDocsRootDocLink(filePath, rawHref, allowedRoots)
|
||||
|
||||
@@ -10,6 +10,7 @@ import clsx from "clsx";
|
||||
import guestBundleCode from "virtual:mdx-guest-bundle";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { dispatchForwardedKey } from "@/platform/keymap";
|
||||
import { isOpenable, openExternalUrl } from "@/platform/openUrl";
|
||||
import { dirname, useProject } from "@/platform/project";
|
||||
import {
|
||||
@@ -308,6 +309,12 @@ export function MdxLivePreview({
|
||||
reqId?: unknown;
|
||||
src?: unknown;
|
||||
source?: unknown;
|
||||
key?: unknown;
|
||||
code?: unknown;
|
||||
metaKey?: unknown;
|
||||
ctrlKey?: unknown;
|
||||
altKey?: unknown;
|
||||
shiftKey?: unknown;
|
||||
error?: MdxPreviewError;
|
||||
} | null;
|
||||
if (!d || d.tag !== MDX_FRAME_TAG) return;
|
||||
@@ -381,6 +388,21 @@ export function MdxLivePreview({
|
||||
),
|
||||
() => postToGuest({ op: "mediaResolved", reqId, bytes: null, mime: null }, activePort),
|
||||
);
|
||||
} else if (d.op === "keydown" && typeof d.key === "string" && typeof d.code === "string") {
|
||||
if (frameRef.current) {
|
||||
dispatchForwardedKey(
|
||||
frameRef.current,
|
||||
{
|
||||
key: d.key,
|
||||
code: d.code,
|
||||
metaKey: d.metaKey === true,
|
||||
ctrlKey: d.ctrlKey === true,
|
||||
altKey: d.altKey === true,
|
||||
shiftKey: d.shiftKey === true,
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
} else if (d.op === "renderMermaid" && typeof d.reqId === "number" && typeof d.source === "string") {
|
||||
const reqId = d.reqId;
|
||||
void renderMermaidSvg(d.source).then(
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
* files publishes the text, scroll position, and caret moves per path.
|
||||
* Preview Only follows navigation in the hidden editor.
|
||||
*/
|
||||
import { StateEffect, Text, type EditorState } from "@codemirror/state";
|
||||
import { Annotation, 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 { onEditorEvent, registerEditorContribution, useEditorRegistry } from "@/editor/api";
|
||||
import { MAX_COUNT, findExcluded, findOpen, findScope } from "@/editor/core/cm/find";
|
||||
import { isNavigation } from "@/editor/core/model/navHistory";
|
||||
import { fontZoom, resetConfiguredEditorsFontZoom, stepConfiguredEditorsFontZoom } from "@/editor/core/cm/prefs";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -43,6 +44,10 @@ export interface LiveMarkdown {
|
||||
caretLine: number;
|
||||
/** Bumped with `caretLine`, so going to the same place again still scrolls. */
|
||||
caretSeq: number;
|
||||
/** Bumped on explicit editor navigation (Back/Forward, Go to Line, Structure…) not triggered by a preview click. */
|
||||
navSeq?: number;
|
||||
/** True when the latest `topLine` update came from syncing the editor to a preview click. */
|
||||
scrollFromPreview?: boolean;
|
||||
/** Active Find in File query and match state for the preview. */
|
||||
find?: LiveMarkdownFind | null;
|
||||
/** Single-line text selected in the editor (2..200 chars), for preview occurrence highlighting. */
|
||||
@@ -53,6 +58,9 @@ export interface LiveMarkdown {
|
||||
|
||||
export const useLiveMarkdown = create<Record<string, LiveMarkdown | undefined>>(() => ({}));
|
||||
|
||||
/** Marks editor transactions dispatched from a Markdown preview click so the preview does not bounce-scroll. */
|
||||
export const previewClickNavigation = Annotation.define<boolean>();
|
||||
|
||||
const TEXT_DELAY = 120;
|
||||
const setPreviewSelectionEffect = StateEffect.define<string>();
|
||||
const previewSelectionMark = Decoration.mark({ class: "cm-selectionMatch" });
|
||||
@@ -67,6 +75,7 @@ function publish(path: string, patch: Partial<LiveMarkdown>) {
|
||||
fontZoom: 0,
|
||||
caretLine: 0,
|
||||
caretSeq: 0,
|
||||
navSeq: 0,
|
||||
previewTop: 0,
|
||||
};
|
||||
return { [path]: { ...prev, ...patch } };
|
||||
@@ -255,22 +264,64 @@ function livePlugin(path: string) {
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
private pendingEdit: MarkdownEdit | null = null;
|
||||
private scrolled = false;
|
||||
private suppressNextScroll = false;
|
||||
private suppressedScroll = false;
|
||||
private suppressFrame1 = 0;
|
||||
private suppressFrame2 = 0;
|
||||
private destroyed = false;
|
||||
private previewSel = "";
|
||||
private unsubscribe: () => void;
|
||||
private clearScrollSuppression() {
|
||||
this.suppressNextScroll = false;
|
||||
this.suppressedScroll = false;
|
||||
cancelAnimationFrame(this.suppressFrame1);
|
||||
cancelAnimationFrame(this.suppressFrame2);
|
||||
this.suppressFrame1 = 0;
|
||||
this.suppressFrame2 = 0;
|
||||
}
|
||||
private armScrollSuppression() {
|
||||
this.clearScrollSuppression();
|
||||
this.suppressNextScroll = true;
|
||||
// CodeMirror applies scrollIntoView during its next measure pass and the browser fires
|
||||
// scroll asynchronously after that; two frames clear the flag when no scroll was needed.
|
||||
this.suppressFrame1 = requestAnimationFrame(() => {
|
||||
this.suppressFrame1 = 0;
|
||||
this.suppressFrame2 = requestAnimationFrame(() => {
|
||||
this.suppressFrame2 = 0;
|
||||
this.suppressNextScroll = false;
|
||||
});
|
||||
});
|
||||
}
|
||||
private readonly onUserInput = () => {
|
||||
this.clearScrollSuppression();
|
||||
};
|
||||
private readonly measureSource = {
|
||||
read: sourcePositionOf,
|
||||
write: (position: ReturnType<typeof sourcePositionOf>) => {
|
||||
const scrolled = this.scrolled;
|
||||
const suppressed = this.suppressedScroll;
|
||||
this.scrolled = false;
|
||||
this.suppressedScroll = 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) });
|
||||
publish(path, {
|
||||
...position,
|
||||
scrollFromPreview: suppressed,
|
||||
scrollSeq: (prev?.scrollSeq ?? 0) + Number(scrolled && !suppressed),
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
private readonly onScroll = () => {
|
||||
if (this.suppressNextScroll) {
|
||||
this.suppressedScroll = true;
|
||||
this.suppressNextScroll = false;
|
||||
cancelAnimationFrame(this.suppressFrame1);
|
||||
cancelAnimationFrame(this.suppressFrame2);
|
||||
this.suppressFrame1 = 0;
|
||||
this.suppressFrame2 = 0;
|
||||
}
|
||||
this.scrolled = true;
|
||||
this.view.requestMeasure(this.measureSource);
|
||||
};
|
||||
@@ -287,6 +338,9 @@ function livePlugin(path: string) {
|
||||
editorSelection: editorSelectionOf(view.state),
|
||||
});
|
||||
view.scrollDOM.addEventListener("scroll", this.onScroll, { passive: true });
|
||||
view.dom.addEventListener("wheel", this.onUserInput, { passive: true });
|
||||
view.dom.addEventListener("pointerdown", this.onUserInput, { passive: true });
|
||||
view.dom.addEventListener("keydown", this.onUserInput, { passive: true });
|
||||
this.unsubscribe = useLiveMarkdown.subscribe((s) => {
|
||||
const next = s[path]?.previewSelection ?? "";
|
||||
if (next === this.previewSel) return;
|
||||
@@ -298,9 +352,14 @@ function livePlugin(path: string) {
|
||||
});
|
||||
}
|
||||
|
||||
private publishCaret() {
|
||||
private publishCaret(isNav: boolean) {
|
||||
const prev = useLiveMarkdown.getState()[path];
|
||||
const caretLine = this.view.state.doc.lineAt(this.view.state.selection.main.head).number - 1;
|
||||
publish(path, { caretLine, caretSeq: (useLiveMarkdown.getState()[path]?.caretSeq ?? 0) + 1 });
|
||||
publish(path, {
|
||||
caretLine,
|
||||
caretSeq: (prev?.caretSeq ?? 0) + 1,
|
||||
...(isNav ? { navSeq: (prev?.navSeq ?? 0) + 1, scrollFromPreview: false } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
update(u: ViewUpdate) {
|
||||
@@ -339,8 +398,19 @@ function livePlugin(path: string) {
|
||||
}
|
||||
|
||||
if (u.geometryChanged) u.view.requestMeasure(this.measureSource);
|
||||
const fromPreview =
|
||||
u.transactions.length > 0 && u.transactions.every((tr) => tr.annotation(previewClickNavigation));
|
||||
if (fromPreview) {
|
||||
if (u.transactions.some((tr) => tr.effects.length > 0)) this.armScrollSuppression();
|
||||
} else if (u.selectionSet || u.docChanged) {
|
||||
this.clearScrollSuppression();
|
||||
}
|
||||
if (!u.docChanged) {
|
||||
if (u.selectionSet) this.publishCaret();
|
||||
if (u.selectionSet && !fromPreview) {
|
||||
const isNav = u.transactions.some((tr) => tr.selection && isNavigation(tr));
|
||||
this.publishCaret(isNav);
|
||||
if (isNav) u.view.requestMeasure(this.measureSource);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const pending = this.pendingEdit;
|
||||
@@ -363,8 +433,12 @@ function livePlugin(path: string) {
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
clearTimeout(this.timer);
|
||||
this.clearScrollSuppression();
|
||||
this.unsubscribe();
|
||||
this.view.scrollDOM.removeEventListener("scroll", this.onScroll);
|
||||
this.view.dom.removeEventListener("wheel", this.onUserInput);
|
||||
this.view.dom.removeEventListener("pointerdown", this.onUserInput);
|
||||
this.view.dom.removeEventListener("keydown", this.onUserInput);
|
||||
// Flush the latest edit for a preview that outlives this view.
|
||||
this.publishText();
|
||||
}
|
||||
|
||||
@@ -1029,6 +1029,13 @@ function startSandboxGuest(): void {
|
||||
};
|
||||
const eventType = nativeGetter<Event>(Event.prototype, "type");
|
||||
const eventTarget = nativeGetter<Event>(Event.prototype, "target");
|
||||
const eventDefaultPrevented = nativeGetter<Event>(Event.prototype, "defaultPrevented");
|
||||
const keyEventKey = nativeGetter<KeyboardEvent>(KeyboardEvent.prototype, "key");
|
||||
const keyEventCode = nativeGetter<KeyboardEvent>(KeyboardEvent.prototype, "code");
|
||||
const keyEventMeta = nativeGetter<KeyboardEvent>(KeyboardEvent.prototype, "metaKey");
|
||||
const keyEventCtrl = nativeGetter<KeyboardEvent>(KeyboardEvent.prototype, "ctrlKey");
|
||||
const keyEventAlt = nativeGetter<KeyboardEvent>(KeyboardEvent.prototype, "altKey");
|
||||
const keyEventShift = nativeGetter<KeyboardEvent>(KeyboardEvent.prototype, "shiftKey");
|
||||
const messageData = nativeGetter<MessageEvent>(MessageEvent.prototype, "data");
|
||||
const nativeClosest = Element.prototype.closest;
|
||||
const nativeGetAttribute = Element.prototype.getAttribute;
|
||||
@@ -1078,6 +1085,35 @@ function startSandboxGuest(): void {
|
||||
postToHost({ op: "openLink", href, clickId });
|
||||
});
|
||||
|
||||
// Forward unhandled modifier shortcuts (e.g. ⌥⌘← / ⌥⌘→ Back/Forward) to the host keymap.
|
||||
window.addEventListener("keydown", (ev) => {
|
||||
if (!isTrustedEvent(ev) || eventType?.(ev) !== "keydown" || eventDefaultPrevented?.(ev) === true) return;
|
||||
const metaKey = keyEventMeta?.(ev) === true;
|
||||
const ctrlKey = keyEventCtrl?.(ev) === true;
|
||||
const altKey = keyEventAlt?.(ev) === true;
|
||||
if (!metaKey && !ctrlKey && !altKey) return;
|
||||
const target = eventTarget?.(ev);
|
||||
if (
|
||||
!metaKey &&
|
||||
!ctrlKey &&
|
||||
target instanceof HTMLElement &&
|
||||
(target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)
|
||||
)
|
||||
return;
|
||||
const key = keyEventKey?.(ev);
|
||||
const code = keyEventCode?.(ev);
|
||||
if (typeof key !== "string" || typeof code !== "string") return;
|
||||
postToHost({
|
||||
op: "keydown",
|
||||
key,
|
||||
code,
|
||||
metaKey,
|
||||
ctrlKey,
|
||||
altKey,
|
||||
shiftKey: keyEventShift?.(ev) === true,
|
||||
});
|
||||
});
|
||||
|
||||
const components = createGuestDocsComponents({
|
||||
onLinkSuppressed: (ev) => suppressedClicks.add(ev),
|
||||
resolveImage: (src) =>
|
||||
|
||||
@@ -7,7 +7,9 @@ import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { commands, emitLocalIdeEvent, type ProjectInfo, type Settings, type TrustStatus } from "@/platform/ipc";
|
||||
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import * as openUrlModule from "@/platform/openUrl";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { MDX_FRAME_CSP, MDX_FRAME_HOST_PATH, SANDBOX_FRAME_TAG } from "@/platform/sandboxFrame";
|
||||
import { FRAME_CSP } from "@/features/plugins/views/frame";
|
||||
@@ -628,6 +630,54 @@ describe("Guest-to-host bridge security and frame CSP separation", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// 4b. Forwarded navigation shortcuts over the MessagePort invoke allowed actions (Back/Forward).
|
||||
const prevOs = usePlatform.getState().os;
|
||||
const prevKeymap = useKeymap.getState();
|
||||
const backSpy = vi.fn();
|
||||
const forwardSpy = vi.fn();
|
||||
usePlatform.setState({ os: "macos" });
|
||||
useKeymap.setState({ preset: "intellij-macos", overrides: {}, extensions: {} });
|
||||
const offBack = registerAction({ id: "navigate.back", title: "Back", category: "Navigate", run: backSpy });
|
||||
const offForward = registerAction({
|
||||
id: "navigate.forward",
|
||||
title: "Forward",
|
||||
category: "Navigate",
|
||||
run: forwardSpy,
|
||||
});
|
||||
const offDispatcher = installKeyboardDispatcher(window);
|
||||
try {
|
||||
guestPort.postMessage({
|
||||
tag: MDX_FRAME_TAG,
|
||||
op: "keydown",
|
||||
key: "ArrowLeft",
|
||||
code: "ArrowLeft",
|
||||
metaKey: true,
|
||||
altKey: true,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
});
|
||||
guestPort.postMessage({
|
||||
tag: MDX_FRAME_TAG,
|
||||
op: "keydown",
|
||||
key: "ArrowRight",
|
||||
code: "ArrowRight",
|
||||
metaKey: true,
|
||||
altKey: true,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(backSpy).toHaveBeenCalledTimes(1);
|
||||
expect(forwardSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
} finally {
|
||||
offDispatcher();
|
||||
offBack();
|
||||
offForward();
|
||||
usePlatform.setState({ os: prevOs });
|
||||
useKeymap.setState(prevKeymap);
|
||||
}
|
||||
|
||||
// 5. Reloading the host frame closes the previous MessagePort and rotates the bootstrap nonce.
|
||||
windowPosted.length = 0;
|
||||
act(() => {
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { _addEditor, _removeEditor, editorContributions, type EditorDocContext } from "@/editor/api";
|
||||
import { EditorController, editorController } from "@/editor/core/controller";
|
||||
import { createMemoryBackend } from "@/editor/core/backend";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { provideEditorService } from "@/workbench/contributions";
|
||||
import { registerMarkdownLiveSource, useLiveMarkdown } from "./live";
|
||||
import { MarkdownEditor } from "./MarkdownEditor";
|
||||
import { useMarkdownModes } from "./modes";
|
||||
import { previewElementForLine, previewLineAtClick } from "./previewNavigation";
|
||||
import styles from "./Markdown.module.css";
|
||||
|
||||
const OTHER_MD = "# Other\n\nBody\n\n## Target\n\nDone\n";
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const ipc = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...ipc,
|
||||
commands: { ...ipc.commands, fsReadText: (path: string) => ({ __testReadText: path }) },
|
||||
call: (request: unknown) => {
|
||||
const path = (request as { __testReadText?: string } | null)?.__testReadText;
|
||||
if (path === "/p/other.md") return Promise.resolve(OTHER_MD);
|
||||
return ipc.call(request as never);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const LINE = 10;
|
||||
|
||||
describe("previewLineAtClick & previewElementForLine", () => {
|
||||
it("resolves blocks, multi-line interpolation, list items, table rows, padding gaps, and ignores controls", () => {
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = `<div data-preview-blocks="">
|
||||
<div data-line="0" data-end-line="1"><h1>Title</h1></div>
|
||||
<div data-line="2" data-end-line="12"><pre><code>line 2\n...\nline 11</code></pre><button type="button">Copy</button></div>
|
||||
<div data-line="14" data-end-line="18">
|
||||
<table data-markdown-table="">
|
||||
<thead><tr><th>H</th></tr></thead>
|
||||
<tbody><tr><td>R1</td></tr><tr><td>R2</td></tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div data-line="20" data-end-line="24">
|
||||
<ul>
|
||||
<li data-markdown-line-offset="0">First</li>
|
||||
<li data-markdown-line-offset="2">Second</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div data-line="26" data-end-line="29"><details><summary>Toggle</summary><p>Inside</p></details></div>
|
||||
</div>`;
|
||||
|
||||
const mockRect = (el: Element, top: number, height: number) =>
|
||||
vi.spyOn(el, "getBoundingClientRect").mockReturnValue({
|
||||
top,
|
||||
bottom: top + height,
|
||||
left: 0,
|
||||
right: 400,
|
||||
width: 400,
|
||||
height,
|
||||
x: 0,
|
||||
y: top,
|
||||
toJSON: () => {},
|
||||
});
|
||||
|
||||
mockRect(root, 0, 500);
|
||||
const codeBlock = root.querySelector('[data-line="2"]')!;
|
||||
mockRect(codeBlock, 20, 100);
|
||||
const blocks = [
|
||||
{ line: 0, endLine: 1, top: 0 },
|
||||
{ line: 2, endLine: 12, top: 20 },
|
||||
{ line: 14, endLine: 18, top: 140 },
|
||||
{ line: 20, endLine: 24, top: 200 },
|
||||
{ line: 26, endLine: 29, top: 260 },
|
||||
];
|
||||
|
||||
expect(previewLineAtClick(root, blocks, root.querySelector("h1"), 5, 30)).toBe(0);
|
||||
// Midpoint of a 10-line code block (lines 2..12) at clientY = 70 -> line 7.
|
||||
expect(previewLineAtClick(root, blocks, root.querySelector("code"), 70, 30)).toBe(7);
|
||||
// Button inside code block is ignored.
|
||||
expect(previewLineAtClick(root, blocks, root.querySelector("button"), 25, 30)).toBeNull();
|
||||
// Summary toggle is ignored, while content inside <details> still resolves.
|
||||
expect(previewLineAtClick(root, blocks, root.querySelector("summary"), 265, 30)).toBeNull();
|
||||
expect(previewLineAtClick(root, blocks, root.querySelector("details p"), 265, 30)).toBe(26);
|
||||
// Table rows map header -> 14, row 1 -> 16, row 2 -> 17.
|
||||
const rows = root.querySelectorAll("tr");
|
||||
expect(previewLineAtClick(root, blocks, rows[0]!.firstElementChild, 145, 30)).toBe(14);
|
||||
expect(previewLineAtClick(root, blocks, rows[1]!.firstElementChild, 160, 30)).toBe(16);
|
||||
expect(previewLineAtClick(root, blocks, rows[2]!.firstElementChild, 175, 30)).toBe(17);
|
||||
// List items map to exact data-markdown-line-offset lines.
|
||||
const items = root.querySelectorAll("li");
|
||||
mockRect(items[0]!, 200, 10);
|
||||
mockRect(items[1]!, 220, 10);
|
||||
expect(previewLineAtClick(root, blocks, items[0]!, 205, 30)).toBe(20);
|
||||
expect(previewLineAtClick(root, blocks, items[1]!, 225, 30)).toBe(22);
|
||||
// Click in blank gap falls back to previewLineAtOffset.
|
||||
expect(previewLineAtClick(root, blocks, root, 150, 30)).toBe(14);
|
||||
|
||||
// previewElementForLine picks the most specific element (tr, li, or block).
|
||||
expect(previewElementForLine(root, 0)?.dataset.line).toBe("0");
|
||||
expect(previewElementForLine(root, 16)).toBe(rows[1]);
|
||||
expect(previewElementForLine(root, 22)).toBe(items[1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Markdown navigation history with mouse click and Option+Command+Left/Right", () => {
|
||||
const disposers: Array<() => void> = [];
|
||||
const offsetTop = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "offsetTop")!;
|
||||
let ctrl: EditorController;
|
||||
|
||||
const mdLines = [
|
||||
"# Intro",
|
||||
"",
|
||||
"[Jump to Deep](#deep)",
|
||||
"",
|
||||
"[Open Other](other.md#target)",
|
||||
"",
|
||||
...Array.from({ length: 14 }, (_, i) => `Intro body ${i}`),
|
||||
"",
|
||||
"## Middle",
|
||||
"",
|
||||
...Array.from({ length: 14 }, (_, i) => `Middle body ${i}`),
|
||||
"",
|
||||
"## Deep",
|
||||
"",
|
||||
...Array.from({ length: 10 }, (_, i) => `Deep body ${i}`),
|
||||
];
|
||||
const readmeText = mdLines.join("\n");
|
||||
const middleLine = mdLines.indexOf("## Middle");
|
||||
const deepLine = mdLines.indexOf("## Deep");
|
||||
const otherText = OTHER_MD;
|
||||
|
||||
const pressOptionCmd = (
|
||||
arrow: "ArrowLeft" | "ArrowRight",
|
||||
target: Document | Element | Node | Window = document.activeElement ?? window,
|
||||
) => {
|
||||
fireEvent.keyDown(target, {
|
||||
key: arrow,
|
||||
code: arrow,
|
||||
metaKey: true,
|
||||
altKey: true,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
};
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(HTMLElement.prototype, "offsetTop", {
|
||||
configurable: true,
|
||||
get(this: HTMLElement) {
|
||||
return Number(this.dataset.line ?? 0) * LINE;
|
||||
},
|
||||
});
|
||||
});
|
||||
afterAll(() => Object.defineProperty(HTMLElement.prototype, "offsetTop", offsetTop));
|
||||
|
||||
beforeEach(() => {
|
||||
usePlatform.setState({ os: "macos" });
|
||||
useKeymap.setState({ preset: "intellij-macos", overrides: {}, extensions: {} });
|
||||
disposers.push(registerMarkdownLiveSource());
|
||||
ctrl = new EditorController(
|
||||
createMemoryBackend({
|
||||
"/p/README.md": readmeText,
|
||||
"/p/other.md": otherText,
|
||||
}),
|
||||
);
|
||||
ctrl.start();
|
||||
vi.spyOn(editorController(), "slotFor").mockImplementation((id) => ctrl.slotFor(id));
|
||||
disposers.push(() => ctrl.stop());
|
||||
provideEditorService({
|
||||
openFile: (path, opts) => ctrl.openFile(path, opts),
|
||||
openInput: (input, opts) => ctrl.openInput(input, opts),
|
||||
activePath: () => ctrl.activeSlot?.model.path ?? null,
|
||||
activeCursor: () => null,
|
||||
focus: () => ctrl.focus(),
|
||||
closePath: (path) => ctrl.closePath(path),
|
||||
saveAll: () => ctrl.manager.saveAll("explicit"),
|
||||
openTabs: () => [],
|
||||
});
|
||||
disposers.push(
|
||||
registerActions([
|
||||
{ id: "navigate.back", title: "Back", category: "Navigate", run: () => ctrl.back() },
|
||||
{ id: "navigate.forward", title: "Forward", category: "Navigate", run: () => ctrl.forward() },
|
||||
]),
|
||||
);
|
||||
disposers.push(installKeyboardDispatcher(window));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
for (const dispose of disposers.splice(0).reverse()) dispose();
|
||||
useLiveMarkdown.setState({}, true);
|
||||
useMarkdownModes.setState({ byTab: {}, fallback: "split" });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function mountMarkdownTab(path: string, mode: "preview" | "split" | "editor") {
|
||||
await ctrl.openFile(path, { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const editorHost = document.createElement("div");
|
||||
if (mode === "preview") editorHost.style.display = "none";
|
||||
slot.mount(editorHost);
|
||||
act(() => useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, [slot.tabId]: mode } })));
|
||||
|
||||
const rendered = render(
|
||||
<div data-pane-id="pane1">
|
||||
<MarkdownEditor path={path} tabId={slot.tabId}>
|
||||
<div
|
||||
ref={(el) => {
|
||||
if (el && !el.contains(editorHost)) el.appendChild(editorHost);
|
||||
}}
|
||||
/>
|
||||
</MarkdownEditor>
|
||||
</div>,
|
||||
);
|
||||
const preview = mode !== "editor" ? screen.getByRole("document", { name: "Markdown preview" }) : null;
|
||||
if (preview) {
|
||||
Object.defineProperty(preview, "scrollHeight", { configurable: true, value: mdLines.length * LINE });
|
||||
}
|
||||
return { slot, preview, ...rendered };
|
||||
}
|
||||
|
||||
it("remembers mouse-clicked positions in Preview Only without yanking scroll and supports Option+Command+Left/Right", async () => {
|
||||
const { slot, preview } = await mountMarkdownTab("/p/README.md", "preview");
|
||||
expect(preview).not.toBeNull();
|
||||
preview!.focus();
|
||||
|
||||
// Scroll to line 15, then click on "## Middle" (middleLine) in the viewport.
|
||||
preview!.scrollTop = 15 * LINE;
|
||||
fireEvent.scroll(preview!);
|
||||
const middleHeading = within(preview!).getByRole("heading", { name: "Middle" });
|
||||
fireEvent.click(middleHeading, { button: 0, clientY: 50 });
|
||||
|
||||
expect(slot.caret().line).toBe(middleLine);
|
||||
// Clicking in Preview Only must not yank the scroll offset.
|
||||
expect(preview!.scrollTop).toBe(15 * LINE);
|
||||
|
||||
// Scroll to line 30, then click on "## Deep" (deepLine).
|
||||
preview!.scrollTop = 30 * LINE;
|
||||
fireEvent.scroll(preview!);
|
||||
const deepHeading = within(preview!).getByRole("heading", { name: "Deep" });
|
||||
fireEvent.click(deepHeading, { button: 0, clientY: 60 });
|
||||
|
||||
expect(slot.caret().line).toBe(deepLine);
|
||||
expect(preview!.scrollTop).toBe(30 * LINE);
|
||||
|
||||
// A slight trackpad scroll nudge after clicking must not corrupt the remembered entry.
|
||||
preview!.scrollTop = 30 * LINE + 2;
|
||||
fireEvent.scroll(preview!);
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
|
||||
// Option+Command+Left -> navigates back to "## Middle", scrolls preview, and pulses target block.
|
||||
await act(async () => {
|
||||
pressOptionCmd("ArrowLeft", preview!);
|
||||
});
|
||||
await waitFor(() => expect(slot.caret().line).toBe(middleLine));
|
||||
expect(preview!.scrollTop).toBe(middleLine * LINE);
|
||||
expect(middleHeading.closest("[data-line]")?.classList.contains(styles.navPulse!)).toBe(true);
|
||||
|
||||
// Option+Command+Left again -> navigates back to line 0 ("# Intro").
|
||||
await act(async () => {
|
||||
pressOptionCmd("ArrowLeft", preview!);
|
||||
});
|
||||
await waitFor(() => expect(slot.caret().line).toBe(0));
|
||||
expect(preview!.scrollTop).toBe(0);
|
||||
|
||||
// Option+Command+Right -> navigates forward to "## Middle", then "## Deep".
|
||||
await act(async () => {
|
||||
pressOptionCmd("ArrowRight", preview!);
|
||||
});
|
||||
await waitFor(() => expect(slot.caret().line).toBe(middleLine));
|
||||
expect(preview!.scrollTop).toBe(middleLine * LINE);
|
||||
|
||||
await act(async () => {
|
||||
pressOptionCmd("ArrowRight", preview!);
|
||||
});
|
||||
await waitFor(() => expect(slot.caret().line).toBe(deepLine));
|
||||
expect(preview!.scrollTop).toBe(deepLine * LINE);
|
||||
});
|
||||
|
||||
it("records origin and destination when clicking an internal #anchor link and supports Back/Forward", async () => {
|
||||
const { slot, preview } = await mountMarkdownTab("/p/README.md", "preview");
|
||||
preview!.focus();
|
||||
|
||||
const anchorHeading = within(preview!).getByRole("heading", { name: "Deep" });
|
||||
const scrollIntoView = vi.fn(() => {
|
||||
preview!.scrollTop = deepLine * LINE;
|
||||
});
|
||||
anchorHeading.scrollIntoView = scrollIntoView;
|
||||
|
||||
fireEvent.click(within(preview!).getByText("Jump to Deep"), { button: 0 });
|
||||
expect(scrollIntoView).toHaveBeenCalledTimes(1);
|
||||
expect(ctrl.nav.entries.map((e) => e.line)).toEqual([2, deepLine]);
|
||||
expect(slot.caret().line).toBe(deepLine);
|
||||
|
||||
// Option+Command+Left returns to the TOC link line (line 2), not line 0.
|
||||
await act(async () => {
|
||||
pressOptionCmd("ArrowLeft", preview!);
|
||||
});
|
||||
await waitFor(() => expect(slot.caret().line).toBe(2));
|
||||
expect(preview!.scrollTop).toBe(2 * LINE);
|
||||
|
||||
// Option+Command+Right returns forward to "## Deep".
|
||||
await act(async () => {
|
||||
pressOptionCmd("ArrowRight", preview!);
|
||||
});
|
||||
await waitFor(() => expect(slot.caret().line).toBe(deepLine));
|
||||
});
|
||||
|
||||
it("records the clicked link line before opening another file so Back returns to that link", async () => {
|
||||
const { preview } = await mountMarkdownTab("/p/README.md", "preview");
|
||||
preview!.focus();
|
||||
|
||||
fireEvent.click(within(preview!).getByText("Open Other"), { button: 0 });
|
||||
await waitFor(() => expect(ctrl.activeSlot?.model.path).toBe("/p/other.md"));
|
||||
expect(ctrl.activeSlot?.caret().line).toBe(4);
|
||||
|
||||
await act(async () => {
|
||||
pressOptionCmd("ArrowLeft", document.body);
|
||||
});
|
||||
await waitFor(() => expect(ctrl.activeSlot?.model.path).toBe("/p/README.md"));
|
||||
expect(ctrl.activeSlot?.caret().line).toBe(4);
|
||||
});
|
||||
|
||||
it("in Split mode, a plain click in the preview leaves the source caret and scroll alone", async () => {
|
||||
const { slot, preview } = await mountMarkdownTab("/p/README.md", "split");
|
||||
expect(preview).not.toBeNull();
|
||||
const before = slot.caret().line;
|
||||
const scrollSpy = vi.spyOn(EditorView, "scrollIntoView");
|
||||
preview!.scrollTop = 180;
|
||||
|
||||
fireEvent.click(within(preview!).getByRole("heading", { name: "Deep" }), { button: 0 });
|
||||
expect(slot.caret().line).toBe(before);
|
||||
expect(scrollSpy).not.toHaveBeenCalled();
|
||||
expect(preview!.scrollTop).toBe(180);
|
||||
});
|
||||
|
||||
it("in Editor Only mode, mouse-clicking positions records history and supports Option+Command+Left/Right", async () => {
|
||||
const { slot } = await mountMarkdownTab("/p/README.md", "editor");
|
||||
const view = slot.view!;
|
||||
|
||||
act(() => {
|
||||
view.dispatch({
|
||||
selection: EditorSelection.cursor(view.state.doc.line(middleLine + 1).from),
|
||||
userEvent: "select.pointer",
|
||||
});
|
||||
});
|
||||
act(() => {
|
||||
view.dispatch({
|
||||
selection: EditorSelection.cursor(view.state.doc.line(deepLine + 1).from),
|
||||
userEvent: "select.pointer",
|
||||
});
|
||||
});
|
||||
expect(slot.caret().line).toBe(deepLine);
|
||||
|
||||
await act(async () => {
|
||||
pressOptionCmd("ArrowLeft", view.contentDOM);
|
||||
});
|
||||
await waitFor(() => expect(slot.caret().line).toBe(middleLine));
|
||||
|
||||
await act(async () => {
|
||||
pressOptionCmd("ArrowRight", view.contentDOM);
|
||||
});
|
||||
await waitFor(() => expect(slot.caret().line).toBe(deepLine));
|
||||
});
|
||||
|
||||
it("falls back to editorsFor when slotFor is absent (standalone preview harnesses)", () => {
|
||||
const ctx: EditorDocContext = {
|
||||
doc: 99,
|
||||
path: "/p/standalone.md",
|
||||
language: "markdown",
|
||||
uiMode: null,
|
||||
readOnly: false,
|
||||
};
|
||||
const live = editorContributions().find((c) => c.id === "viewers.markdownLive")!;
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc: "# Top\n\nMiddle\n\n## End", extensions: [live.extensions(ctx)] }),
|
||||
});
|
||||
const handle = { view, ctx, tabId: "standalone-tab" };
|
||||
_addEditor(handle);
|
||||
vi.spyOn(editorController(), "slotFor").mockReturnValue(null);
|
||||
act(() => useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, "standalone-tab": "preview" } })));
|
||||
try {
|
||||
render(
|
||||
<MarkdownEditor path={ctx.path} tabId="standalone-tab">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("heading", { name: "End" }), { button: 0 });
|
||||
expect(view.state.doc.lineAt(view.state.selection.main.head).number - 1).toBe(4);
|
||||
} finally {
|
||||
_removeEditor(handle);
|
||||
view.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Click-to-line mapping and target highlight pulse for the rendered Markdown preview.
|
||||
*/
|
||||
import { reducedMotion } from "@/platform/motion";
|
||||
import { previewLineAtOffset } from "./render";
|
||||
|
||||
export interface PreviewBlockGeometry {
|
||||
line: number;
|
||||
endLine?: number;
|
||||
top: number;
|
||||
}
|
||||
|
||||
const IGNORED_CLICK_SELECTOR = 'button, summary, [data-mermaid-tools], [data-dragging="true"]';
|
||||
|
||||
/**
|
||||
* Resolves a pointer click inside the Markdown preview to a 0-based source line,
|
||||
* or `null` when the click hit an interactive control that should not record history.
|
||||
*/
|
||||
export function previewLineAtClick(
|
||||
root: HTMLElement,
|
||||
blocks: ReadonlyArray<PreviewBlockGeometry>,
|
||||
target: EventTarget | null,
|
||||
clientY: number,
|
||||
lineCount: number,
|
||||
): number | null {
|
||||
if (lineCount <= 0) return null;
|
||||
const maxLine = lineCount - 1;
|
||||
const clamp = (line: number) => Math.max(0, Math.min(maxLine, Math.floor(line)));
|
||||
|
||||
const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;
|
||||
if (element?.closest(IGNORED_CLICK_SELECTOR)) return null;
|
||||
|
||||
const block = element?.closest<HTMLElement>("[data-line][data-end-line]");
|
||||
if (block && root.contains(block)) {
|
||||
const start = Number(block.dataset.line);
|
||||
const end = Number(block.dataset.endLine);
|
||||
if (Number.isInteger(start) && Number.isInteger(end) && start >= 0) {
|
||||
// GFM table row: header is `start`, body row `i` (1-based in table.rows) is `start + i + 1`.
|
||||
const tr = element?.closest<HTMLTableRowElement>("tr");
|
||||
const table = tr?.closest<HTMLTableElement>("table[data-markdown-table]");
|
||||
if (tr && table && block.contains(table) && table.rows.length + 1 === end - start) {
|
||||
const index = tr.rowIndex;
|
||||
if (index >= 0) return clamp(index === 0 ? start : start + index + 1);
|
||||
}
|
||||
|
||||
// List item with exact source line offset relative to the enclosing list block.
|
||||
const li = element?.closest<HTMLElement>("li[data-markdown-line-offset]");
|
||||
if (li && block.contains(li)) {
|
||||
const offset = Number(li.dataset.markdownLineOffset);
|
||||
if (Number.isInteger(offset) && offset >= 0 && start + offset < end) {
|
||||
return clamp(start + offset);
|
||||
}
|
||||
}
|
||||
|
||||
return clamp(interpolateLine(block, start, Math.max(start + 1, end), clientY));
|
||||
}
|
||||
}
|
||||
|
||||
const rootRect = root.getBoundingClientRect();
|
||||
const offset = clientY - rootRect.top + root.scrollTop;
|
||||
return clamp(previewLineAtOffset(blocks, Math.max(0, offset)));
|
||||
}
|
||||
|
||||
function interpolateLine(el: HTMLElement, start: number, end: number, clientY: number): number {
|
||||
const span = end - start;
|
||||
if (span <= 1) return start;
|
||||
const rect = el.getBoundingClientRect();
|
||||
if (rect.height <= 0) return start;
|
||||
const fraction = Math.max(0, Math.min(1, (clientY - rect.top) / rect.height));
|
||||
return Math.min(end - 1, start + Math.floor(fraction * span));
|
||||
}
|
||||
|
||||
/** Finds the most specific rendered DOM element in `root` representing 0-based `line`. */
|
||||
export function previewElementForLine(root: HTMLElement, line: number): HTMLElement | null {
|
||||
const blocks = [...root.querySelectorAll<HTMLElement>(":scope > [data-preview-blocks] > [data-line]")];
|
||||
if (!blocks.length) return null;
|
||||
|
||||
let chosen: HTMLElement | null = null;
|
||||
for (const block of blocks) {
|
||||
const start = Number(block.dataset.line);
|
||||
const end = Number(block.dataset.endLine ?? start + 1);
|
||||
if (!Number.isInteger(start)) continue;
|
||||
if (start <= line) chosen = block;
|
||||
if (start <= line && line < end) {
|
||||
chosen = block;
|
||||
break;
|
||||
}
|
||||
if (start > line) break;
|
||||
}
|
||||
if (!chosen) return blocks[0] ?? null;
|
||||
|
||||
const start = Number(chosen.dataset.line);
|
||||
const end = Number(chosen.dataset.endLine ?? start + 1);
|
||||
|
||||
const table = chosen.firstElementChild;
|
||||
if (
|
||||
table instanceof HTMLTableElement &&
|
||||
table.hasAttribute("data-markdown-table") &&
|
||||
table.rows.length + 1 === end - start
|
||||
) {
|
||||
const rowIndex = line <= start + 1 ? 0 : Math.min(table.rows.length - 1, line - start - 1);
|
||||
return table.rows[rowIndex] ?? chosen;
|
||||
}
|
||||
|
||||
let matchedItem: HTMLElement | null = null;
|
||||
for (const li of chosen.querySelectorAll<HTMLElement>("li[data-markdown-line-offset]")) {
|
||||
const offset = Number(li.dataset.markdownLineOffset);
|
||||
if (!Number.isInteger(offset)) continue;
|
||||
const itemLine = start + offset;
|
||||
if (itemLine <= line) matchedItem = li;
|
||||
else break;
|
||||
}
|
||||
return matchedItem ?? chosen;
|
||||
}
|
||||
|
||||
const activePulses = new WeakMap<HTMLElement, () => void>();
|
||||
|
||||
/** Plays a brief highlight pulse on the preview element at `line` (no-op under reduced motion). */
|
||||
export function pulsePreviewLine(root: HTMLElement, line: number, className: string): () => void {
|
||||
activePulses.get(root)?.();
|
||||
if (!className || reducedMotion()) return () => {};
|
||||
const target = previewElementForLine(root, line);
|
||||
if (!target) return () => {};
|
||||
|
||||
target.classList.remove(className);
|
||||
// Restart the CSS animation when navigating repeatedly to the same block.
|
||||
void target.offsetWidth;
|
||||
target.classList.add(className);
|
||||
|
||||
let disposed = false;
|
||||
const cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
clearTimeout(timer);
|
||||
target.removeEventListener("animationend", cleanup);
|
||||
target.classList.remove(className);
|
||||
if (activePulses.get(root) === cleanup) activePulses.delete(root);
|
||||
};
|
||||
const timer = setTimeout(cleanup, 1100);
|
||||
target.addEventListener("animationend", cleanup, { once: true });
|
||||
activePulses.set(root, cleanup);
|
||||
return cleanup;
|
||||
}
|
||||
@@ -69,6 +69,21 @@ it("retargets one animation, settles exactly, and yields to manual scrolling", (
|
||||
expect(root.scrollTop).toBe(350);
|
||||
follow.resume();
|
||||
expect(root.scrollTop).toBe(150);
|
||||
|
||||
// Editor scrolls caused by a preview click do not bounce back to the preview.
|
||||
useLiveMarkdown.setState((s) => ({
|
||||
doc: { ...s.doc!, topLine: 45, scrollFromPreview: true },
|
||||
}));
|
||||
expect(callback).toBeUndefined();
|
||||
expect(root.scrollTop).toBe(150);
|
||||
|
||||
// Explicit editor navigation (Back/Forward) realigns the preview even if topLine did not change.
|
||||
useLiveMarkdown.setState((s) => ({
|
||||
doc: { ...s.doc!, topLine: 45, scrollFromPreview: false, navSeq: (s.doc?.navSeq ?? 0) + 1 },
|
||||
}));
|
||||
expect(callback).toBeDefined();
|
||||
for (let i = 0; i < 15; i++) tick(40);
|
||||
expect(root.scrollTop).toBe(450);
|
||||
} finally {
|
||||
follow.dispose();
|
||||
}
|
||||
|
||||
@@ -45,7 +45,12 @@ export function followMarkdownSource(path: string, root: HTMLElement, offsetForL
|
||||
if (a?.caretSeq !== b?.caretSeq) navigated = true;
|
||||
return;
|
||||
}
|
||||
if (!a || (a.topLine === b?.topLine && a.scrollSeq === b?.scrollSeq && a.sourceAtEnd === b?.sourceAtEnd)) return;
|
||||
if (!a) return;
|
||||
const navChanged = (a.navSeq ?? 0) !== (b?.navSeq ?? 0);
|
||||
const scrollChanged =
|
||||
!a.scrollFromPreview &&
|
||||
(a.topLine !== b?.topLine || a.scrollSeq !== b?.scrollSeq || a.sourceAtEnd !== b?.sourceAtEnd);
|
||||
if (!navChanged && !scrollChanged) return;
|
||||
if (reducedMotion()) return align();
|
||||
if (frame) return;
|
||||
applied = position = root.scrollTop;
|
||||
|
||||
Reference in new issue
Заблокувати користувача