дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
fix(markdown): keep reading position when toggling Structure (#6483)
Showing or hiding a docked Structure pane changes the Markdown editor's width. CodeMirror could keep an old pixel offset within a wrapped line, and the preview measured its position after some blocks had already reflowed, so both jumped. The source view now anchors the first visible character across a side-dock change and restores it in the resize frame; the preview remembers its line and offset on scroll, pauses following the source while blocks reflow, and restores the position once the width settles. A navigation made while paused is applied on resume. Works in all three Markdown modes. Co-authored-by: faysou <[email protected]>
Цей коміт міститься в:
1 джерело
a52a639b8e
коміт
f4be752dda
4 files changed
+323
-22
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function choosePreviewLayout(page: Page, layout: "Side by side" | "Stacked") {
|
||||
await page.keyboard.press("Meta+,");
|
||||
@@ -213,3 +213,173 @@ test("applies the Markdown sticky-lines setting to an open editor", async ({ wor
|
||||
await checkbox.check();
|
||||
await settings.getByRole("button", { name: "OK", exact: true }).click();
|
||||
});
|
||||
|
||||
async function openSections(page: Page, mode: "Preview Only" | "Editor Only" | "Editor and Preview") {
|
||||
const target = "Section 30";
|
||||
await page.setViewportSize({ width: 1100, height: 760 });
|
||||
const line = await page.evaluate(async (title) => {
|
||||
const backendPath = "/src/editor/core/backend.ts";
|
||||
const servicePath = "/src/workbench/contributions.ts";
|
||||
const { docBackend } = await import(backendPath);
|
||||
const { editorService } = await import(servicePath);
|
||||
const path = "/dev/acme-api/sections.md";
|
||||
const paragraph = "Wrapping changes the height of this paragraph when the docked pane closes. ".repeat(11);
|
||||
const sections = Array.from({ length: 65 }, (_, i) => `## Section ${i}\n\n${paragraph}\n\n`);
|
||||
const source = sections.join("");
|
||||
docBackend().files.set(path, source);
|
||||
await editorService().openFile(path);
|
||||
return source.split("\n").indexOf(`## ${title}`);
|
||||
}, target);
|
||||
await page.getByRole("button", { name: mode, exact: true }).click();
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ name, line }) => {
|
||||
const pos = { line, col: 3 };
|
||||
window.__ipc.handlers.doc_outline = () => [
|
||||
{
|
||||
name,
|
||||
kind: "key",
|
||||
range: { start: { line, col: 0 }, end: { line: line + 2, col: 0 } },
|
||||
selection_range: { start: pos, end: pos },
|
||||
children: [],
|
||||
},
|
||||
];
|
||||
const path = "/src/workbench/toolwindows/store.ts";
|
||||
const { moveToolWindow, setToolWindowSize, showToolWindow } = await import(path);
|
||||
moveToolWindow("structure", "right");
|
||||
setToolWindowSize("right", 330);
|
||||
showToolWindow("structure", true);
|
||||
},
|
||||
{ name: target, line },
|
||||
);
|
||||
const panel = page.getByRole("region", { name: "Structure", exact: true });
|
||||
const stripe = page.locator('[data-stripe-button="structure"]');
|
||||
return { target, line, panel, stripe };
|
||||
}
|
||||
|
||||
const position = (heading: Locator) =>
|
||||
heading.evaluate((el) => {
|
||||
const preview = el.closest('[aria-label="Markdown preview"]')!;
|
||||
return { y: el.getBoundingClientRect().top - preview.getBoundingClientRect().top, width: preview.clientWidth };
|
||||
});
|
||||
|
||||
const settled = (preview: Locator) =>
|
||||
preview.evaluate((el) => {
|
||||
const style = getComputedStyle(el);
|
||||
const width = el.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
|
||||
return Math.abs(width - parseFloat(style.getPropertyValue("--markdown-block-width")));
|
||||
});
|
||||
|
||||
test("keeps the Markdown reading position when toggling the right Structure stripe", async ({ workbench: page }) => {
|
||||
const { target, panel, stripe } = await openSections(page, "Preview Only");
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
const heading = preview.getByRole("heading", { name: target, exact: true });
|
||||
await expect.poll(() => settled(preview)).toBeLessThanOrEqual(1);
|
||||
const starting = await position(heading);
|
||||
await panel.getByRole("treeitem", { name: target, exact: true }).click();
|
||||
await expect.poll(async () => (await position(heading)).y).toBeGreaterThanOrEqual(-1);
|
||||
await expect.poll(async () => (await position(heading)).y).toBeLessThan(45);
|
||||
const before = await position(heading);
|
||||
expect(starting.y).toBeGreaterThan(before.y + 1000);
|
||||
await stripe.click();
|
||||
await expect(panel).toBeHidden();
|
||||
await expect.poll(async () => (await position(heading)).width).toBeGreaterThan(before.width + 200);
|
||||
await expect.poll(() => settled(preview)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs((await position(heading)).y - before.y)).toBeLessThanOrEqual(2);
|
||||
|
||||
const readingHeading = preview.getByRole("heading", { name: "Section 35", exact: true });
|
||||
await readingHeading.evaluate((el) => {
|
||||
const preview = el.closest('[aria-label="Markdown preview"]')!;
|
||||
preview.scrollTop += el.getBoundingClientRect().top - preview.getBoundingClientRect().top + 12;
|
||||
});
|
||||
await expect.poll(async () => Math.abs((await position(readingHeading)).y + 12)).toBeLessThanOrEqual(1);
|
||||
await expect.poll(async () => (await position(heading)).y).toBeLessThan(-500);
|
||||
const reading = await position(readingHeading);
|
||||
await stripe.click();
|
||||
await expect(panel).toBeVisible();
|
||||
await expect.poll(async () => (await position(readingHeading)).width).toBeLessThan(reading.width - 200);
|
||||
await expect.poll(() => settled(preview)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs((await position(readingHeading)).y - reading.y)).toBeLessThanOrEqual(2);
|
||||
});
|
||||
|
||||
for (const mode of ["Editor Only", "Editor and Preview"] as const) {
|
||||
test(`keeps wrapped Markdown in place when toggling Structure in ${mode}`, async ({ workbench: page }) => {
|
||||
const { target, line, panel, stripe } = await openSections(page, mode);
|
||||
const source = page.locator(".cm-content:visible");
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
const previewHeading = preview.getByRole("heading", { name: "Section 49", exact: true });
|
||||
const readSource = (pos: number | null = null) =>
|
||||
source.evaluate((el, pos) => {
|
||||
const view = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view;
|
||||
const viewport = view.scrollDOM.getBoundingClientRect();
|
||||
const marker =
|
||||
pos ?? view.posAtCoords({ x: view.contentDOM.getBoundingClientRect().left + 1, y: viewport.top + 2 });
|
||||
const coords = marker !== null ? view.coordsAtPos(marker) : null;
|
||||
const markerLine = marker !== null ? view.state.doc.lineAt(marker) : null;
|
||||
const caret = view.state.selection.main.head;
|
||||
return {
|
||||
marker,
|
||||
caret: view.state.doc.lineAt(caret).number,
|
||||
markerLine: markerLine?.number,
|
||||
markerColumn: markerLine && marker !== null ? marker - markerLine.from : 0,
|
||||
y: coords ? coords.top - viewport.top : null,
|
||||
width: view.scrollDOM.clientWidth,
|
||||
};
|
||||
}, pos);
|
||||
const browseSource = (section: number, column: number) =>
|
||||
source.evaluate(
|
||||
(el, { section, column }) => {
|
||||
const view = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view;
|
||||
const line = view.state.doc.line(section * 4 + (column ? 3 : 1));
|
||||
view.dispatch({
|
||||
effects: (view.constructor as typeof EditorView).scrollIntoView(line.from + column, {
|
||||
y: "start",
|
||||
yMargin: 0,
|
||||
}),
|
||||
});
|
||||
},
|
||||
{ section, column },
|
||||
);
|
||||
await expect(source).toHaveClass(/cm-lineWrapping/);
|
||||
await panel.getByRole("treeitem", { name: target, exact: true }).click();
|
||||
await expect.poll(async () => (await readSource()).caret).toBe(line + 1);
|
||||
await browseSource(35, 500);
|
||||
await expect.poll(async () => (await readSource()).markerLine).toBe(35 * 4 + 3);
|
||||
if (mode === "Editor and Preview") {
|
||||
await expect.poll(() => settled(preview)).toBeLessThanOrEqual(1);
|
||||
await expect.poll(async () => (await position(previewHeading)).y).toBeGreaterThan(800);
|
||||
await previewHeading.evaluate((el) => {
|
||||
const preview = el.closest('[aria-label="Markdown preview"]')!;
|
||||
preview.scrollTop += el.getBoundingClientRect().top - preview.getBoundingClientRect().top + 12;
|
||||
});
|
||||
await expect.poll(async () => Math.abs((await position(previewHeading)).y + 12)).toBeLessThanOrEqual(1);
|
||||
}
|
||||
const before = await readSource();
|
||||
const reading = mode === "Editor and Preview" ? await position(previewHeading) : null;
|
||||
expect(before.markerColumn).toBeGreaterThan(200);
|
||||
expect(before.marker).not.toBeNull();
|
||||
expect(before.y).not.toBeNull();
|
||||
for (const open of [false, true, false, true]) {
|
||||
await stripe.click();
|
||||
await expect(stripe).toHaveAttribute("aria-pressed", String(open));
|
||||
if (!open) await expect.poll(async () => (await readSource()).width).toBeGreaterThan(before.width + 100);
|
||||
else await expect.poll(async () => (await readSource()).width).toBe(before.width);
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const after = await readSource(before.marker);
|
||||
return after.y === null ? Infinity : Math.abs(after.y - before.y!);
|
||||
})
|
||||
.toBeLessThanOrEqual(2);
|
||||
expect((await readSource()).caret).toBe(line + 1);
|
||||
if (reading) {
|
||||
await expect.poll(() => settled(preview)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs((await position(previewHeading)).y - reading.y)).toBeLessThanOrEqual(2);
|
||||
}
|
||||
}
|
||||
if (mode === "Editor and Preview") {
|
||||
const followerHeading = preview.getByRole("heading", { name: "Section 52", exact: true });
|
||||
await browseSource(52, 0);
|
||||
await expect.poll(async () => Math.abs((await position(followerHeading)).y)).toBeLessThanOrEqual(45);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -22,11 +22,12 @@ import {
|
||||
import clsx from "clsx";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { editorController } from "@/editor/core/controller";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { Direction, 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, notifications, registerFontZoomSurface, useEditorShown } from "@/workbench/contributions";
|
||||
import { useToolWindowLayout, viewModeOf } from "@/workbench/toolwindows/store";
|
||||
import { editorsFor, setShownLine } from "@/editor/api";
|
||||
import { highlightInto } from "@/editor/lsp/markdown";
|
||||
import {
|
||||
@@ -132,6 +133,14 @@ function attachImagePanZoom(img: HTMLImageElement): void {
|
||||
const SPLIT_STORAGE_KEY = "openidea.markdown.split";
|
||||
const DEFAULT_SPLIT_LAYOUT = { editor: 50, preview: 50 };
|
||||
|
||||
function sideDockChanged(next: ReturnType<typeof useToolWindowLayout.getState>, prev: typeof next) {
|
||||
const docked = (state: typeof next, side: "left" | "right") =>
|
||||
[state.visible[side], state.visible[`${side}-split`]].some(
|
||||
(id) => id && viewModeOf(id, state.viewModes) !== "undock",
|
||||
);
|
||||
return (["left", "right"] as const).some((side) => docked(next, side) !== docked(prev, side));
|
||||
}
|
||||
|
||||
export function MarkdownEditor({
|
||||
path,
|
||||
tabId,
|
||||
@@ -153,23 +162,52 @@ export function MarkdownEditor({
|
||||
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(() => {
|
||||
const el = editorRef.current;
|
||||
if (!el || typeof ResizeObserver === "undefined") return;
|
||||
const viewOf = () => editorsFor(path).find((ed) => ed.tabId === tabId || el.contains(ed.view.dom))?.view;
|
||||
let width = el.clientWidth;
|
||||
let anchor: ReturnType<typeof sourceResizeAnchor>;
|
||||
let pending = false;
|
||||
const unsubscribe = useToolWindowLayout.subscribe((next, prev) => {
|
||||
if (!sideDockChanged(next, prev)) return;
|
||||
const view = viewOf();
|
||||
if (!width || !view?.lineWrapping || !view.inView) return;
|
||||
if (anchor?.view !== view || anchor.doc !== view.state.doc || anchor.top !== view.scrollDOM.scrollTop) {
|
||||
anchor = sourceResizeAnchor(view);
|
||||
}
|
||||
pending = true;
|
||||
});
|
||||
const ro = new ResizeObserver(() => {
|
||||
const next = el.clientWidth;
|
||||
if (next === width) return;
|
||||
width = next;
|
||||
const restore = pending ? anchor : undefined;
|
||||
pending = false;
|
||||
anchor = undefined;
|
||||
if (next <= 0) return;
|
||||
for (const ed of editorsFor(path)) {
|
||||
if (!ed.tabId || ed.tabId === tabId) ed.view.requestMeasure();
|
||||
const view = viewOf();
|
||||
if (!view) return;
|
||||
if (restore?.view === view && restore.doc === view.state.doc) {
|
||||
const topMargin = Math.max(
|
||||
0,
|
||||
...view.state.facet(EditorView.scrollMargins).map((margin) => margin(view)?.top ?? 0),
|
||||
);
|
||||
view.dispatch({
|
||||
effects: EditorView.scrollIntoView(restore.pos, { y: "start", yMargin: restore.inset - topMargin }),
|
||||
});
|
||||
// Read the position after CodeMirror has applied the anchor in this resize frame.
|
||||
view.lineBlockAtHeight(0);
|
||||
anchor = { ...restore, top: view.scrollDOM.scrollTop };
|
||||
} else {
|
||||
view.requestMeasure();
|
||||
}
|
||||
});
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
return () => {
|
||||
unsubscribe();
|
||||
ro.disconnect();
|
||||
};
|
||||
}, [path, tabId]);
|
||||
|
||||
const splitBounds = mode === "split" ? { minSize: "10%", maxSize: "90%" } : {};
|
||||
@@ -214,6 +252,20 @@ export function MarkdownEditor({
|
||||
);
|
||||
}
|
||||
|
||||
function sourceResizeAnchor(view: EditorView) {
|
||||
const scroller = view.scrollDOM;
|
||||
const top = scroller.scrollTop;
|
||||
if (top <= 0 || scroller.scrollHeight - scroller.clientHeight - top <= 1) return;
|
||||
const viewport = scroller.getBoundingClientRect();
|
||||
const content = view.contentDOM.getBoundingClientRect();
|
||||
const pos = view.posAtCoords({
|
||||
x: view.textDirection === Direction.LTR ? content.left + 1 : content.right - 1,
|
||||
y: viewport.top + 2,
|
||||
});
|
||||
const coords = pos !== null ? view.coordsAtPos(pos) : null;
|
||||
if (pos !== null && coords) return { view, doc: view.state.doc, pos, inset: coords.top - viewport.top, top };
|
||||
}
|
||||
|
||||
function blocksOf(root: HTMLElement) {
|
||||
const blocks = [];
|
||||
for (const el of root.querySelectorAll<HTMLElement>(":scope > [data-preview-blocks] > [data-line]")) {
|
||||
@@ -517,8 +569,17 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root || !window.IntersectionObserver || !window.ResizeObserver) return;
|
||||
let width = 0;
|
||||
let settled = 0;
|
||||
let viewportWidth = root.clientWidth;
|
||||
let visibilityPaused = false;
|
||||
const visibility = new IntersectionObserver(
|
||||
(entries) => {
|
||||
// Changing which blocks use the live width can move the anchor between resize passes.
|
||||
if (width !== settled || root.clientWidth !== viewportWidth) {
|
||||
visibilityPaused = true;
|
||||
return;
|
||||
}
|
||||
for (const entry of entries) entry.target.toggleAttribute("data-in-viewport", entry.isIntersecting);
|
||||
},
|
||||
{ root, rootMargin: "100% 0px" },
|
||||
@@ -534,23 +595,49 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
const replaced = new MutationObserver(observeBlocks);
|
||||
replaced.observe(root, { childList: true });
|
||||
|
||||
let width = 0;
|
||||
let settled = 0;
|
||||
let timer: number | undefined;
|
||||
let restoredTop: number | undefined;
|
||||
let anchor: { line: number; within: number; atBottom: boolean } | undefined;
|
||||
const rememberPosition = () => {
|
||||
const top = root.scrollTop;
|
||||
if (root.clientWidth !== viewportWidth || top === restoredTop) return;
|
||||
restoredTop = undefined;
|
||||
const end = root.scrollHeight;
|
||||
const line = previewLineAtOffset(blocks.current, top);
|
||||
anchor =
|
||||
top > 0
|
||||
? {
|
||||
line,
|
||||
within: top - previewOffsetForLine(blocks.current, line, end),
|
||||
atBottom: top + root.clientHeight >= end - 1,
|
||||
}
|
||||
: undefined;
|
||||
};
|
||||
const restorePosition = () => {
|
||||
if (anchor) {
|
||||
root.scrollTop = anchor.atBottom
|
||||
? root.scrollHeight
|
||||
: previewOffsetForLine(blocks.current, anchor.line, root.scrollHeight) + anchor.within;
|
||||
restoredTop = root.scrollTop;
|
||||
}
|
||||
viewportWidth = root.clientWidth;
|
||||
if (width === settled) {
|
||||
follower.current?.resume();
|
||||
if (visibilityPaused) {
|
||||
visibilityPaused = false;
|
||||
observeBlocks();
|
||||
}
|
||||
}
|
||||
};
|
||||
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 = !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;
|
||||
const initial = !settled;
|
||||
settled = width;
|
||||
root.removeAttribute("data-constrain-blocks");
|
||||
root.style.setProperty("--markdown-block-width", `${width}px`);
|
||||
if (follow) follow.align();
|
||||
else if (atBottom) root.scrollTop = root.scrollHeight;
|
||||
else if (block) root.scrollTop = block.top + within;
|
||||
const follow = follower.current;
|
||||
if (initial && follow) follow.align();
|
||||
else restorePosition();
|
||||
};
|
||||
const schedule = () => {
|
||||
if (width === settled) return;
|
||||
@@ -575,8 +662,15 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
if (settled && width !== settled) markVisible();
|
||||
root.toggleAttribute("data-constrain-blocks", width < settled);
|
||||
if (!settled) apply();
|
||||
else schedule();
|
||||
else {
|
||||
// Visible blocks reflow at the new width before ResizeObserver runs.
|
||||
follower.current?.pause();
|
||||
restorePosition();
|
||||
schedule();
|
||||
}
|
||||
});
|
||||
rememberPosition();
|
||||
root.addEventListener("scroll", rememberPosition, { passive: true });
|
||||
sizes.observe(root);
|
||||
document.addEventListener("pointerup", schedule, true);
|
||||
document.addEventListener("pointercancel", schedule, true);
|
||||
@@ -586,13 +680,15 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
replaced.disconnect();
|
||||
sizes.disconnect();
|
||||
window.clearTimeout(timer);
|
||||
root.removeEventListener("scroll", rememberPosition);
|
||||
document.removeEventListener("pointerup", schedule, true);
|
||||
document.removeEventListener("pointercancel", schedule, true);
|
||||
window.removeEventListener("blur", schedule);
|
||||
root.style.removeProperty("--markdown-block-width");
|
||||
root.removeAttribute("data-constrain-blocks");
|
||||
follower.current?.resume();
|
||||
};
|
||||
}, [html]);
|
||||
}, [html, sync]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
|
||||
@@ -28,9 +28,15 @@ it("retargets one animation, settles exactly, and yields to manual scrolling", (
|
||||
now += dt;
|
||||
cb?.(now);
|
||||
};
|
||||
const move = (topLine: number, sourceAtEnd = false) =>
|
||||
const move = (topLine: number, sourceAtEnd = false, navigate = false) =>
|
||||
useLiveMarkdown.setState((s) => ({
|
||||
doc: { ...s.doc!, topLine, sourceAtEnd, scrollSeq: (s.doc?.scrollSeq ?? 0) + 1 },
|
||||
doc: {
|
||||
...s.doc!,
|
||||
topLine,
|
||||
sourceAtEnd,
|
||||
scrollSeq: (s.doc?.scrollSeq ?? 0) + 1,
|
||||
caretSeq: (s.doc?.caretSeq ?? 0) + Number(navigate),
|
||||
},
|
||||
}));
|
||||
const follow = followMarkdownSource("doc", root, (line) => line * 10);
|
||||
try {
|
||||
@@ -52,6 +58,17 @@ it("retargets one animation, settles exactly, and yields to manual scrolling", (
|
||||
move(20);
|
||||
root.dispatchEvent(new Event("wheel"));
|
||||
expect(callback).toBeUndefined();
|
||||
|
||||
follow.pause();
|
||||
move(30);
|
||||
expect(callback).toBeUndefined();
|
||||
follow.resume();
|
||||
expect(root.scrollTop).toBe(350);
|
||||
follow.pause();
|
||||
move(15, false, true);
|
||||
expect(root.scrollTop).toBe(350);
|
||||
follow.resume();
|
||||
expect(root.scrollTop).toBe(150);
|
||||
} finally {
|
||||
follow.dispose();
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ export function followMarkdownSource(path: string, root: HTMLElement, offsetForL
|
||||
let lastTime = 0;
|
||||
let position = root.scrollTop;
|
||||
let applied = position;
|
||||
let paused = false;
|
||||
let navigated = false;
|
||||
const target = () => {
|
||||
const state = useLiveMarkdown.getState()[path];
|
||||
const max = Math.max(0, root.scrollHeight - root.clientHeight);
|
||||
@@ -17,6 +19,7 @@ export function followMarkdownSource(path: string, root: HTMLElement, offsetForL
|
||||
frame = 0;
|
||||
};
|
||||
const align = () => {
|
||||
if (paused) return;
|
||||
stop();
|
||||
root.scrollTop = target();
|
||||
};
|
||||
@@ -38,6 +41,10 @@ export function followMarkdownSource(path: string, root: HTMLElement, offsetForL
|
||||
const off = useLiveMarkdown.subscribe((next, prev) => {
|
||||
const a = next[path],
|
||||
b = prev[path];
|
||||
if (paused) {
|
||||
if (a?.caretSeq !== b?.caretSeq) navigated = true;
|
||||
return;
|
||||
}
|
||||
if (!a || (a.topLine === b?.topLine && a.scrollSeq === b?.scrollSeq && a.sourceAtEnd === b?.sourceAtEnd)) return;
|
||||
if (reducedMotion()) return align();
|
||||
if (frame) return;
|
||||
@@ -49,6 +56,17 @@ export function followMarkdownSource(path: string, root: HTMLElement, offsetForL
|
||||
root.addEventListener("touchstart", stop, { passive: true });
|
||||
return {
|
||||
align,
|
||||
pause() {
|
||||
paused = true;
|
||||
stop();
|
||||
},
|
||||
resume() {
|
||||
paused = false;
|
||||
if (navigated) {
|
||||
navigated = false;
|
||||
align();
|
||||
}
|
||||
},
|
||||
dispose() {
|
||||
stop();
|
||||
off();
|
||||
|
||||
Reference in new issue
Заблокувати користувача