Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): stand scroll writers down for outline navigation (PRD-8186) (#3924)

Andrew Mikofalvy9244466ba7b3
diff --git a/.changeset/prd-8186-outline-backward-navigation.md b/.changeset/prd-8186-outline-backward-navigation.md
new file mode 100644
index 000000000..c94908788
--- /dev/null
+++ b/.changeset/prd-8186-outline-backward-navigation.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Clicking an outline row that sits above where you are reading now moves you there, instead of doing nothing for the first ten seconds after a document opens. A freshly opened document keeps a loop running that puts you back where you left off, and that loop only recognized someone else taking the scroller when the page moved **down**. A click aimed **up** the document looked like drift to it, so it put the page back, frame after frame, until the loop gave up ten seconds later. The click was never lost; it was being undone. Every explicit navigation now stands that loop down while it lands, so the same fix covers outline rows in both editing modes, Problems rows, raw-MDX jumps, deep links, and find/replace matches.
+
+One behavior worth knowing, because it is new: for about half a second after a jump, other things that scroll the page hold off — the view following an agent's writes, the pull to the bottom of the document while the composer resizes, and revealing the caret as you type. The place you just asked for outranks all of them. Following a link straight to a heading holds a little longer, because it re-aims a few times while the page settles. While you are stepping through find results, or while a linked comment settles into place, the hold-off lasts as long as that does. Reopening a document you had jumped in still returns you to where the jump left you.
diff --git a/knip.config.ts b/knip.config.ts
index 8ad68f996..b61debe5e 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -124,9 +124,7 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: [
- '@types/shell-quote',
- ],
+ ignoreDependencies: ['@types/shell-quote'],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
diff --git a/packages/app/src/comments/jump-scroll-ownership.dom.test.ts b/packages/app/src/comments/jump-scroll-ownership.dom.test.ts
index 5baf1a128..f7c84f2ad 100644
--- a/packages/app/src/comments/jump-scroll-ownership.dom.test.ts
+++ b/packages/app/src/comments/jump-scroll-ownership.dom.test.ts
@@ -8,9 +8,9 @@
* did nothing until the loop's ten-second backstop expired, which reads as
* "it works after five or six taps".
*
- * `acquireScrollRestoreSuppression` is the channel the loop actually watches
- * (it exits with `reason: 'landing'` on the next frame), so what this pins is
- * that the jump holds it ACROSS the write and lets go afterwards.
+ * `acquireScrollRestoreSuppression` is the channel the loop actually watches (it
+ * exits on the next frame, naming whichever holder raised it), so what this pins
+ * is that the jump holds it ACROSS the write and lets go afterwards.
*/
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
diff --git a/packages/app/src/comments/scroll-to-anchor.ts b/packages/app/src/comments/scroll-to-anchor.ts
index bb3d7a643..756adb98d 100644
--- a/packages/app/src/comments/scroll-to-anchor.ts
+++ b/packages/app/src/comments/scroll-to-anchor.ts
@@ -16,10 +16,7 @@
*/
import type { Editor } from '@tiptap/react';
-import {
- acquireScrollRestoreSuppression,
- runScrollNavigation,
-} from '@/editor/scroll-restore-coordination';
+import { runScrollNavigation } from '@/editor/scroll-restore-coordination';
import { getEditorView } from '@/editor/utils/get-editor-view';
/**
@@ -32,44 +29,6 @@ const BOTTOM_ROOM_PX = 220;
/** Breathing room below the toolbar when we do move, so it isn't flush. */
const LEAD_PX = 24;
-/**
- * How long a jump holds the document's scroller after writing to it.
- *
- * Long enough for the scroll-restore loop to see the flag on its next frame and
- * stand down (it exits for good at that point), short enough that the other
- * readers of this flag — the agent-follow scroll, the composer's bottom pin —
- * are barely affected.
- */
-const JUMP_OWNERSHIP_MS = 600;
-
-/**
- * Perform a jump's scroll as the document's single scroll writer, or decline.
- *
- * TWO writers have to be told, and they take different signals:
- *
- * - Mode-switch landings register as scroll owners; `runScrollNavigation`
- * pre-empts the ones that yield and refuses for one that does not.
- * - The pool's scroll-restore loop watches `isScrollRestoreSuppressed`. Left
- * untold it does NOT yield to a jump toward the top of the document: its
- * takeover test is directional, and a scrollTop DECREASE is indistinguishable
- * from the browser's shrink-clamp, so it re-applies its own target over ours,
- * frame after frame, until its 10-second backstop expires. That is why a
- * comment above the current view did nothing for click after click and then
- * suddenly worked — the clicks were not accumulating, the backstop was
- * running out.
- *
- * Returns whether the scroll ran.
- */
-function applyJumpScroll(docName: string, write: () => void): boolean {
- return runScrollNavigation(docName, () => {
- // Acquired BEFORE the write: the restore loop reads the flag on the frame it
- // measures, and a write it sees first is measured as drift to correct.
- const suppression = acquireScrollRestoreSuppression(docName);
- write();
- window.setTimeout(() => suppression.release(), JUMP_OWNERSHIP_MS);
- });
-}
-
export interface AnchorViewport {
/** The passage, in viewport coordinates. */
anchorTop: number;
@@ -121,10 +80,10 @@ export function scrollportInsetTop(container: HTMLElement): number {
/**
* Bring a comment's passage into a readable position, with room beneath it.
*
- * Returns whether the navigation RAN — see {@link applyJumpScroll} for what can
- * decline it and for the two scroll writers a jump has to out-rank. `docName` is
- * required so that contract is enforced by this producer rather than by each
- * call site remembering to ask.
+ * Returns whether the navigation RAN — see `claimScrollerForNavigation` for what
+ * can decline it and for the two scroll writers a jump has to out-rank.
+ * `docName` is required so that contract is enforced by that producer rather
+ * than by each call site remembering to ask.
*/
export function scrollAnchorIntoView(
editor: Editor,
@@ -148,7 +107,7 @@ export function scrollAnchorIntoView(
// No scrollport of our own to drive (an embedded or content-sized editor):
// ProseMirror's minimal scroll is still better than not moving at all.
if (!container) {
- return applyJumpScroll(docName, () => editor.commands.scrollIntoView());
+ return runScrollNavigation(docName, 'comment-reveal', () => editor.commands.scrollIntoView());
}
let start: { top: number; bottom: number };
let end: { top: number; bottom: number };
@@ -172,7 +131,7 @@ export function scrollAnchorIntoView(
// not jolt the page for each.
if (delta === 0) return true;
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
- return applyJumpScroll(docName, () =>
+ return runScrollNavigation(docName, 'comment-reveal', () =>
container.scrollTo({
top: container.scrollTop + delta,
behavior: opts?.instant || reduceMotion ? 'auto' : 'smooth',
diff --git a/packages/app/src/components/BottomComposer.tsx b/packages/app/src/components/BottomComposer.tsx
index a16a3b468..ae0ea2a75 100644
--- a/packages/app/src/components/BottomComposer.tsx
+++ b/packages/app/src/components/BottomComposer.tsx
@@ -265,13 +265,15 @@ export function BottomComposer({
// eases down so the last lines stay above the newly-grown composer instead of
// being covered. Also clamps any scroller stranded past shrinking content.
const followBottom = () => {
- // A mode-switch landing owns the scroller for its whole settle window, so
- // the pin must stand down for it exactly as it does for the user's own
+ // Another writer owns this document's scroller — a mode-switch landing for
+ // its whole settle window, or an explicit navigation for its brief hold —
+ // so the pin must stand down for it exactly as it does for the user's own
// wheel. Without this the pin wins: a deep mode flip momentarily clamps
// the scroller to the bottom (the outgoing mode's scrollTop overshoots the
// incoming mode's shorter content), which reads here as "bottom-anchored"
// and re-pins the user to the end of the document every frame, stomping
- // the landing after it settled.
+ // the landing after it settled. The navigation case is the same shape with
+ // a different cause: a jump the reader just asked for outranks the pin.
if (isScrollRestoreSuppressed(docName)) return;
const pinned = [...document.querySelectorAll<HTMLElement>('.editor-doc-scroll')].filter(
(el) => {
@@ -290,9 +292,10 @@ export function BottomComposer({
window.addEventListener('touchstart', cancel, { passive: true });
const start = performance.now();
const step = () => {
- // A landing that starts mid-window cancels the pin outright rather than
- // pausing it: resuming afterwards would yank the settled landing back to
- // the bottom, since `pinned` was captured before the landing moved it.
+ // A landing or a navigation that takes the scroller mid-window cancels
+ // the pin outright rather than pausing it: resuming afterwards would
+ // yank the settled position back to the bottom, since `pinned` was
+ // captured before that writer moved it.
if (isScrollRestoreSuppressed(docName)) cancelled = true;
if (cancelled || performance.now() - start >= 300) {
window.removeEventListener('wheel', cancel);
@@ -310,8 +313,9 @@ export function BottomComposer({
const revealCaret = () => {
if (surface !== 'wysiwyg') return;
requestAnimationFrame(() => {
- // Same standing-down rule as the bottom pin: never write scroll while a
- // landing owns the scroller.
+ // Same standing-down rule as the bottom pin: never write scroll while
+ // another writer owns the scroller, whether that is a landing settling
+ // or an explicit navigation holding the place it just took.
if (isScrollRestoreSuppressed(docName)) return;
const editor = getEditorForDoc(docName);
const box = cardRef.current;
diff --git a/packages/app/src/components/EditorActivityPool.scroll-suppression.dom.test.tsx b/packages/app/src/components/EditorActivityPool.scroll-suppression.dom.test.tsx
index af8625eab..14490b492 100644
--- a/packages/app/src/components/EditorActivityPool.scroll-suppression.dom.test.tsx
+++ b/packages/app/src/components/EditorActivityPool.scroll-suppression.dom.test.tsx
@@ -124,13 +124,13 @@ describe('ScrollPreservingContainer scroll-restore suppression', () => {
});
test('stands down and writes no scroll position while a landing holds suppression', () => {
- acquireScrollRestoreSuppression('doc-b');
+ acquireScrollRestoreSuppression('doc-b', 'landing');
const { container } = render(<Harness active docName="doc-b" />);
expect(scrollerOf(container).scrollTop).toBe(0);
});
test('resumes restoring on the next activation after the landing releases', () => {
- const handle = acquireScrollRestoreSuppression('doc-c');
+ const handle = acquireScrollRestoreSuppression('doc-c', 'landing');
const { container, rerender } = render(<Harness active={false} docName="doc-c" />);
// Activate while suppressed → the restore stands down.
rerender(<Harness active docName="doc-c" />);
diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsx
index dc84f3276..5d49d49f0 100644
--- a/packages/app/src/components/EditorActivityPool.tsx
+++ b/packages/app/src/components/EditorActivityPool.tsx
@@ -65,9 +65,9 @@ import type { ServerRestartRecoveryState } from '@/editor/provider-pool';
import {
BODY_ANCHOR_ATTR,
getDocScrollState,
- isScrollRestoreSuppressed,
rememberDocScrollState,
scrollFraction,
+ scrollSuppressionHolder,
} from '@/editor/scroll-restore-coordination';
import { TiptapEditor } from '@/editor/TiptapEditor';
import type { EditorModeValue } from '@/editor/use-editor-mode';
@@ -820,7 +820,17 @@ export function ScrollPreservingContainer({
// A mode-switch landing owns the scroll for this document during its settle
// window; stand down so there is a single writer and the restore does not
// overwrite the landing with the pre-landing position.
- if (isScrollRestoreSuppressed(docName)) return;
+ //
+ // For a LANDING only, because this effect gets exactly one chance: it reads
+ // the holder once and its deps carry no signal that fires when a hold
+ // lapses, so returning here is a restore that never runs rather than one
+ // that runs later. Standing down for a landing still leaves a deliberate
+ // position, since the landing writes one. Standing down for an explicit
+ // navigation would not: it has already written its position and is only
+ // defending it, while `display:none` zeroed this scroller on the way out
+ // (the reason the position is captured by the scroll listener above and not
+ // read here) — so the reader would be handed the top of the document.
+ if (scrollSuppressionHolder(docName) === 'landing') return;
const saved = getDocScrollState(docName);
// Cross-mode re-activation floor. The saved offset was measured against the
@@ -971,15 +981,43 @@ export function ScrollPreservingContainer({
el.addEventListener('keydown', yieldToUser);
const tick = () => {
if (done) return;
- // A landing acquired the scroll for this document mid-restore — stop
- // competing so the landing is the single writer. Probed BEFORE the
- // external-scroll check below: a landing's own writes would otherwise
- // read as a takeover of unknown origin, and the named reason is the more
- // precise signal for an exit we can attribute exactly.
- if (isScrollRestoreSuppressed(docName)) {
+ // Another writer acquired the scroll for this document mid-restore — a
+ // mode-switch landing for its settle window, or an explicit navigation
+ // for its brief hold. Stop competing either way, so that writer is the
+ // single one. Probed BEFORE the external-scroll check below: its own
+ // writes would otherwise read as a takeover of unknown origin, and the
+ // holder attributes the exit exactly.
+ //
+ // `reason` carries the holder rather than a fixed value. Each of the
+ // sibling reasons names a real actor, and this is the branch that used to
+ // absorb every navigation under the wrong one: an operator reading a
+ // trace for "why did scroll restore stop here" would go to the landing
+ // controller and find no matching mode-switch mark, when the cause was an
+ // outline click.
+ //
+ // The handover gets a mark of its own, UNGATED, because `yielded` cannot
+ // carry it: `yielded` means a restore that never completed, which is why
+ // IT is gated — and a restore that HAS landed and is re-applying its
+ // target frame after frame is exactly the state an explicit navigation
+ // collides with. Reported only through `yielded`, that common case is
+ // silent: the last thing recorded is a phase-success, so a restore cut
+ // short by a named writer reads the same as one that ran undisturbed.
+ // Widening `yielded` instead would make a healthy restore read as an
+ // incomplete one, trading one attribution error for another. Both marks
+ // fire when a restore that never landed is taken over, and they say
+ // different things: one that it did not complete, one who has the
+ // scroller now. No seam here — this reader sees the holder kind the
+ // registry keeps, not the click that produced it.
+ const holder = scrollSuppressionHolder(docName);
+ if (holder) {
+ mark('ok/scroll-restore/superseded', {
+ holder,
+ elapsedMs: performance.now() - startTs,
+ finalScrollTop: el.scrollTop,
+ });
if (!hasLandedOnce) {
mark('ok/scroll-restore/yielded', {
- reason: 'landing',
+ reason: holder,
elapsedMs: performance.now() - startTs,
finalScrollTop: el.scrollTop,
});
diff --git a/packages/app/src/editor/SourceEditor.dom.test.tsx b/packages/app/src/editor/SourceEditor.dom.test.tsx
index 7c639186d..c22dc26b3 100644
--- a/packages/app/src/editor/SourceEditor.dom.test.tsx
+++ b/packages/app/src/editor/SourceEditor.dom.test.tsx
@@ -8,6 +8,7 @@ import { Awareness } from 'y-protocols/awareness';
import * as Y from 'yjs';
import { subscribeToOpenAskAiComposer } from '@/components/ask-ai-composer-events';
import { OUTLINE_NAV_EVENT, type OutlineNavDetail } from '@/components/OutlinePanel';
+import { LINT_NAV_EVENT, type LintNavDetail } from '@/components/ProblemsPanel';
import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
import { evictCmEditor } from './editor-cache';
import type { LandingHandle } from './landing-controller';
@@ -495,3 +496,66 @@ describe('SourceEditor cross-mode landing replay', () => {
expect(peekPendingSourceNavigation('source-landing-started')).toBeNull();
});
});
+
+/**
+ * The Problems row banks its intent and then dispatches a live event, so
+ * whichever editor is visible consumes the event and clears the bank. A click
+ * the scroller refuses moved nothing, so clearing on it spends the intent on a
+ * jump that never happened. The WYSIWYG half of this seam gates its clear on
+ * the same answer.
+ */
+describe('SourceEditor Problems-row navigation', () => {
+ const detailFor = (docName: string): LintNavDetail => ({ docName, line: 3, column: 1 });
+
+ beforeEach(() => {
+ __resetScrollRestoreCoordination();
+ clearPendingSourceNavigationsForTest();
+ globalThis.fetch = vi.fn(async () => Response.json({})) as unknown as typeof fetch;
+ });
+
+ afterEach(() => {
+ __resetScrollRestoreCoordination();
+ clearPendingSourceNavigationsForTest();
+ cleanup();
+ for (const docName of mountedDocNames) evictCmEditor(docName);
+ mountedDocNames.clear();
+ globalThis.fetch = originalFetch;
+ });
+
+ /**
+ * Mount source mode, then bank and click in the panel's own order. Banking
+ * before the mount would be replayed and consumed by the mount-time effect,
+ * which is a different path from the live click under test.
+ */
+ async function clickProblemsRow(docName: string): Promise<void> {
+ const { provider, ytext } = makeProvider(docName, '# heading\n\nbody\n\nmore body');
+ const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);
+ await findCmContent(container);
+ rememberPendingSourceNavigation(docName, { kind: 'lint', detail: detailFor(docName) });
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent(LINT_NAV_EVENT, { detail: detailFor(docName) }));
+ });
+ }
+
+ test('keeps the banked intent when a landing refuses the scroller', async () => {
+ const docName = 'source-problems-row-refused';
+ // A landing that is itself an explicit navigation keeps the scroller: it has
+ // already placed the caret, so this click stands down whole.
+ registerLandingScrollOwner(docName, { yieldsToNavigation: false, supersede: () => {} });
+
+ await clickProblemsRow(docName);
+
+ expect(peekPendingSourceNavigation(docName)).toEqual({
+ kind: 'lint',
+ detail: detailFor(docName),
+ });
+ });
+
+ test('consumes it once the jump has run', async () => {
+ const docName = 'source-problems-row-granted';
+
+ await clickProblemsRow(docName);
+
+ expect(peekPendingSourceNavigation(docName)).toBeNull();
+ });
+});
diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsx
index 17d8becdf..680473a14 100644
--- a/packages/app/src/editor/SourceEditor.tsx
+++ b/packages/app/src/editor/SourceEditor.tsx
@@ -79,7 +79,7 @@ function applyOutlineNavigation(view: EditorView, detail: OutlineNavDetail, docN
const heading = sourceHeadingLines(view.state.doc)[detail.index];
if (!heading) return;
- runScrollNavigation(docName, () => {
+ runScrollNavigation(docName, 'outline', () => {
view.dispatch({
selection: EditorSelection.cursor(heading.from),
effects: EditorView.scrollIntoView(heading.from, { y: 'start' }),
@@ -103,7 +103,7 @@ export function applyRawMdxNavigation(
// Clamp offset to doc length (offset may exceed doc length if content
// differs between Y.Text and originalSpan).
const pos = Math.min(detail.offset, doc.length);
- runScrollNavigation(docName, () => {
+ runScrollNavigation(docName, 'raw-mdx', () => {
view.dispatch({
selection: EditorSelection.cursor(pos),
effects: EditorView.scrollIntoView(pos, { y: 'center' }),
@@ -114,13 +114,19 @@ export function applyRawMdxNavigation(
}
/** Jump to a lint diagnostic's 1-based line/column. Lines/columns are clamped —
- * the doc may shift between the click and this dispatch. */
-function applyLintNavigation(view: EditorView, detail: LintNavDetail, docName: string): void {
+ * the doc may shift between the click and this dispatch.
+ *
+ * Returns whether the jump ran. A landing that is itself an explicit navigation
+ * keeps the scroller and this click stands down whole, so a caller holding the
+ * banked intent must keep it for a later replay rather than spend it on a jump
+ * that did not happen. The WYSIWYG half of this seam gates its clear the same
+ * way. */
+function applyLintNavigation(view: EditorView, detail: LintNavDetail, docName: string): boolean {
const doc = view.state.doc;
const lineNumber = Math.min(Math.max(detail.line, 1), doc.lines);
const line = doc.line(lineNumber);
const pos = Math.min(line.from + Math.max(0, detail.column - 1), line.to);
- runScrollNavigation(docName, () => {
+ return runScrollNavigation(docName, 'problems-row', () => {
view.dispatch({
selection: EditorSelection.cursor(pos),
// `y: 'start'` (not 'center'/'nearest'): in full-page source mode the editor
@@ -275,7 +281,7 @@ export function SourceEditor({
// landing's own target milliseconds later.
search({
scrollToMatch: (range) =>
- claimScrollerForNavigation(resolvedDocName)
+ claimScrollerForNavigation(resolvedDocName, 'find-match')
? EditorView.scrollIntoView(range, { y: 'start' })
: noScrollEffect.of(null),
}),
@@ -540,8 +546,7 @@ export function SourceEditor({
if (!detail || detail.docName !== docName || !isSourceModeActive) return;
const view = viewRef.current;
if (!view) return;
- applyLintNavigation(view, detail, docName);
- clearPendingSourceNavigation(docName);
+ if (applyLintNavigation(view, detail, docName)) clearPendingSourceNavigation(docName);
}
window.addEventListener(LINT_NAV_EVENT, onLintNav);
return () => window.removeEventListener(LINT_NAV_EVENT, onLintNav);
diff --git a/packages/app/src/editor/TiptapEditor.outline-nav.dom.test.tsx b/packages/app/src/editor/TiptapEditor.outline-nav.dom.test.tsx
new file mode 100644
index 000000000..7fbcd7513
--- /dev/null
+++ b/packages/app/src/editor/TiptapEditor.outline-nav.dom.test.tsx
@@ -0,0 +1,262 @@
+// @vitest-environment jsdom
+/**
+ * The WYSIWYG outline seam, end to end.
+ *
+ * An outline row click is an explicit navigation: it reaches the editor as the
+ * panel's own custom event, resolves the Nth heading in the ProseMirror DOM, and
+ * scrolls it into view. What makes it correct is not the scroll — it is that the
+ * scroll goes through the coordination producer, which is what makes the
+ * document's other scroll writers stand down for it. Two of them exist, and a
+ * click that only pre-empts one is erased by the other whenever the clicked
+ * heading is ABOVE where the reader currently is.
+ *
+ * So these cases assert the seam reaches the guarantee, through the predicate
+ * the container's restore loop actually reads. That the predicate then stops the
+ * real loop is pinned next door, in scroll-navigation-ownership.dom.test.tsx —
+ * together the two cover the click all the way to the loop stepping aside.
+ *
+ * The editor construction path (cache + mount promise) is replaced by a real
+ * TipTap editor built here, so the component's own effects run unchanged against
+ * a genuine ProseMirror view; the surrounding chrome is stubbed to markers. That
+ * is the same harness the deep-link ladder test uses.
+ */
+
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import { act, cleanup, render } from '@testing-library/react';
+import { Editor } from '@tiptap/core';
+import { Suspense } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { Awareness } from 'y-protocols/awareness';
+import * as Y from 'yjs';
+import { OUTLINE_NAV_EVENT, type OutlineNavDetail } from '@/components/OutlinePanel';
+import {
+ __resetScrollRestoreCoordination,
+ isScrollRestoreSuppressed,
+ registerLandingScrollOwner,
+} from '@/editor/scroll-restore-coordination';
+import { getCollector } from '@/lib/perf/collector';
+import { sharedExtensions } from './extensions/shared';
+
+const DOC_NAME = 'outline-nav-doc';
+/** The diagnostic mark that makes a refused navigation attributable. */
+const NAVIGATION_DECLINED_MARK = 'ok/scroll-nav/declined';
+
+let editorEntry: {
+ editor: Editor;
+ ydoc: Y.Doc;
+ ytext: Y.Text;
+ provider: HocuspocusProvider;
+} | null = null;
+
+vi.doMock('./DocumentContext', () => ({
+ useDocumentContext: () => ({
+ principal: null,
+ activeDocName: DOC_NAME,
+ recycleDocument: () => {},
+ openTarget: () => {},
+ }),
+}));
+vi.doMock('../presence/identity', () => ({
+ useIdentity: () => ({ name: 'Tester', color: '#336699' }),
+}));
+vi.doMock('./mount-promise', () => ({
+ mountTiptapEditorPromise: () => Promise.resolve(editorEntry),
+}));
+vi.doMock('./editor-cache', () => ({
+ parkTiptapEditor: () => {},
+ peekRenameSnapshot: () => null,
+ clearRenameSnapshot: () => {},
+}));
+vi.doMock('./bubble-menu/BubbleMenuBar', () => ({ BubbleMenuBar: () => <div /> }));
+vi.doMock('./table-controls/TableCellHandles', () => ({ TableCellHandles: () => <div /> }));
+vi.doMock('@/components/editor/SelectionAnnouncer', () => ({
+ SelectionAnnouncer: () => <div />,
+}));
+vi.doMock('./interaction-layer', () => ({ InteractionLayerView: () => <div /> }));
+vi.doMock('@tiptap/react', () => ({ EditorContent: () => <div data-testid="editor-content" /> }));
+
+const { TiptapEditor } = await import('./TiptapEditor');
+
+// jsdom ships no `CSS` object; the deep-link ladder escapes an anchor before
+// querying for it, and it runs on mount here too.
+if (typeof globalThis.CSS === 'undefined') {
+ Object.defineProperty(globalThis, 'CSS', {
+ value: { escape: (value: string) => value.replace(/[^\w-]/g, (c) => `\\${c}`) },
+ configurable: true,
+ });
+}
+
+function makeProvider(ydoc: Y.Doc): HocuspocusProvider {
+ return {
+ document: ydoc,
+ awareness: new Awareness(ydoc),
+ configuration: { name: DOC_NAME },
+ on: () => {},
+ off: () => {},
+ } as unknown as HocuspocusProvider;
+}
+
+describe('outline navigation in the WYSIWYG editor', () => {
+ let host: HTMLElement;
+ let portalTarget: HTMLElement;
+ let scrolled: HTMLElement[];
+ let suppressedAtScroll: boolean[];
+ let originalScrollIntoView: PropertyDescriptor | undefined;
+
+ beforeEach(() => {
+ __resetScrollRestoreCoordination();
+ getCollector()?.reset();
+ host = document.createElement('div');
+ document.body.appendChild(host);
+ portalTarget = document.createElement('div');
+ document.body.appendChild(portalTarget);
+
+ const ydoc = new Y.Doc();
+ const ytext = ydoc.getText('source');
+ ytext.insert(0, '# Top\n\nbody\n\n## Middle\n\nbody\n\n## Bottom\n\nbody');
+ const editor = new Editor({
+ element: host,
+ extensions: sharedExtensions,
+ content: {
+ type: 'doc',
+ content: [
+ { type: 'heading', attrs: { level: 1 }, content: [{ type: 'text', text: 'Top' }] },
+ { type: 'paragraph', content: [{ type: 'text', text: 'body' }] },
+ { type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'Middle' }] },
+ { type: 'paragraph', content: [{ type: 'text', text: 'body' }] },
+ { type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'Bottom' }] },
+ { type: 'paragraph', content: [{ type: 'text', text: 'body' }] },
+ ],
+ },
+ });
+ editorEntry = { editor, ydoc, ytext, provider: makeProvider(ydoc) };
+
+ // jsdom implements neither scroll nor layout, so the seam's only observable
+ // act is this call, and which element it landed on.
+ scrolled = [];
+ suppressedAtScroll = [];
+ originalScrollIntoView = Object.getOwnPropertyDescriptor(
+ HTMLElement.prototype,
+ 'scrollIntoView',
+ );
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ value: function scrollIntoViewStub(this: HTMLElement) {
+ scrolled.push(this);
+ suppressedAtScroll.push(isScrollRestoreSuppressed(DOC_NAME));
+ },
+ configurable: true,
+ writable: true,
+ });
+ window.location.hash = '';
+ });
+
+ afterEach(() => {
+ cleanup();
+ editorEntry?.editor.destroy();
+ editorEntry = null;
+ host.remove();
+ portalTarget.remove();
+ __resetScrollRestoreCoordination();
+ if (originalScrollIntoView) {
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', originalScrollIntoView);
+ } else {
+ Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView');
+ }
+ });
+
+ function tree() {
+ const entry = editorEntry;
+ if (!entry) throw new Error('editor entry not prepared');
+ return (
+ <Suspense fallback={null}>
+ <TiptapEditor provider={entry.provider} isSourceMode={false} portalTarget={portalTarget} />
+ </Suspense>
+ );
+ }
+
+ async function renderEditor(): Promise<void> {
+ // The editor arrives through a suspended promise, so the commit that runs
+ // the effects happens after it resolves — inside this awaited act scope.
+ await act(async () => {
+ render(tree());
+ });
+ }
+
+ /** What the outline panel emits when a row is clicked. */
+ async function clickOutlineRow(index: number, slug: string): Promise<void> {
+ const detail: OutlineNavDetail = { docName: DOC_NAME, index, slug, mode: 'wysiwyg' };
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent(OUTLINE_NAV_EVENT, { detail }));
+ });
+ }
+
+ function declinedNavigations(): unknown[] {
+ return (getCollector()?.marks.toArray() ?? [])
+ .filter((m) => m.name === NAVIGATION_DECLINED_MARK)
+ .map((m) => m.properties);
+ }
+
+ test('scrolls the heading the clicked row names', async () => {
+ await renderEditor();
+
+ await clickOutlineRow(1, 'middle');
+
+ expect(scrolled.map((el) => el.textContent)).toEqual(['Middle']);
+ });
+
+ test('the click stands the document scroll-restore down while it lands', async () => {
+ await renderEditor();
+
+ await clickOutlineRow(1, 'middle');
+
+ // Sampled inside the scroll stub rather than read back here, because the
+ // guarantee is that the flag was up AT the moment the click scrolled — the
+ // hold self-releases on a timer, so a later read measures how long the
+ // assertion took to arrive as much as it measures the seam. This is the
+ // predicate the container's restore loop polls every frame; a click that
+ // scrolls without setting it is re-applied over whenever the heading sits
+ // above the reader, because the loop's takeover test only recognises a
+ // scrollTop increase.
+ expect(suppressedAtScroll).toEqual([true]);
+ });
+
+ test('a refused click is recorded rather than silently doing nothing', async () => {
+ await renderEditor();
+ // A landing that is itself an explicit navigation does not yield the
+ // scroller, so the click is declined and nothing moves.
+ registerLandingScrollOwner(DOC_NAME, { yieldsToNavigation: false, supersede: () => {} });
+
+ await clickOutlineRow(1, 'middle');
+
+ expect(scrolled).toEqual([]);
+ // The outline seam treats the producer as an action and drops its answer, so
+ // a refusal is invisible from here: the row highlights and the view does not
+ // move. The refusal has to be attributable somewhere, and to THIS seam —
+ // other seams consume the answer and retry, so the same mark means a dead
+ // click here and a late one there.
+ expect(declinedNavigations()).toEqual([
+ expect.objectContaining({ docName: DOC_NAME, seam: 'outline' }),
+ ]);
+ });
+
+ test('a click for another document is ignored', async () => {
+ await renderEditor();
+
+ const detail: OutlineNavDetail = {
+ docName: 'some-other-doc',
+ index: 1,
+ slug: 'middle',
+ mode: 'wysiwyg',
+ };
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent(OUTLINE_NAV_EVENT, { detail }));
+ });
+
+ // Pooled siblings all hold this listener; claiming a scroller on someone
+ // else's behalf would stand down a restore that has nothing to do with the
+ // click.
+ expect(scrolled).toEqual([]);
+ expect(isScrollRestoreSuppressed('some-other-doc')).toBe(false);
+ expect(isScrollRestoreSuppressed(DOC_NAME)).toBe(false);
+ });
+});
diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsx
index 09f60c174..c1dae8114 100644
--- a/packages/app/src/editor/TiptapEditor.tsx
+++ b/packages/app/src/editor/TiptapEditor.tsx
@@ -1409,9 +1409,14 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
const scrollToChange = (): void => {
const sv = liveView();
if (sv == null || sv.hasFocus() || document.visibilityState !== 'visible') return;
- // Following an agent's write is not the user navigating, so it defers to
- // a mode-switch landing rather than pre-empting one; the later follow-up
- // attempts run once the landing has settled and released.
+ // Following an agent's write is not the user navigating, so it yields to
+ // whoever holds the scroller rather than pre-empting them. Whether a
+ // later rung of the follow-up ladder gets through is the holder's to
+ // decide: a landing may settle and release inside the ladder, but a
+ // navigation's hold outlasts every rung, so a follow that coincides with
+ // one is dropped outright rather than deferred. That is the intended
+ // order — the place the user just asked for outranks the place the agent
+ // wrote.
if (isScrollRestoreSuppressed(docName)) return;
try {
const docSize = sv.state.doc.content.size;
@@ -1544,7 +1549,7 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
// A deep link is an explicit navigation and supersedes a position-
// preserving landing. Reporting a stand-down as "not scrolled" feeds the
// retry ladder below, which re-tries once the other navigation released.
- return runScrollNavigation(docName, () => {
+ return runScrollNavigation(docName, 'deep-link', () => {
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
}
@@ -1656,7 +1661,7 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
const headings = realView.dom.querySelectorAll<HTMLElement>('h1, h2, h3, h4, h5, h6');
const target = headings[detail.index];
if (!target) return;
- runScrollNavigation(docName, () => {
+ runScrollNavigation(docName, 'outline', () => {
target.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
}
diff --git a/packages/app/src/editor/editor-cache.test.ts b/packages/app/src/editor/editor-cache.test.ts
index 2125131a5..0e366bd70 100644
--- a/packages/app/src/editor/editor-cache.test.ts
+++ b/packages/app/src/editor/editor-cache.test.ts
@@ -430,7 +430,7 @@ describe('TipTap cache — lifecycle', () => {
h.editorDom.scrollTop = 1234;
parkTiptapEditor(entry);
- const suppression = acquireScrollRestoreSuppression(h.docName);
+ const suppression = acquireScrollRestoreSuppression(h.docName, 'landing');
const suppressed = makeNode();
mountTiptapEditor({
docName: h.docName,
@@ -452,6 +452,33 @@ describe('TipTap cache — lifecycle', () => {
expect(released.scrollTop).toBe(1234);
});
+ test('mount: cache-hit still restores scroll while a NAVIGATION holds the scroller', () => {
+ // A navigation's hold is not a landing's, and this reader gets one chance.
+ // A landing is still placing a position and will write one, so standing down
+ // for it preserves a deliberate position. A navigation has already written
+ // its position, and the parked scrollTop IS that result — so standing down
+ // here would not defer the restore, it would drop it, and the reader would
+ // arrive at the top of the document rather than where they navigated to.
+ const h = makeTiptapHarness('doc-a');
+ const entry = mountTiptapEditor({
+ docName: h.docName,
+ container: h.container as unknown as HTMLElement,
+ factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,
+ });
+ h.editorDom.scrollTop = 1234;
+ parkTiptapEditor(entry);
+
+ acquireScrollRestoreSuppression(h.docName, 'navigation');
+ const held = makeNode();
+ mountTiptapEditor({
+ docName: h.docName,
+ container: held as unknown as HTMLElement,
+ factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,
+ });
+
+ expect(held.scrollTop).toBe(1234);
+ });
+
test('mount: cache-hit restores focus ONLY when editor owned focus at park time', () => {
const h = makeTiptapHarness('doc-a');
const entry = mountTiptapEditor({
@@ -1217,7 +1244,7 @@ describe('CM6 cache — lifecycle', () => {
h.viewDom.scrollTop = 42;
parkCmEditor(entry);
- const suppression = acquireScrollRestoreSuppression(h.docName);
+ const suppression = acquireScrollRestoreSuppression(h.docName, 'landing');
const suppressed = makeNode();
mountCmEditor({
docName: h.docName,
@@ -1237,6 +1264,31 @@ describe('CM6 cache — lifecycle', () => {
expect(released.scrollTop).toBe(42);
});
+ test('mount: cache-hit still restores scroll while a NAVIGATION holds the scroller', () => {
+ // Source-mode twin of the TipTap case: a navigation has already written its
+ // position, and the parked scrollTop is that result. This write is a
+ // one-shot into a target at zero, so standing down for it drops the position
+ // rather than deferring it.
+ const h = makeCmHarness('cm-doc-a');
+ const entry = mountCmEditor({
+ docName: h.docName,
+ container: h.container as unknown as HTMLElement,
+ factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,
+ });
+ h.viewDom.scrollTop = 42;
+ parkCmEditor(entry);
+
+ acquireScrollRestoreSuppression(h.docName, 'navigation');
+ const held = makeNode();
+ mountCmEditor({
+ docName: h.docName,
+ container: held as unknown as HTMLElement,
+ factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,
+ });
+
+ expect(held.scrollTop).toBe(42);
+ });
+
test('evict: destroys view + provider + ydoc', () => {
const h = makeCmHarness('cm-doc-a');
mountCmEditor({
diff --git a/packages/app/src/editor/editor-cache.ts b/packages/app/src/editor/editor-cache.ts
index 38d47f5df..2cefae258 100644
--- a/packages/app/src/editor/editor-cache.ts
+++ b/packages/app/src/editor/editor-cache.ts
@@ -66,7 +66,7 @@ import { getMountId } from './mount-id-registry';
// module — keep it that way to preserve coordinated lifecycle between this
// V2 cache and the mount-promise cache.
import { invalidateMountPromise } from './mount-promise';
-import { isScrollRestoreSuppressed } from './scroll-restore-coordination';
+import { scrollSuppressionHolder } from './scroll-restore-coordination';
/**
* Read the per-editor Yjs UndoManager so the caller can null its `restore`
@@ -673,11 +673,18 @@ export function mountTiptapEditor(params: MountTiptapParams): TiptapCacheEntry {
reuse.activeMountKey = docName;
touchLru(tiptapLru, docName);
// Restore scroll AFTER DOM is re-attached (scrollTop on detached nodes
- // is a no-op in real browsers). Stand down when a mode-switch landing owns
+ // is a no-op in real browsers). Stand down when a mode-switch LANDING owns
// the scroller for this doc — this warm-mount restore fires at the same
// moment as a landing and would otherwise overwrite it with the parked
// position.
- if (!isScrollRestoreSuppressed(docName)) container.scrollTop = reuse.scrollTop;
+ //
+ // A navigation's hold does NOT stand it down. This write happens once, with
+ // no retry, into a reparent target sitting at scrollTop 0, so deferring to a
+ // writer that has already finished loses the position outright rather than
+ // postponing it. And the parked scrollTop IS a navigation's result whenever
+ // the navigation preceded the park, so writing it re-applies the very
+ // position the hold is defending.
+ if (scrollSuppressionHolder(docName) !== 'landing') container.scrollTop = reuse.scrollTop;
// Focus restore is gated on "had focus at park time". Blindly calling
// .focus() on every mount hijacks focus from keyboard users
// Tab-navigating through the sidebar and from deep-link cold loads
@@ -996,9 +1003,12 @@ export function mountCmEditor(params: MountCmParams): CmCacheEntry {
reparentCmDom(reuse, container);
reuse.activeMountKey = docName;
touchLru(cmLru, docName);
- // Stand down when a mode-switch landing owns the scroller for this doc, so
- // the warm-mount restore cannot overwrite the landing with the parked scroll.
- if (!isScrollRestoreSuppressed(docName)) container.scrollTop = reuse.scrollTop;
+ // Stand down when a mode-switch LANDING owns the scroller for this doc, so
+ // the warm-mount restore cannot overwrite the landing with the parked
+ // scroll. A navigation's hold does not stand it down, for the reason spelled
+ // out at the Tiptap reparent above: this write is a one-shot into a target
+ // at zero, and the parked position is the navigation's own result.
+ if (scrollSuppressionHolder(docName) !== 'landing') container.scrollTop = reuse.scrollTop;
if (reuse.hadFocus) {
try {
reuse.view.focus();
diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
index 9b1e0b3b7..dbd0a76ae 100644
--- a/packages/app/src/editor/extensions/markdown-lint-decorations.ts
+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
@@ -661,7 +661,7 @@ export const MarkdownLintDecorations = Extension.create<MarkdownLintDecorationsO
// landing that is itself an explicit navigation keeps the scroller
// and this click stands down whole, leaving the banked source-mode
// intent alive for the caller to replay.
- return runScrollNavigation(docName, () => {
+ return runScrollNavigation(docName, 'problems-row', () => {
view.dispatch(
view.state.tr.setSelection(
TextSelection.near(view.state.doc.resolve(blockOffset + 1)),
diff --git a/packages/app/src/editor/landing-controller.test.ts b/packages/app/src/editor/landing-controller.test.ts
index 7fba7d31c..89e395bb3 100644
--- a/packages/app/src/editor/landing-controller.test.ts
+++ b/packages/app/src/editor/landing-controller.test.ts
@@ -380,14 +380,18 @@ describe('startLanding — explicit navigation pre-emption', () => {
});
expect(container.scrollTop).toBe(2000 - TOOLBAR);
- const ran = runScrollNavigation('doc', () => {
+ const ran = runScrollNavigation('doc', 'outline', () => {
container.scrollTop = NAV_SCROLL_TOP;
});
expect(ran).toBe(true);
expect(container.scrollTop).toBe(NAV_SCROLL_TOP);
expect(outcomes).toEqual([{ status: 'cancelled', reason: 'superseded' }]);
- expect(isScrollRestoreSuppressed('doc')).toBe(false); // released before the scroll
+ // The superseded landing let go of the flag as it unwound; the only hold
+ // left is the navigation's own. Ref-counting is what makes this pair a leak
+ // check: a landing handle that survived its supersede would keep the count
+ // above zero even after the navigation released.
+ expect(isScrollRestoreSuppressed('doc')).toBe(true);
// The queued intent was already consumed to start this landing, so there is
// nothing stale left to replay — same as a user-scroll cancel.
expect(discard).not.toHaveBeenCalled();
@@ -399,6 +403,7 @@ describe('startLanding — explicit navigation pre-emption', () => {
vi.advanceTimersByTime(2000);
expect(container.scrollTop).toBe(NAV_SCROLL_TOP);
expect(outcomes).toHaveLength(1);
+ expect(isScrollRestoreSuppressed('doc')).toBe(false); // and neither hold leaked
});
test('does not persist the position it would have erased', () => {
@@ -410,7 +415,7 @@ describe('startLanding — explicit navigation pre-emption', () => {
intent: 'toggle',
});
- runScrollNavigation('doc', () => {
+ runScrollNavigation('doc', 'outline', () => {
container.scrollTop = NAV_SCROLL_TOP;
});
vi.advanceTimersByTime(2000);
@@ -435,7 +440,7 @@ describe('startLanding — explicit navigation pre-emption', () => {
});
const landingTarget = container.scrollTop;
- const ran = runScrollNavigation('doc', scroll);
+ const ran = runScrollNavigation('doc', 'outline', scroll);
// A jump has already placed the caret, so pre-empting it would split caret
// from viewport — the failure this contract exists to prevent.
@@ -459,7 +464,7 @@ describe('startLanding — explicit navigation pre-emption', () => {
onOutcome: (o) => outcomes.push(o),
});
- expect(runScrollNavigation('some-other-doc', () => {})).toBe(true);
+ expect(runScrollNavigation('some-other-doc', 'outline', () => {})).toBe(true);
expect(outcomes).toEqual([]);
vi.advanceTimersByTime(150);
@@ -477,7 +482,7 @@ describe('startLanding — explicit navigation pre-emption', () => {
vi.advanceTimersByTime(150); // land
const scroll = vi.fn();
- expect(runScrollNavigation('doc', scroll)).toBe(true);
+ expect(runScrollNavigation('doc', 'outline', scroll)).toBe(true);
expect(scroll).toHaveBeenCalledTimes(1);
});
});
@@ -500,7 +505,7 @@ describe('startLanding — a throwing measurer releases every hold', () => {
function expectHoldsReleased(): void {
expect(isScrollRestoreSuppressed('doc')).toBe(false);
const scroll = vi.fn();
- expect(runScrollNavigation('doc', scroll)).toBe(true);
+ expect(runScrollNavigation('doc', 'outline', scroll)).toBe(true);
expect(scroll).toHaveBeenCalledTimes(1);
}
diff --git a/packages/app/src/editor/landing-controller.ts b/packages/app/src/editor/landing-controller.ts
index 055b2ba0d..64cebac64 100644
--- a/packages/app/src/editor/landing-controller.ts
+++ b/packages/app/src/editor/landing-controller.ts
@@ -173,7 +173,7 @@ export function startLanding(params: StartLandingParams): LandingHandle {
} = params;
const contentColumn = params.contentColumn ?? container.firstElementChild;
- const suppression = acquireScrollRestoreSuppression(docName);
+ const suppression = acquireScrollRestoreSuppression(docName, 'landing');
const scrollOwner = registerLandingScrollOwner(docName, {
yieldsToNavigation: intent === 'toggle',
supersede: () => cancel('superseded'),
diff --git a/packages/app/src/editor/scroll-navigation-ownership.dom.test.tsx b/packages/app/src/editor/scroll-navigation-ownership.dom.test.tsx
new file mode 100644
index 000000000..112f007d4
--- /dev/null
+++ b/packages/app/src/editor/scroll-navigation-ownership.dom.test.tsx
@@ -0,0 +1,425 @@
+// @vitest-environment jsdom
+/**
+ * An explicit navigation is the document's single scroll writer while it lands —
+ * including against the editor container's own scroll-restore loop.
+ *
+ * The loop is armed on document activation and defends the position the reader
+ * was last at, re-applying it every animation frame until something stops it.
+ * Four things can: the suppression probe, its wheel/touchstart/mousedown/keydown
+ * listeners, its takeover test, and a ten-second backstop.
+ *
+ * Of those, only the takeover test is something a navigation trips by accident,
+ * and only in one direction. It fires on a scrollTop INCREASE, which has no
+ * browser-side explanation and is therefore safely attributable to someone else;
+ * a DECREASE is indistinguishable from the browser's shrink-clamp against a
+ * transient height, so the loop reads it as drift and corrects it. A navigation
+ * to a heading ABOVE the reader's position is exactly that shape, and gets
+ * erased frame after frame until the backstop expires — the row highlights, the
+ * view does not move, and then the same click starts working. (The direction
+ * heuristic itself is pinned in components/scroll-restore.test.ts; nothing here
+ * substitutes for that.)
+ *
+ * Which leaves the suppression probe as the one stop condition a navigation can
+ * reach deliberately, in either direction. `runScrollNavigation` is the producer
+ * that reaches it, precisely so that no caller has to know the population of
+ * scroll writers. These cases pin the whole of that promise for the whole of
+ * that population: the outline rows in both editor modes, deep-link anchors, the
+ * Problems-panel rows, raw-MDX navigation, find/replace matches.
+ *
+ * The probe is shared with readers that do NOT run every frame, so the last case
+ * covers the interleaving that makes those two populations different: a
+ * document re-activated while a navigation still holds gets one chance at a
+ * restore, and standing that one chance down leaves the reader at the top of the
+ * document rather than where they navigated to.
+ *
+ * Fidelity: the real `ScrollPreservingContainer`, its real restore loop, and the
+ * real coordination primitives. jsdom computes no layout, so scroll geometry is
+ * stubbed on the prototype the way the sibling suppression test does, and a
+ * direct scrollTop write stands in for `scrollIntoView`. The loop only ever
+ * observes the effect on scrollTop, so the stand-in is faithful to its inputs;
+ * a real smooth-scroll animation and real content-visibility materialization
+ * are above this rung.
+ */
+
+import { cleanup, render } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { ScrollPreservingContainer } from '@/components/EditorActivityPool';
+import {
+ __resetScrollRestoreCoordination,
+ acquireScrollRestoreSuppression,
+ registerLandingScrollOwner,
+ runScrollNavigation,
+} from '@/editor/scroll-restore-coordination';
+import { getCollector } from '@/lib/perf/collector';
+
+const DOC = 'notes/long-doubled-note';
+/** Where the restore loop believes the reader was — the position it defends. */
+const RESTORED_TOP = 4000;
+/** A heading ABOVE that position: the navigation the loop refuses to yield to. */
+const BACKWARD_TARGET = 500;
+/** A heading BELOW it: the direction the loop already reads as a takeover. */
+const FORWARD_TARGET = 4500;
+/** A downward-shaped move nobody claimed — the drift the loop exists to correct. */
+const UNCLAIMED_DRIFT = 1200;
+/** Generous ceiling on a navigation's hold, so the case does not encode the value. */
+const OWNERSHIP_LAPSES_WITHIN_MS = 2_000;
+
+const scrollTops = new WeakMap<HTMLElement, number>();
+/**
+ * The scroller's reach. Mutable so a case can make the content SHORTER than the
+ * saved position: the restore then writes its target but never counts as landed,
+ * which is the only state in which the loop reports its exit as an INCOMPLETE
+ * restore. A restore that already landed and was then taken over is a healthy
+ * one, so it reports the handover alone.
+ */
+let stubScrollHeight = 20_000;
+const CONTENT_TOO_SHORT_TO_LAND = 1_000;
+let origScrollTop: PropertyDescriptor | undefined;
+let origScrollHeight: PropertyDescriptor | undefined;
+let origClientHeight: PropertyDescriptor | undefined;
+
+function restoreDescriptor(
+ prop: 'scrollTop' | 'scrollHeight' | 'clientHeight',
+ desc: PropertyDescriptor | undefined,
+) {
+ if (desc) Object.defineProperty(HTMLElement.prototype, prop, desc);
+ else Reflect.deleteProperty(HTMLElement.prototype, prop);
+}
+
+beforeEach(() => {
+ // Frames are faked alongside timers so a case can advance the restore loop and
+ // outlive a navigation's hold with one call, whichever clock each rides on.
+ vi.useFakeTimers({
+ toFake: [
+ 'setTimeout',
+ 'clearTimeout',
+ 'setInterval',
+ 'clearInterval',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ ],
+ });
+ __resetScrollRestoreCoordination();
+ getCollector()?.reset();
+ stubScrollHeight = 20_000;
+ origScrollTop = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollTop');
+ origScrollHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollHeight');
+ origClientHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientHeight');
+ Object.defineProperty(HTMLElement.prototype, 'scrollTop', {
+ configurable: true,
+ get(this: HTMLElement) {
+ return scrollTops.get(this) ?? 0;
+ },
+ set(this: HTMLElement, value: number) {
+ scrollTops.set(this, value);
+ },
+ });
+ Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {
+ configurable: true,
+ get() {
+ return stubScrollHeight;
+ },
+ });
+ Object.defineProperty(HTMLElement.prototype, 'clientHeight', {
+ configurable: true,
+ get() {
+ return 800;
+ },
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ __resetScrollRestoreCoordination();
+ vi.useRealTimers();
+ restoreDescriptor('scrollTop', origScrollTop);
+ restoreDescriptor('scrollHeight', origScrollHeight);
+ restoreDescriptor('clientHeight', origClientHeight);
+});
+
+/** Let the restore loop take several turns, the way it does in the wild. */
+function letTheRestoreLoopRun(): void {
+ vi.advanceTimersByTime(100);
+}
+
+/** Outlive a navigation's hold on the scroller. */
+function lapseNavigationOwnership(): void {
+ vi.advanceTimersByTime(OWNERSHIP_LAPSES_WITHIN_MS);
+}
+
+/**
+ * The position the restore loop's re-apply branch reported forcing the scroller
+ * onto, or `undefined` when that branch never ran. Emitted by the loop itself,
+ * at most once per restore session — so a case reads production code's own
+ * account of what it did rather than inferring from a final scrollTop.
+ */
+function reappliedTarget(): unknown {
+ return getCollector()
+ ?.marks.toArray()
+ .find((m) => m.name === 'ok/scroll-restore/phase2-success')?.properties?.target;
+}
+
+/**
+ * How the loop attributed its own exit, or `undefined` when it did not report
+ * one. The field an operator reads to tell "someone else took the scroller" from
+ * "the restore never ran", so it has to name the writer that actually took it.
+ */
+function yieldedReason(): unknown {
+ return getCollector()
+ ?.marks.toArray()
+ .find((m) => m.name === 'ok/scroll-restore/yielded')?.properties?.reason;
+}
+
+/**
+ * The position the restore reported LANDING on in its synchronous first stage,
+ * or `undefined` when it never landed. What lets a case establish that a restore
+ * had already completed rather than assume it.
+ */
+function landedTarget(): unknown {
+ return getCollector()
+ ?.marks.toArray()
+ .find((m) => m.name === 'ok/scroll-restore/phase1-success')?.properties?.target;
+}
+
+/**
+ * The writer the loop named as having taken the scroller from it, or `undefined`
+ * when it recorded no handover. Unlike `yieldedReason` this is not conditioned
+ * on the restore having failed, because a named writer taking over is
+ * attributable either way.
+ */
+function supersededHolder(): unknown {
+ return getCollector()
+ ?.marks.toArray()
+ .find((m) => m.name === 'ok/scroll-restore/superseded')?.properties?.holder;
+}
+
+/**
+ * Mount the container active for `DOC`, restoring to `from`.
+ *
+ * No precondition assertion: a re-activation is exactly the moment a restore may
+ * legitimately be measured for NOT running, so the case has to be able to see a
+ * scroller left at zero rather than throw on it.
+ */
+function activate(from: number): HTMLDivElement {
+ const { container } = render(
+ <ScrollPreservingContainer isActive docName={DOC} mode="wysiwyg" initialScrollTop={from}>
+ <div>document body</div>
+ </ScrollPreservingContainer>,
+ );
+ const el = container.querySelector<HTMLDivElement>('[data-testid="editor-scroll-container"]');
+ if (!el) throw new Error('editor-scroll-container not rendered');
+ return el;
+}
+
+function mountWithLiveRestore(): HTMLDivElement {
+ const el = activate(RESTORED_TOP);
+ // Stage 1 of the restore ran synchronously inside the layout effect; the
+ // per-frame poll is now armed and defending this position.
+ if (el.scrollTop !== RESTORED_TOP) {
+ throw new Error(`harness precondition failed: restore did not seed ${RESTORED_TOP}`);
+ }
+ return el;
+}
+
+describe('an explicit navigation taken while the scroll-restore loop is live', () => {
+ test('survives when it moves the reader UP the document', () => {
+ const scroller = mountWithLiveRestore();
+
+ const ran = runScrollNavigation(DOC, 'outline', () => {
+ scroller.scrollTop = BACKWARD_TARGET;
+ });
+
+ expect(ran).toBe(true);
+ letTheRestoreLoopRun();
+ expect(scroller.scrollTop).toBe(BACKWARD_TARGET);
+ // The loop's re-apply branch names the position it forced. Silence here is
+ // the loop reporting that it never took the scroller back.
+ expect(reappliedTarget()).toBeUndefined();
+
+ // And it exits for GOOD on the handover rather than pausing for the length
+ // of the hold. A loop that only paused would resume against a baseline it
+ // never updated, read the navigation as drift, and re-apply the
+ // pre-navigation target the moment the hold lapsed — the same erasure,
+ // later. That is the property that lets the hold be brief rather than
+ // open-ended. Deterministic under fake timers: a loop that stood down has
+ // already cancelled its frame and its backstop, so this advance is inert.
+ lapseNavigationOwnership();
+ letTheRestoreLoopRun();
+ expect(scroller.scrollTop).toBe(BACKWARD_TARGET);
+ expect(reappliedTarget()).toBeUndefined();
+ });
+
+ test('survives when it moves the reader DOWN the document', () => {
+ // The other direction, and the direction that already worked. It does not
+ // reach the loop's takeover test from here — the hold is taken before the
+ // write, so the suppression probe wins the race whichever way the reader
+ // moves — so what this pins is that the hold covers both directions, not
+ // that the direction heuristic still works. That heuristic has its own
+ // cases, in components/scroll-restore.test.ts.
+ const scroller = mountWithLiveRestore();
+
+ const ran = runScrollNavigation(DOC, 'outline', () => {
+ scroller.scrollTop = FORWARD_TARGET;
+ });
+
+ expect(ran).toBe(true);
+ letTheRestoreLoopRun();
+ expect(scroller.scrollTop).toBe(FORWARD_TARGET);
+ expect(reappliedTarget()).toBeUndefined();
+ });
+
+ test('a refused navigation neither scrolls nor stands the restore down', () => {
+ const scroller = mountWithLiveRestore();
+ // A landing that is itself an explicit navigation does not yield: it has
+ // already placed the caret, so pre-empting it halfway would split caret and
+ // viewport.
+ registerLandingScrollOwner(DOC, { yieldsToNavigation: false, supersede: () => {} });
+
+ const ran = runScrollNavigation(DOC, 'outline', () => {
+ scroller.scrollTop = BACKWARD_TARGET;
+ });
+
+ expect(ran).toBe(false);
+ expect(scroller.scrollTop).toBe(RESTORED_TOP);
+
+ // Nothing was navigated to, so the loop still owns the scroller and still
+ // corrects drift on it. Standing it down here would cost the reader their
+ // place on top of the click that did nothing.
+ scroller.scrollTop = UNCLAIMED_DRIFT;
+ letTheRestoreLoopRun();
+ expect(scroller.scrollTop).toBe(RESTORED_TOP);
+ });
+
+ test('holds the scroller only while it lands, so the document restores again later', () => {
+ const scroller = mountWithLiveRestore();
+ runScrollNavigation(DOC, 'outline', () => {
+ scroller.scrollTop = BACKWARD_TARGET;
+ });
+ letTheRestoreLoopRun();
+
+ lapseNavigationOwnership();
+ cleanup();
+ getCollector()?.reset();
+
+ // Re-activating the document arms a fresh loop. A navigation that never let
+ // go would leave this one standing down for a click that finished a session
+ // ago, and the reader would silently lose scroll restore on this document
+ // from then on.
+ const reactivated = mountWithLiveRestore();
+ reactivated.scrollTop = UNCLAIMED_DRIFT;
+ letTheRestoreLoopRun();
+
+ expect(reactivated.scrollTop).toBe(RESTORED_TOP);
+ expect(reappliedTarget()).toBe(RESTORED_TOP);
+ });
+
+ test('a document re-activated INSIDE the hold still restores the reader', () => {
+ // The interleaving the cases above step over: each of them lapses the hold
+ // before it re-activates, which pins the after-the-window behavior and is
+ // blind to the inside-the-window one.
+ //
+ // The activation restore is not the per-frame loop. It reads the flag ONCE,
+ // inside a layout effect whose deps carry no signal that fires when a hold
+ // lapses, so standing it down is a restore that never happens rather than
+ // one that happens a moment later. And the pool hides an inactive Activity
+ // with display:none, which zeroes scrollTop before any layout effect can
+ // read it — so the skipped restore does not leave the reader where they
+ // were, it leaves them at the top.
+ const scroller = mountWithLiveRestore();
+ runScrollNavigation(DOC, 'outline', () => {
+ scroller.scrollTop = BACKWARD_TARGET;
+ });
+ letTheRestoreLoopRun();
+
+ // Switch away and back. Deliberately WITHOUT lapsing the hold: the window is
+ // wider than its constant suggests, since the deep-link ladder takes four
+ // overlapping holds and a hidden desktop window throttles the release timer.
+ cleanup();
+ getCollector()?.reset();
+ const reactivated = activate(BACKWARD_TARGET);
+
+ // Where the reader navigated to, not the top of the document.
+ expect(reactivated.scrollTop).toBe(BACKWARD_TARGET);
+ });
+
+ test('the loop reports WHO took the scroller, not a fixed holder', () => {
+ // `reason` is how an operator reading a trace answers "why did scroll
+ // restore stop here". Its siblings each name a real actor — the user, an
+ // unattributed external move — and this branch is probed before the
+ // takeover test, so it absorbs every navigation. Reported as a landing, it
+ // sends the reader to the landing controller to look for a mode-switch mark
+ // that was never emitted, for a stop whose cause was an outline click.
+ stubScrollHeight = CONTENT_TOO_SHORT_TO_LAND;
+ const scroller = mountWithLiveRestore();
+
+ runScrollNavigation(DOC, 'outline', () => {
+ scroller.scrollTop = BACKWARD_TARGET;
+ });
+ letTheRestoreLoopRun();
+
+ expect(yieldedReason()).toBe('navigation');
+ });
+
+ test('and reports a landing as a landing', () => {
+ // The same branch, the other holder — so the case above is pinning the value
+ // that gets reported rather than a constant that happens to have changed.
+ stubScrollHeight = CONTENT_TOO_SHORT_TO_LAND;
+ const scroller = mountWithLiveRestore();
+
+ acquireScrollRestoreSuppression(DOC, 'landing');
+ scroller.scrollTop = BACKWARD_TARGET;
+ letTheRestoreLoopRun();
+
+ expect(yieldedReason()).toBe('landing');
+ });
+
+ test('reports the handover even when the restore had already landed', () => {
+ // The two cases above have to starve the restore of content to hear it
+ // speak, because `yielded` is gated on a restore that never landed. That
+ // gate is silent for the common shape: a restore that landed and is
+ // re-applying its target frame after frame is exactly what a backward
+ // navigation collides with. Silent, the last thing such a session records
+ // is a phase-success — so a restore cut short by a named writer reads the
+ // same as one that ran undisturbed. The reasoning for saying it in a
+ // separate mark lives at the emission site.
+ const scroller = mountWithLiveRestore();
+ expect(landedTarget()).toBe(RESTORED_TOP);
+
+ runScrollNavigation(DOC, 'outline', () => {
+ scroller.scrollTop = BACKWARD_TARGET;
+ });
+ letTheRestoreLoopRun();
+
+ expect(supersededHolder()).toBe('navigation');
+ // Said in its own mark rather than by widening `yielded`, which means a
+ // restore that did not complete. This one completed before the navigation
+ // arrived, and counting it as incomplete would trade one attribution error
+ // for another.
+ expect(yieldedReason()).toBeUndefined();
+ });
+
+ test('and names a landing handover the same way', () => {
+ // The other holder through the same branch, so the case above pins the value
+ // being reported rather than a constant that happens to match it.
+ const scroller = mountWithLiveRestore();
+
+ acquireScrollRestoreSuppression(DOC, 'landing');
+ scroller.scrollTop = BACKWARD_TARGET;
+ letTheRestoreLoopRun();
+
+ expect(supersededHolder()).toBe('landing');
+ });
+
+ test('a document re-activated inside a LANDING still stands down', () => {
+ // The other half of the same distinction, and the reason the activation
+ // restore reads the holder rather than ignoring the flag outright: a landing
+ // is still placing a position, and will write one. Standing down for it
+ // keeps a single writer; standing down for a navigation loses the position
+ // outright.
+ acquireScrollRestoreSuppression(DOC, 'landing');
+
+ const reactivated = activate(RESTORED_TOP);
+
+ expect(reactivated.scrollTop).toBe(0);
+ });
+});
diff --git a/packages/app/src/editor/scroll-restore-coordination.test.ts b/packages/app/src/editor/scroll-restore-coordination.test.ts
index 97bda155f..96365d440 100644
--- a/packages/app/src/editor/scroll-restore-coordination.test.ts
+++ b/packages/app/src/editor/scroll-restore-coordination.test.ts
@@ -13,6 +13,7 @@
*/
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { getCollector } from '@/lib/perf/collector';
import {
__resetScrollRestoreCoordination,
acquireScrollRestoreSuppression,
@@ -22,11 +23,13 @@ import {
getDocScrollState,
isScrollRestoreSuppressed,
type LandingScrollOwner,
+ MAX_TRACKED_DECLINE_DOCS,
MAX_TRACKED_DOC_SCROLL,
registerLandingScrollOwner,
rememberDocScrollState,
runScrollNavigation,
scrollFraction,
+ scrollSuppressionHolder,
writeLandingResult,
} from './scroll-restore-coordination';
import type { EditorModeValue } from './use-editor-mode';
@@ -194,15 +197,15 @@ describe('scroll-restore suppression registry', () => {
});
test('acquiring a handle suppresses the document; releasing it re-enables restore', () => {
- const handle = acquireScrollRestoreSuppression('doc');
+ const handle = acquireScrollRestoreSuppression('doc', 'landing');
expect(isScrollRestoreSuppressed('doc')).toBe(true);
handle.release();
expect(isScrollRestoreSuppressed('doc')).toBe(false);
});
test('overlapping holders each keep suppression until all release', () => {
- const first = acquireScrollRestoreSuppression('doc');
- const second = acquireScrollRestoreSuppression('doc');
+ const first = acquireScrollRestoreSuppression('doc', 'landing');
+ const second = acquireScrollRestoreSuppression('doc', 'landing');
first.release();
expect(isScrollRestoreSuppressed('doc')).toBe(true); // second still holds
second.release();
@@ -210,8 +213,8 @@ describe('scroll-restore suppression registry', () => {
});
test('releasing the same handle twice does not underflow another holder', () => {
- const first = acquireScrollRestoreSuppression('doc');
- const second = acquireScrollRestoreSuppression('doc');
+ const first = acquireScrollRestoreSuppression('doc', 'landing');
+ const second = acquireScrollRestoreSuppression('doc', 'landing');
first.release();
first.release(); // idempotent — must not decrement second's hold
expect(isScrollRestoreSuppressed('doc')).toBe(true);
@@ -220,13 +223,86 @@ describe('scroll-restore suppression registry', () => {
});
test('suppression is scoped per document', () => {
- const handle = acquireScrollRestoreSuppression('a');
+ const handle = acquireScrollRestoreSuppression('a', 'landing');
expect(isScrollRestoreSuppressed('a')).toBe(true);
expect(isScrollRestoreSuppressed('b')).toBe(false);
handle.release();
});
});
+/**
+ * WHICH writer holds the scroller, not just whether one does.
+ *
+ * A reader that runs every frame stands down for either kind and looks again
+ * next frame. A reader that gets one chance — the container's activation
+ * restore, the cached editor's warm-reparent write — writes now or never, and
+ * the two kinds mean opposite things to it: a landing is going to write a
+ * position of its own, so deferring preserves one; a navigation has already
+ * written its position and is only defending it, so deferring loses one.
+ *
+ * Which makes RELEASE ORDER the property worth pinning. The two kinds overlap
+ * routinely (a navigation taken across a landing handover), and a registry that
+ * remembered only the most recent holder would answer `navigation` the moment a
+ * navigation released out from under a landing that still holds — handing the
+ * one-shot readers a green light in the middle of the settle window they exist
+ * to stay out of.
+ */
+describe('the holder behind a document suppression', () => {
+ test('nobody holds an unsuppressed document', () => {
+ expect(scrollSuppressionHolder('doc')).toBeNull();
+ });
+
+ test('each kind names itself', () => {
+ const landing = acquireScrollRestoreSuppression('doc', 'landing');
+ expect(scrollSuppressionHolder('doc')).toBe('landing');
+ landing.release();
+
+ const navigation = acquireScrollRestoreSuppression('doc', 'navigation');
+ expect(scrollSuppressionHolder('doc')).toBe('navigation');
+ navigation.release();
+ expect(scrollSuppressionHolder('doc')).toBeNull();
+ });
+
+ test('a landing outranks a navigation while both hold', () => {
+ const navigation = acquireScrollRestoreSuppression('doc', 'navigation');
+ const landing = acquireScrollRestoreSuppression('doc', 'landing');
+
+ // The landing is the one still placing a position, so it is the answer a
+ // one-shot reader needs: standing down for it still leaves the document
+ // somewhere deliberate.
+ expect(scrollSuppressionHolder('doc')).toBe('landing');
+
+ navigation.release();
+ expect(scrollSuppressionHolder('doc')).toBe('landing');
+ landing.release();
+ expect(scrollSuppressionHolder('doc')).toBeNull();
+ });
+
+ test('releasing one kind does not clear the other, in either order', () => {
+ const landingFirst = acquireScrollRestoreSuppression('doc', 'landing');
+ acquireScrollRestoreSuppression('doc', 'navigation');
+ landingFirst.release();
+ // A single last-writer-wins field would have been overwritten to 'landing'
+ // and then cleared outright here, losing the navigation still holding.
+ expect(scrollSuppressionHolder('doc')).toBe('navigation');
+ });
+
+ test('a handle issued before a reset cannot decrement what came after', () => {
+ // `__resetScrollRestoreCoordination` discards the counts a handle refers to.
+ // Releasing it afterwards must be inert rather than driving a later holder's
+ // count to zero and stealing a hold it never took.
+ const stale = acquireScrollRestoreSuppression('doc', 'landing');
+ __resetScrollRestoreCoordination();
+ const fresh = acquireScrollRestoreSuppression('doc', 'landing');
+
+ stale.release();
+
+ expect(scrollSuppressionHolder('doc')).toBe('landing');
+ fresh.release();
+ expect(scrollSuppressionHolder('doc')).toBeNull();
+ });
+});
+
describe('landing scroll owners and explicit navigation', () => {
/**
* Register a landing owner that behaves like the controller's: superseding it
@@ -246,7 +322,7 @@ describe('landing scroll owners and explicit navigation', () => {
test('an unowned scroller is free for a navigation', () => {
const scroll = vi.fn();
- expect(runScrollNavigation('doc', scroll)).toBe(true);
+ expect(runScrollNavigation('doc', 'outline', scroll)).toBe(true);
expect(scroll).toHaveBeenCalledTimes(1);
});
@@ -254,12 +330,12 @@ describe('landing scroll owners and explicit navigation', () => {
const superseded = ownLanding('doc', true);
const scroll = vi.fn();
- expect(runScrollNavigation('doc', scroll)).toBe(true);
+ expect(runScrollNavigation('doc', 'outline', scroll)).toBe(true);
expect(superseded()).toBe(1);
expect(scroll).toHaveBeenCalledTimes(1);
// Superseding released the registration, so the next navigation is free.
- expect(claimScrollerForNavigation('doc')).toBe(true);
+ expect(claimScrollerForNavigation('doc', 'find-match')).toBe(true);
expect(superseded()).toBe(1);
});
@@ -267,7 +343,7 @@ describe('landing scroll owners and explicit navigation', () => {
const superseded = ownLanding('doc', false);
const scroll = vi.fn();
- expect(runScrollNavigation('doc', scroll)).toBe(false);
+ expect(runScrollNavigation('doc', 'outline', scroll)).toBe(false);
expect(superseded()).toBe(0);
expect(scroll).not.toHaveBeenCalled();
@@ -277,7 +353,7 @@ describe('landing scroll owners and explicit navigation', () => {
const first = ownLanding('doc', true);
const second = ownLanding('doc', true);
- expect(runScrollNavigation('doc', () => {})).toBe(true);
+ expect(runScrollNavigation('doc', 'outline', () => {})).toBe(true);
expect(first()).toBe(1);
expect(second()).toBe(1);
@@ -289,7 +365,7 @@ describe('landing scroll owners and explicit navigation', () => {
const yielding = ownLanding('doc', true);
const holding = ownLanding('doc', false);
- expect(runScrollNavigation('doc', () => {})).toBe(false);
+ expect(runScrollNavigation('doc', 'outline', () => {})).toBe(false);
expect(yielding()).toBe(0);
expect(holding()).toBe(0);
@@ -299,18 +375,326 @@ describe('landing scroll owners and explicit navigation', () => {
const supersede = vi.fn();
const owner: LandingScrollOwner = { yieldsToNavigation: false, supersede };
const registration = registerLandingScrollOwner('doc', owner);
- expect(claimScrollerForNavigation('doc')).toBe(false);
+ expect(claimScrollerForNavigation('doc', 'find-match')).toBe(false);
registration.release();
registration.release(); // idempotent
- expect(claimScrollerForNavigation('doc')).toBe(true);
+ expect(claimScrollerForNavigation('doc', 'find-match')).toBe(true);
expect(supersede).not.toHaveBeenCalled();
});
test('ownership is scoped per document', () => {
ownLanding('a', false);
- expect(claimScrollerForNavigation('a')).toBe(false);
- expect(claimScrollerForNavigation('b')).toBe(true);
+ expect(claimScrollerForNavigation('a', 'find-match')).toBe(false);
+ expect(claimScrollerForNavigation('b', 'find-match')).toBe(true);
+ });
+});
+
+/**
+ * The OTHER writer.
+ *
+ * `runScrollNavigation` pre-empts the landings that own a document's scroller —
+ * but a landing is not the only thing that writes to it. The editor container's
+ * scroll-restore loop is a per-frame writer of its own, and it has four ways to
+ * stop: the suppression probe, its wheel/touchstart/mousedown/keydown listeners,
+ * its directional takeover test, and a wall-clock backstop.
+ *
+ * Only the first of those is reachable by a navigation toward the TOP of the
+ * document. The listeners answer to the user's own hands, the backstop is ten
+ * seconds away, and the takeover test fires on a scrollTop INCREASE only — a
+ * decrease is indistinguishable from the browser's shrink-clamp against a
+ * transient height, so the loop reads a backward navigation as drift and
+ * re-applies its own target over it, frame after frame, until the backstop
+ * expires. What the user sees is a row that highlights while nothing moves, and
+ * then the same click working some seconds later.
+ *
+ * Which of the two writers a given navigation collides with is not something a
+ * caller can know, which is the whole reason this precedence is enforced by the
+ * producer instead of by each writer remembering to ask. So the guarantee has to
+ * be delivered in full: routing a scroll through this module means EVERY scroll
+ * writer stands down for it, not just the one the module was built for first.
+ * The cases below pin that promise through the module's public predicate — the
+ * same one the restore loop reads.
+ */
+describe('an explicit navigation stands the scroll-restore loop down', () => {
+ /**
+ * Upper bound on how long a navigation may hold the flag.
+ *
+ * Not the implementation's value — a ceiling the contract has to respect. The
+ * restore loop exits for good on the first frame it sees the flag, so a hold
+ * measured in seconds buys nothing and costs the NEXT restore or landing for
+ * this document: they read the same flag, and would stand down for a
+ * navigation that finished long ago.
+ */
+ const OWNERSHIP_LAPSES_WITHIN_MS = 2_000;
+
+ /** The diagnostic mark that makes a refused navigation attributable. */
+ const NAVIGATION_DECLINED_MARK = 'ok/scroll-nav/declined';
+
+ beforeEach(() => {
+ // Frames are faked alongside timers so `lapseOwnership` covers a release on
+ // either clock. Date/performance stay real — nothing here asserts on the
+ // elapsed times the surrounding marks carry.
+ vi.useFakeTimers({
+ toFake: [
+ 'setTimeout',
+ 'clearTimeout',
+ 'setInterval',
+ 'clearInterval',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ ],
+ });
+ getCollector()?.reset();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ /** Let a navigation's hold on the scroller lapse, on whichever clock it rides. */
+ function lapseOwnership(): void {
+ vi.advanceTimersByTime(OWNERSHIP_LAPSES_WITHIN_MS);
+ }
+
+ /** A landing that refuses to be pre-empted, so every claim against it fails. */
+ function ownLandingThatNeverYields(docName: string): void {
+ registerLandingScrollOwner(docName, { yieldsToNavigation: false, supersede: () => {} });
+ }
+
+ function declinedNavigations(): unknown[] {
+ return (getCollector()?.marks.toArray() ?? [])
+ .filter((m) => m.name === NAVIGATION_DECLINED_MARK)
+ .map((m) => m.properties);
+ }
+
+ test('the restore loop is suppressed for the whole of the caller write', () => {
+ // Held BEFORE the write, not after: the loop measures on the frame it first
+ // sees the move, and a move it reads before the flag is a decrease to
+ // correct rather than a takeover to respect.
+ let suppressedDuringWrite: boolean | undefined;
+
+ const ran = runScrollNavigation('doc', 'outline', () => {
+ suppressedDuringWrite = isScrollRestoreSuppressed('doc');
+ });
+
+ expect(ran).toBe(true);
+ expect(suppressedDuringWrite).toBe(true);
+ });
+
+ test('the suppression outlives the call, because the loop measures a frame later', () => {
+ runScrollNavigation('doc', 'outline', () => {});
+
+ // A hold scoped to the synchronous callback would be gone before the loop
+ // ever looked, which is the same as never having held it at all.
+ expect(isScrollRestoreSuppressed('doc')).toBe(true);
+ });
+
+ test('and then lapses — a navigation borrows the scroller, it does not keep it', () => {
+ runScrollNavigation('doc', 'outline', () => {});
+
+ lapseOwnership();
+
+ // A hold that never lapses reads as "always suppressed" and disables scroll
+ // restore for this document for the rest of the session, which trades a
+ // ten-second dead click for a permanently dead restore.
+ expect(isScrollRestoreSuppressed('doc')).toBe(false);
+ });
+
+ test('successive navigations each release their own hold', () => {
+ runScrollNavigation('doc', 'outline', () => {});
+ runScrollNavigation('doc', 'outline', () => {});
+
+ lapseOwnership();
+
+ // Holders are ref-counted, so two acquisitions need two releases; a release
+ // that fired twice would underflow the count out from under whichever
+ // landing holds it next.
+ expect(isScrollRestoreSuppressed('doc')).toBe(false);
+ expect(runScrollNavigation('doc', 'outline', () => {})).toBe(true);
+ expect(isScrollRestoreSuppressed('doc')).toBe(true);
+ });
+
+ test('suppression is scoped to the navigated document', () => {
+ runScrollNavigation('doc', 'outline', () => {});
+
+ // The flag is per-document and so is the loop that reads it: navigating one
+ // editor must not stop a pooled sibling from restoring.
+ expect(isScrollRestoreSuppressed('other')).toBe(false);
+ });
+
+ test('the hold is taken before a superseded landing lets go of its own', () => {
+ // A landing releases its own suppression handle from inside `supersede`. A
+ // claim that acquired only afterwards would leave the count at zero across
+ // that unwind, and the landing's teardown re-enables the browser's scroll
+ // anchoring and runs its outcome callback inside exactly that gap — so the
+ // document must never read as unsuppressed mid-handover.
+ const landing = acquireScrollRestoreSuppression('doc', 'landing');
+ let suppressedDuringHandover: boolean | undefined;
+ registerLandingScrollOwner('doc', {
+ yieldsToNavigation: true,
+ supersede: () => {
+ landing.release();
+ suppressedDuringHandover = isScrollRestoreSuppressed('doc');
+ },
+ });
+
+ expect(runScrollNavigation('doc', 'outline', () => {})).toBe(true);
+
+ expect(suppressedDuringHandover).toBe(true);
+ });
+
+ test('a refused navigation suppresses nothing', () => {
+ ownLandingThatNeverYields('doc');
+
+ expect(runScrollNavigation('doc', 'outline', () => {})).toBe(false);
+
+ // Nothing scrolled, so there is nothing to defend — and standing the restore
+ // down here would turn a dead click into a dead click that also cost the
+ // reader their place.
+ expect(isScrollRestoreSuppressed('doc')).toBe(false);
+ });
+
+ test('a refused navigation is recorded, not silently swallowed', () => {
+ ownLandingThatNeverYields('doc');
+
+ expect(runScrollNavigation('doc', 'outline', () => {})).toBe(false);
+
+ // For the outline and raw-MDX seams the refusal is an outcome nobody
+ // downstream can see: they drop the boolean, so the row highlights, the
+ // caret may already have moved, and the view does not. The seam rides along
+ // because the other seams DO consume the boolean and retry, which makes the
+ // same event a dead click at one call site and a late one at another.
+ // `ownerCount` is a number, so it takes the count suffix this package uses
+ // for one: a bare plural in a mark payload is an array here, and an operator
+ // reading `owners: 2` would take it for a truncated list of who refused.
+ expect(declinedNavigations()).toEqual([
+ expect.objectContaining({ docName: 'doc', seam: 'outline', ownerCount: 1 }),
+ ]);
+ });
+
+ test('a completed navigation is not recorded as refused', () => {
+ runScrollNavigation('doc', 'outline', () => {});
+
+ expect(declinedNavigations()).toEqual([]);
+ });
+
+ test('a polling seam records one refusal episode, not one entry per attempt', () => {
+ // The comment reveal re-attempts on an 80ms ticker for ten seconds and the
+ // deep-link ladder retries a hundred times; marking each would bury the
+ // surrounding scroll-restore and mode-switch marks that identify WHICH
+ // landing refused, in the same ring, destroying the attribution this mark
+ // exists to provide.
+ ownLandingThatNeverYields('doc');
+
+ for (let attempt = 0; attempt < 25; attempt += 1) {
+ expect(runScrollNavigation('doc', 'deep-link', () => {})).toBe(false);
+ }
+
+ expect(declinedNavigations()).toHaveLength(1);
+ });
+
+ test('a second seam refused in the same window is recorded separately', () => {
+ // Collapsing a ladder must not collapse two different dead clicks into one:
+ // an outline row refused during a deep link is its own user-visible outcome.
+ ownLandingThatNeverYields('doc');
+
+ runScrollNavigation('doc', 'deep-link', () => {});
+ runScrollNavigation('doc', 'outline', () => {});
+
+ expect(declinedNavigations().map((p) => (p as { seam: string }).seam)).toEqual([
+ 'deep-link',
+ 'outline',
+ ]);
+ });
+
+ test('a navigation that gets through re-arms the next refusal', () => {
+ // The streak is what is being collapsed, and a successful claim ends it. A
+ // later refusal is a new episode the reader felt separately.
+ const registration = registerLandingScrollOwner('doc', {
+ yieldsToNavigation: false,
+ supersede: () => {},
+ });
+ runScrollNavigation('doc', 'outline', () => {});
+ registration.release();
+ expect(runScrollNavigation('doc', 'outline', () => {})).toBe(true);
+ ownLandingThatNeverYields('doc');
+
+ runScrollNavigation('doc', 'outline', () => {});
+
+ expect(declinedNavigations()).toHaveLength(2);
+ });
+
+ test('the refusal streak map does not grow without bound', () => {
+ // Every other registry in the module is bounded by construction: the saved
+ // scroll map caps, a suppression count self-deletes at zero, a landing
+ // registration self-deletes when its set empties. A streak entry is cleared
+ // only by a LATER navigation that succeeds on the same document, so one dead
+ // click on a document the reader never returns to would hold an entry for
+ // the rest of a session that walks hundreds of documents.
+ const first = 'doc-0';
+ ownLandingThatNeverYields(first);
+ // Two seams on the one document, because an entry is a SET of seams: what an
+ // eviction re-arms is every seam the dropped entry had marked, and a
+ // single-seam streak cannot tell that apart from one extra mark.
+ expect(runScrollNavigation(first, 'outline', () => {})).toBe(false);
+ expect(runScrollNavigation(first, 'deep-link', () => {})).toBe(false);
+
+ for (let i = 1; i <= MAX_TRACKED_DECLINE_DOCS; i += 1) {
+ const later = `doc-${i}`;
+ ownLandingThatNeverYields(later);
+ runScrollNavigation(later, 'outline', () => {});
+ }
+
+ runScrollNavigation(first, 'outline', () => {});
+ runScrollNavigation(first, 'deep-link', () => {});
+
+ // The least recently refused streak was dropped, so both of the first
+ // document's seams read as fresh episodes and mark again. Only a document
+ // nobody has navigated since pays that — the polling case above still
+ // collapses to one entry.
+ expect(
+ declinedNavigations().filter((props) => (props as { docName: string }).docName === first),
+ ).toHaveLength(4);
+ });
+
+ test('the bare claim carries the same guarantee', () => {
+ // The find/replace seam cannot scroll for itself: CodeMirror's search config
+ // asks for a scroll EFFECT and dispatches it, so that seam claims the
+ // scroller and hands the effect back. Same explicit navigation, same reader
+ // that has to stand down, and no way to reach the wrapper form to get it.
+ expect(claimScrollerForNavigation('doc', 'find-match')).toBe(true);
+ expect(isScrollRestoreSuppressed('doc')).toBe(true);
+
+ lapseOwnership();
+
+ expect(isScrollRestoreSuppressed('doc')).toBe(false);
+ });
+
+ test('a refused bare claim suppresses nothing', () => {
+ ownLandingThatNeverYields('doc');
+
+ expect(claimScrollerForNavigation('doc', 'find-match')).toBe(false);
+
+ expect(isScrollRestoreSuppressed('doc')).toBe(false);
+ });
+
+ test('a reset revokes a pending release, so it cannot cut short the next hold', () => {
+ // The hold rides a bare timer with no owner: every other piece of state in
+ // this module is dropped by some lifecycle, and a landing releases from its
+ // own teardown. Left armed across a reset, that timer fires into whatever
+ // counts exist by then and drops a hold it never took.
+ runScrollNavigation('doc', 'outline', () => {});
+
+ __resetScrollRestoreCoordination();
+ const landing = acquireScrollRestoreSuppression('doc', 'landing');
+ lapseOwnership();
+
+ // A landing holds until its own teardown says otherwise. A navigation from
+ // before the reset has no business ending it.
+ expect(isScrollRestoreSuppressed('doc')).toBe(true);
+ landing.release();
+ expect(isScrollRestoreSuppressed('doc')).toBe(false);
});
});
diff --git a/packages/app/src/editor/scroll-restore-coordination.ts b/packages/app/src/editor/scroll-restore-coordination.ts
index b9ad186c1..23a441a4e 100644
--- a/packages/app/src/editor/scroll-restore-coordination.ts
+++ b/packages/app/src/editor/scroll-restore-coordination.ts
@@ -9,11 +9,13 @@
* - the per-document saved-position map — a body-relative offset for a
* same-mode restore, the mode it was captured in, and a scroll fraction for
* a cross-mode proportional floor — plus its reader and writers,
- * - a ref-counted suppression registry that lets a landing become the single
- * scroll writer for a document while its settle window is open,
- * - the landing-owner registry and `runScrollNavigation`, the primitive every
- * explicit navigation scrolls through so it PRE-EMPTS an in-flight landing
- * instead of being erased by it.
+ * - a ref-counted suppression registry that lets a landing — or an explicit
+ * navigation — become the single scroll writer for a document while its
+ * window is open, and that names WHICH of the two holds it, because a
+ * reader with only one chance to write has to tell them apart,
+ * - the landing-owner registry, and the navigation primitives every explicit
+ * navigation scrolls through so it stands BOTH of those writers down
+ * instead of being erased by whichever one it did not tell.
*
* Keeping this state in one module — rather than duplicating it in the landing
* controller — is what makes the reconciliation honest: both writers read and
@@ -23,6 +25,7 @@
*/
import { measureAnchor } from '@/components/scroll-restore';
+import { mark } from '@/lib/perf/mark';
import type { EditorModeValue } from './use-editor-mode';
/**
@@ -143,35 +146,103 @@ export function writeLandingResult(params: {
}
/**
- * Ref-counted set of documents whose scroll-restore is currently suppressed. A
- * landing acquires a handle for the whole of its settle window so the
- * container's two-stage restore stands down and the landing is the single
- * scroll writer. Ref-counting tolerates overlapping holders (a re-dispatch that
- * briefly overlaps its predecessor) without one release re-enabling the restore
- * while another landing is still open.
+ * The kind of writer holding a document's scroller, and the reason this
+ * registry answers more than yes/no.
+ *
+ * A LANDING is PLACING a position: it has a target, it re-verifies that target
+ * on every layout signal, and it writes the result into the saved-position map
+ * when it settles. Standing down for one defers to a writer that is going to
+ * leave the document somewhere deliberate.
+ *
+ * A NAVIGATION has ALREADY written its position and is only defending it for a
+ * brief hold. Nothing further is coming from it.
+ *
+ * That difference decides what a reader which runs ONCE should do. A per-frame
+ * reader stands down for either and looks again next frame. A one-shot reader —
+ * the container's activation restore, the cached editor's warm-reparent write —
+ * has no next frame: it writes now or it never writes at all. Deferring to a
+ * landing is safe there, because the landing supplies a position of its own.
+ * Deferring to a navigation is not: nobody else will write one, and both of
+ * those surfaces start from a scroller sitting at zero.
+ */
+export type ScrollHolder = 'landing' | 'navigation';
+
+/**
+ * Per-document suppression counts, kept PER HOLDER KIND rather than as one
+ * total.
+ *
+ * Ref-counting is what tolerates overlapping holders (a re-dispatch that briefly
+ * overlaps its predecessor; a navigation taken across a landing handover)
+ * without one release re-enabling the restore while another holder is still
+ * open. Counting each kind separately is what keeps "which kind holds it"
+ * correct under those overlaps whatever the RELEASE ORDER turns out to be: a
+ * single last-writer-wins field would report `navigation` the moment a
+ * navigation released out from under a landing that still holds.
*/
-const suppressedDocs = new Map<string, number>();
+interface SuppressionCounts {
+ landing: number;
+ navigation: number;
+}
+
+const suppressedDocs = new Map<string, SuppressionCounts>();
+
+/**
+ * Bumped by `__resetScrollRestoreCoordination`. A handle issued before a reset
+ * refers to counts that no longer exist, so releasing it afterwards has to be
+ * inert rather than decrementing whatever a later holder put in their place.
+ */
+let registryGeneration = 0;
interface ScrollRestoreSuppressionHandle {
release(): void;
}
-export function acquireScrollRestoreSuppression(docName: string): ScrollRestoreSuppressionHandle {
- suppressedDocs.set(docName, (suppressedDocs.get(docName) ?? 0) + 1);
+export function acquireScrollRestoreSuppression(
+ docName: string,
+ holder: ScrollHolder,
+): ScrollRestoreSuppressionHandle {
+ const counts = suppressedDocs.get(docName) ?? { landing: 0, navigation: 0 };
+ counts[holder] += 1;
+ suppressedDocs.set(docName, counts);
+ const generation = registryGeneration;
let released = false;
return {
release() {
if (released) return; // idempotent: a double release must not underflow the count
released = true;
- const remaining = (suppressedDocs.get(docName) ?? 0) - 1;
- if (remaining > 0) suppressedDocs.set(docName, remaining);
- else suppressedDocs.delete(docName);
+ if (generation !== registryGeneration) return; // the counts this held were discarded
+ const live = suppressedDocs.get(docName);
+ if (!live) return;
+ live[holder] = Math.max(0, live[holder] - 1);
+ if (live.landing === 0 && live.navigation === 0) suppressedDocs.delete(docName);
},
};
}
+/**
+ * Which kind of writer holds this document's scroller, or null when none does.
+ *
+ * A landing outranks a navigation while both hold, because it is the one still
+ * placing a position: a one-shot reader that stands down for it ends up with a
+ * deliberate position written by someone, which is the property it stood down
+ * to preserve in the first place.
+ */
+export function scrollSuppressionHolder(docName: string): ScrollHolder | null {
+ const counts = suppressedDocs.get(docName);
+ if (!counts) return null;
+ if (counts.landing > 0) return 'landing';
+ if (counts.navigation > 0) return 'navigation';
+ return null;
+}
+
+/**
+ * Whether ANY writer holds this document's scroller. The predicate for a reader
+ * that runs every frame: it stands down for whoever holds it and looks again on
+ * the next one, so it never needs to know which. A reader that gets a single
+ * chance wants `scrollSuppressionHolder` instead.
+ */
export function isScrollRestoreSuppressed(docName: string): boolean {
- return (suppressedDocs.get(docName) ?? 0) > 0;
+ return scrollSuppressionHolder(docName) !== null;
}
/**
@@ -225,23 +296,188 @@ export function registerLandingScrollOwner(
}
/**
- * Take the document's scroller for an explicit navigation, pre-empting every
- * landing that yields. Returns false when a landing that does not yield still
- * owns it, in which case the caller must not scroll — see `runScrollNavigation`,
- * which is the form to reach for. This bare form exists for the one seam that
- * cannot perform its own scroll: CodeMirror's `scrollToMatch` returns a scroll
- * effect for the search extension to dispatch rather than scrolling itself.
+ * How long an explicit navigation keeps the scroller after claiming it.
+ *
+ * Long enough for the scroll-restore loop to see the flag on its next frame and
+ * stand down (it exits for good at that point), short enough that the flag's
+ * softer readers — the agent-follow scroll and the composer's bottom pin — are
+ * barely affected. A hold scoped to the caller's synchronous write would be gone
+ * before any of them looked, which is indistinguishable from never having held
+ * it.
+ *
+ * This is the length of ONE hold, not of every window a seam can produce. A seam
+ * that re-claims on a cadence shorter than this chains them into one unbroken
+ * stretch. The deep-link follow-up ladder and the comment-reveal settle ticker
+ * each run to a bound of their own, so their chains end without the reader doing
+ * anything. The find seam has none: `scrollToMatch` re-claims on every search
+ * entry point, so a reader stepping through matches holds the scroller for as
+ * long as they keep stepping, plus one more window. Size a change to this
+ * constant against the chained window a seam actually produces, not against
+ * 600ms.
+ *
+ * The one-shot readers that start from a scroller sitting at zero are NOT on the
+ * softer-readers list, and cannot be traded against by shortening this: they gate
+ * on a `'landing'` holder, so no value of this constant reaches them. The caret
+ * reveal is the one one-shot reader deliberately left on the plain boolean — it
+ * starts from wherever the reader already is, so dropping it costs a caret
+ * scroll rather than stranding anyone at the top, and revealing a caret would
+ * fight the place the user just asked for.
+ */
+const NAVIGATION_OWNERSHIP_MS = 600;
+
+/**
+ * Which seam asked for a navigation.
+ *
+ * Carried on the refusal mark so a refused navigation is attributable to the
+ * click that produced it, which matters because the seams differ in what a
+ * refusal COSTS. `outline`, `raw-mdx` and `find-match` drop the answer and have
+ * no recovery, so a refusal there is a dead click. `deep-link`, `comment-reveal`
+ * and `problems-row` consume the answer and try again, so a refusal there is a
+ * delay.
+ */
+export type NavigationSeam =
+ | 'outline'
+ | 'deep-link'
+ | 'problems-row'
+ | 'raw-mdx'
+ | 'find-match'
+ | 'comment-reveal';
+
+/**
+ * A navigation the scroller refused to hand over.
+ *
+ * The seams that drop the claim's answer treat it as an action rather than a
+ * question, so for them the refusal is an outcome nobody downstream can observe:
+ * a row highlights, the caret may already have moved, and the view does not.
+ * That is why the mark carries the seam — the same event means a dead click at
+ * one call site and a late one at another. `NavigationSeam` is where the split
+ * is written down.
+ */
+const NAVIGATION_DECLINED_MARK = 'ok/scroll-nav/declined';
+
+/**
+ * Seams whose refusal has already been marked, per document, since the last
+ * navigation that got through.
+ *
+ * Two of the consuming seams poll: the comment reveal re-runs its attempt on an
+ * 80ms ticker for ten seconds, and the deep-link ladder retries a hundred times
+ * at 100ms. Marking every tick would emit a hundred byte-identical entries, and
+ * both of the places a mark lands are worse for it.
+ *
+ * In a PRODUCTION build a mark is one `performance.measure` call. The user
+ * timing buffer it appends to has no size limit and nothing in this app ever
+ * calls `clearMeasures`, so the flood is buffer growth the session never gets
+ * back — a cost that is paid whether or not anyone is looking. In a DEV build it
+ * also fills the trace ring, evicting the surrounding scroll-restore and
+ * mode-switch marks, which are the only way to identify WHICH landing refused:
+ * there the flood destroys the very attribution the mark exists for.
+ *
+ * So the mark counts EPISODES, not attempts: one per unbroken run of refusals
+ * per seam, re-armed by the next navigation that succeeds on that document.
+ */
+const markedDeclines = new Map<string, Set<NavigationSeam>>();
+
+/**
+ * How many documents may carry a refusal streak at once.
+ *
+ * An entry is created by a refusal and cleared only by a LATER navigation that
+ * succeeds on the same document, so a document that is clicked once, refused,
+ * and never navigated again would hold one for the rest of the session. Capped
+ * for the same reason `MAX_TRACKED_DOC_SCROLL` is, and far lower, because a
+ * streak is only meaningful while the reader is still clicking around that
+ * document. An entry is a SET of seams, so dropping the least recently refused
+ * one re-arms every seam it had already marked — at most one extra mark per
+ * seam — on a document nobody has navigated in a long time.
+ */
+export const MAX_TRACKED_DECLINE_DOCS = 32;
+
+function shouldMarkDecline(docName: string, seam: NavigationSeam): boolean {
+ const marked = markedDeclines.get(docName) ?? new Set<NavigationSeam>();
+ markedDeclines.delete(docName); // re-insert last → LRU order for eviction
+ markedDeclines.set(docName, marked);
+ if (markedDeclines.size > MAX_TRACKED_DECLINE_DOCS) {
+ const oldest = markedDeclines.keys().next().value;
+ if (oldest !== undefined) markedDeclines.delete(oldest);
+ }
+ if (marked.has(seam)) return false;
+ marked.add(seam);
+ return true;
+}
+
+/**
+ * Pending hold releases, so `__resetScrollRestoreCoordination` can revoke them.
+ *
+ * Every other piece of state in this module is revocable by some lifecycle — a
+ * landing releases its suppression and its owner registration from `teardown`.
+ * A hold's release rides a bare timer with no owner, so without this set a timer
+ * armed before a reset would fire afterwards against unrelated counts.
*/
-export function claimScrollerForNavigation(docName: string): boolean {
+const navigationHoldTimers = new Set<ReturnType<typeof setTimeout>>();
+
+/** Stand the document's scroll writers down for a navigation, briefly. */
+function holdScrollerForNavigation(docName: string): void {
+ const suppression = acquireScrollRestoreSuppression(docName, 'navigation');
+ const timer = setTimeout(() => {
+ navigationHoldTimers.delete(timer);
+ suppression.release();
+ }, NAVIGATION_OWNERSHIP_MS);
+ navigationHoldTimers.add(timer);
+}
+
+/**
+ * Take the document's scroller for an explicit navigation: stand its other
+ * scroll writers down and pre-empt every landing that yields. Returns false when
+ * a landing that does not yield still owns it, in which case the caller must not
+ * scroll — see `runScrollNavigation`, which is the form to reach for. This bare
+ * form exists for the one seam that cannot perform its own scroll: CodeMirror's
+ * `scrollToMatch` returns a scroll effect for the search extension to dispatch
+ * rather than scrolling itself.
+ *
+ * BOTH writers are told, because a caller cannot know which one it is about to
+ * collide with. Landings are pre-empted through their registry; the pool's
+ * scroll-restore loop is stood down through the suppression count it polls every
+ * frame. Told only about the landing, that loop does NOT yield to a navigation
+ * toward the TOP of the document: its takeover test is directional, and a
+ * scrollTop decrease is indistinguishable from the browser's shrink-clamp, so it
+ * re-applies its own target over the navigation's, frame after frame, until its
+ * ten-second backstop expires. That is why a heading above the current view did
+ * nothing for click after click and then suddenly worked — the clicks were not
+ * accumulating, the backstop was running out.
+ *
+ * What the hold deliberately does NOT stand down are the readers that get a
+ * single chance to write: the container's activation restore and the cached
+ * editor's warm-reparent write. Those gate on a `'landing'` holder, because a
+ * landing supplies a position of its own while a navigation has already supplied
+ * one — a one-shot reader that deferred to this hold would drop the position
+ * rather than defer it, and both of those surfaces start from a scroller at
+ * zero. See `ScrollHolder` for the whole of that distinction.
+ *
+ * The hold is taken BEFORE the landings are superseded: `supersede` unwinds a
+ * landing, releasing its own suppression handle and then handing control to its
+ * outcome callback, so taking ours first keeps the count from dipping to zero
+ * across the handover. A refused claim takes no hold at all — nothing scrolled,
+ * so there is nothing to defend, and suppressing anyway would cost the reader
+ * their place on top of the click that did nothing.
+ */
+export function claimScrollerForNavigation(docName: string, seam: NavigationSeam): boolean {
const owners = landingScrollOwners.get(docName);
- if (!owners) return true;
- for (const owner of owners) {
- if (!owner.yieldsToNavigation) return false;
+ // Snapshot before anything unwinds: `supersede` releases the registration, and
+ // a landing that registers a successor while unwinding would otherwise be
+ // superseded in the same pass by the navigation that had already claimed the
+ // scroller.
+ const superseding = owners ? Array.from(owners) : [];
+ for (const owner of superseding) {
+ if (!owner.yieldsToNavigation) {
+ if (shouldMarkDecline(docName, seam)) {
+ mark(NAVIGATION_DECLINED_MARK, { docName, seam, ownerCount: superseding.length });
+ }
+ return false;
+ }
}
- // Snapshot first: `supersede` releases the registration, and a landing that
- // registers a successor while unwinding would otherwise be superseded in the
- // same pass by the navigation that had already claimed the scroller.
- const superseding = Array.from(owners);
+ // The scroller was available, so any refusal streak on this document is over
+ // and the next one is a new episode worth marking.
+ markedDeclines.delete(docName);
+ holdScrollerForNavigation(docName);
for (const owner of superseding) owner.supersede();
return true;
}
@@ -251,24 +487,38 @@ export function claimScrollerForNavigation(docName: string): boolean {
* Problems-panel row click, a find/replace match, a deep-link anchor.
*
* Every such navigation goes through here rather than reaching for
- * `scrollIntoView` directly, so the precedence against an in-flight landing is
- * enforced by this producer instead of by each writer remembering to ask. That
- * is the difference that matters: a writer that forgets to poll silently opts
- * out of the contract, which is how a landing came to erase the source-mode
- * Problems-row jump. Put the navigation's selection write inside `scroll` too —
- * caret and viewport should move together or not at all.
+ * `scrollIntoView` directly, so the precedence against the document's other
+ * scroll writers is enforced by this producer instead of by each writer
+ * remembering to ask. That is the difference that matters: a writer that forgets
+ * to poll silently opts out of the contract, which is how a landing came to
+ * erase the source-mode Problems-row jump. Put the navigation's selection write
+ * inside `scroll` too — caret and viewport should move together or not at all.
+ *
+ * The claim is taken before `scroll` runs and held past this call, because the
+ * restore loop measures a frame later: a move it reads before the flag is drift
+ * to correct rather than a takeover to respect.
*
* Returns whether the navigation ran.
*/
-export function runScrollNavigation(docName: string, scroll: () => void): boolean {
- if (!claimScrollerForNavigation(docName)) return false;
+export function runScrollNavigation(
+ docName: string,
+ seam: NavigationSeam,
+ scroll: () => void,
+): boolean {
+ if (!claimScrollerForNavigation(docName, seam)) return false;
scroll();
return true;
}
/** Test-only: clear all coordination state between cases. */
export function __resetScrollRestoreCoordination(): void {
+ // Cancelled first, and the generation bumped last, so a hold armed by the
+ // previous case can neither fire nor decrement a count belonging to the next.
+ for (const timer of navigationHoldTimers) clearTimeout(timer);
+ navigationHoldTimers.clear();
+ markedDeclines.clear();
docScrollState.clear();
suppressedDocs.clear();
landingScrollOwners.clear();
+ registryGeneration += 1;
}
diff --git a/packages/app/src/lib/perf/mark.ts b/packages/app/src/lib/perf/mark.ts
index ef7d86cd2..b4b7fe1b2 100644
--- a/packages/app/src/lib/perf/mark.ts
+++ b/packages/app/src/lib/perf/mark.ts
@@ -8,9 +8,9 @@
*
* Naming convention: `ok/<subsystem>/<event>` where subsystem is
* one of `nav`, `sync`, `activity`, `render`, `editor`, `sidebar`, `outline`,
- * `vitals`, `mount`, `cold`, `startup`, `scroll-restore`. `validatePerfMarkName` is a dev-only lint of the
- * shape; it `console.warn`s in dev and returns silently so emission is always
- * best-effort.
+ * `vitals`, `mount`, `cold`, `startup`, `scroll-restore`, `scroll-nav`.
+ * `validatePerfMarkName` is a dev-only lint of the shape; it `console.warn`s in
+ * dev and returns silently so emission is always best-effort.
*
* Production cost is one `performance.measure` call. The collector push is
* `no-op` in non-DEV builds (see `collector.ts`).
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index dfd95ef49..d7a845280 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,4 +1,3 @@
-
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 8bfdb40cd..005627195 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,4 +1,3 @@
-
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index 2a597ec3d..f4cc8a286 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,4 +1,3 @@
-
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/divergence-locate.ts b/packages/core/src/bridge/divergence-locate.ts
index d979f4b39..6b505314d 100644
--- a/packages/core/src/bridge/divergence-locate.ts
+++ b/packages/core/src/bridge/divergence-locate.ts
@@ -1,4 +1,3 @@
-
import { findFirstDivergenceIndex } from './tolerance-telemetry.ts';
export const BRIDGE_LINE_KINDS = [
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 01ef76a9f..8fb428b90 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,4 +1,3 @@
-
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 463e89595..9d9c244b0 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,4 +1,3 @@
-
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.ts
index 0939885bb..c43fdd7e7 100644
--- a/packages/core/src/bridge/intraline-predicate.ts
+++ b/packages/core/src/bridge/intraline-predicate.ts
@@ -1,4 +1,3 @@
-
export function rawLineCounts(doc: string): Map<string, number> {
const counts = new Map<string, number>();
for (const line of doc.split('\n')) {
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index c0dc65705..251560a35 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -65,7 +65,6 @@ export function tryLineLevelCombine(
return { clean: true, merged };
}
-
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index dcc5b0690..01ac80099 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,4 +1,3 @@
-
import { stripFrontmatter } from '../extensions/frontmatter.ts';
import { bodyEdgeEmpties } from './doc-boundary-space.ts';
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 4f7b79587..bb53e7c7c 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,7 +32,6 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
-
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -129,7 +128,6 @@ export interface ComparePmStructuralOptions {
rawSourceSide?: 'expected';
}
-
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -255,7 +253,6 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
-
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index dca644141..af20de1e2 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,4 +1,3 @@
-
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index a363dfd54..83d47404a 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,4 +1,3 @@
-
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.ts
index 4499dbc92..9807a7e82 100644
--- a/packages/core/src/markdown/code-fence.ts
+++ b/packages/core/src/markdown/code-fence.ts
@@ -1,4 +1,3 @@
-
export function selectFenceChar(info: string): '`' | '~' {
return info.includes('`') ? '~' : '`';
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 34704165b..7415c474a 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index b6299a948..ece5c02a1 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,4 +1,3 @@
-
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index acd398aa6..54774764a 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.ts
index ba9b56384..43ecdc709 100644
--- a/packages/core/src/markdown/div-align-promoter.ts
+++ b/packages/core/src/markdown/div-align-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index 4513da9bb..6d3f3643e 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,4 +1,3 @@
-
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 6931623c7..00f5771ee 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,4 +1,3 @@
-
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
-
interface GfmExample {
section: string;
markdown: string;
@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
-
interface MdxCrashEntry {
id: string;
input: string;
@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
-
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
-
export interface NgPinnedCase {
id: string;
name: string;
@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
-
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index daa3ef82b..8b1eb8519 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,4 +1,3 @@
-
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
-
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
-
const WORDS = [
'lorem',
'ipsum',
@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
-
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
-
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 32c055c5b..420dc0fe5 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,7 +7,6 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
-
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 283913255..2653473da 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,4 +1,3 @@
-
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index 5d1000cc4..da0a81d23 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 9681c0056..787315157 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,4 +1,3 @@
-
import type { Element as HastElement, Root as HastRoot } from 'hast';
import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -129,8 +128,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified()
- .use(rehypeParse, { fragment: true });
+ const processor = unified().use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 994eb6917..706fa9afb 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index ec1ac1b7e..779e27500 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -207,7 +206,6 @@ export class MarkdownManager {
}
}
-
const registry = createRegistry();
function destructureAttrs(
@@ -256,7 +254,6 @@ function destructureAttrs(
return result;
}
-
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -279,7 +276,6 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
-
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -348,7 +344,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
-
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -601,7 +596,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -682,7 +676,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -980,7 +973,6 @@ function buildMdastToPmHandlers(
};
}
-
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1106,7 +1098,6 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
-
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.ts
index b79e9aef7..fa0be9e86 100644
--- a/packages/core/src/markdown/lint/applies-to.ts
+++ b/packages/core/src/markdown/lint/applies-to.ts
@@ -1,4 +1,3 @@
-
import picomatch from 'picomatch';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.ts
index 94b34dee1..312c9c74b 100644
--- a/packages/core/src/markdown/lint/config-files.ts
+++ b/packages/core/src/markdown/lint/config-files.ts
@@ -1,4 +1,3 @@
-
const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([
'.markdownlint.json',
'.markdownlint.jsonc',
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index 7c54c0a73..cc667b93e 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -52,7 +52,6 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
-
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index a51f2ffb0..d48eea5e4 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,7 +6,6 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
-
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
index 9c9542661..ef478e268 100644
--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
@@ -1,4 +1,3 @@
-
import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';
export interface FrontmatterFieldConstraint {
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index b0e7833fd..5f953d667 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -1,4 +1,3 @@
-
import Ajv, { type ValidateFunction } from 'ajv';
import Ajv2019 from 'ajv/dist/2019.js';
import Ajv2020 from 'ajv/dist/2020.js';
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index 26fbc2b22..781226a5d 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,4 +1,3 @@
-
import type { LintPluginFailureReporter } from './plugin-failure.ts';
import { isLintPluginSelected, LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
@@ -80,8 +79,7 @@ function renderErrorMessage(error: unknown, depth = 0): string {
try {
const json = JSON.stringify(error);
if (json !== undefined) return json;
- } catch {
- }
+ } catch {}
}
return String(error);
}
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
index f438f1b16..7a5af097e 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
@@ -1,4 +1,3 @@
-
import type { OkfRuleId } from '../okf-rule-meta.ts';
import { fileNameFor, OKF_SCHEMA_DIR, okfSchemaPathFor } from './paths.ts';
import { OKF_FRONTMATTER_REGISTRY } from './registry.ts';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
index c290b6878..1ee913527 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
@@ -1,4 +1,3 @@
-
import type { OkfRuleId } from '../okf-rule-meta.ts';
export const OKF_SCHEMA_DIR = '.ok/okf';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
index 53ecb619d..f325fbbb4 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
@@ -1,4 +1,3 @@
-
import { compileAppliesTo } from '../applies-to.ts';
import { validateFrontmatterSource } from '../frontmatter-validate.ts';
import {
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
index 89845d3d5..f1c37671b 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
@@ -1,4 +1,3 @@
-
// file-level form is deliberate: the sibling `biome-ignore` must sit on the line
// oxlint-disable unicorn/no-thenable
diff --git a/packages/core/src/markdown/lint/okf-project/rules.ts b/packages/core/src/markdown/lint/okf-project/rules.ts
index 8b476332e..6d691ae2b 100644
--- a/packages/core/src/markdown/lint/okf-project/rules.ts
+++ b/packages/core/src/markdown/lint/okf-project/rules.ts
@@ -1,4 +1,3 @@
-
import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';
import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from '../okf-rule-meta.ts';
diff --git a/packages/core/src/markdown/lint/okf-rule-meta.ts b/packages/core/src/markdown/lint/okf-rule-meta.ts
index 44913a9dc..4de50d79f 100644
--- a/packages/core/src/markdown/lint/okf-rule-meta.ts
+++ b/packages/core/src/markdown/lint/okf-rule-meta.ts
@@ -1,4 +1,3 @@
-
export const OKF_RULE_IDS = [
'no-wiki-links',
'log-shape',
diff --git a/packages/core/src/markdown/lint/okf-rules.ts b/packages/core/src/markdown/lint/okf-rules.ts
index d0999b62e..1d5538421 100644
--- a/packages/core/src/markdown/lint/okf-rules.ts
+++ b/packages/core/src/markdown/lint/okf-rules.ts
@@ -1,4 +1,3 @@
-
import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from './okf-rule-meta.ts';
import type { OkfRule } from './okf-runner.ts';
import { indexShape } from './rules/index-shape.ts';
diff --git a/packages/core/src/markdown/lint/okf-runner.ts b/packages/core/src/markdown/lint/okf-runner.ts
index fabb08d6e..de130e3f4 100644
--- a/packages/core/src/markdown/lint/okf-runner.ts
+++ b/packages/core/src/markdown/lint/okf-runner.ts
@@ -1,4 +1,3 @@
-
import type { Root } from 'mdast';
import remarkFrontmatter from 'remark-frontmatter';
import remarkGfm from 'remark-gfm';
diff --git a/packages/core/src/markdown/lint/plugin-failure.ts b/packages/core/src/markdown/lint/plugin-failure.ts
index 1cd0d2543..e7d694890 100644
--- a/packages/core/src/markdown/lint/plugin-failure.ts
+++ b/packages/core/src/markdown/lint/plugin-failure.ts
@@ -1,4 +1,3 @@
-
import type { LintPluginId } from './types.ts';
export interface LintPluginFailure {
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index 1dae8316d..e7455ccf7 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,4 +1,3 @@
-
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import {
@@ -24,7 +23,6 @@ import {
type OkfSlice,
} from './types.ts';
-
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/rules/index-shape.ts b/packages/core/src/markdown/lint/rules/index-shape.ts
index fcbb1b56c..59fe9b87d 100644
--- a/packages/core/src/markdown/lint/rules/index-shape.ts
+++ b/packages/core/src/markdown/lint/rules/index-shape.ts
@@ -1,4 +1,3 @@
-
import type { List, ListItem } from 'mdast';
import { EXIT, visit } from 'unist-util-visit';
import { defineScopedOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/rules/log-shape.ts b/packages/core/src/markdown/lint/rules/log-shape.ts
index 431e4e9c8..e0159519f 100644
--- a/packages/core/src/markdown/lint/rules/log-shape.ts
+++ b/packages/core/src/markdown/lint/rules/log-shape.ts
@@ -1,4 +1,3 @@
-
import type { Heading } from 'mdast';
import { toString as headingText } from 'mdast-util-to-string';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/lint/rules/no-wiki-links.ts b/packages/core/src/markdown/lint/rules/no-wiki-links.ts
index f75a04d15..2123e977f 100644
--- a/packages/core/src/markdown/lint/rules/no-wiki-links.ts
+++ b/packages/core/src/markdown/lint/rules/no-wiki-links.ts
@@ -1,4 +1,3 @@
-
import type { Point } from 'unist';
import { visit } from 'unist-util-visit';
import { defineOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/rules/reserved-casing.ts b/packages/core/src/markdown/lint/rules/reserved-casing.ts
index c8b4d8f28..89ef3e4a9 100644
--- a/packages/core/src/markdown/lint/rules/reserved-casing.ts
+++ b/packages/core/src/markdown/lint/rules/reserved-casing.ts
@@ -1,4 +1,3 @@
-
import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';
import { defineOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 594830b88..2cffecae6 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,4 +1,3 @@
-
import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';
import type { OkfRuleId } from './okf-rule-meta.ts';
@@ -113,7 +112,6 @@ export interface OkfSlice {
generate?: { index?: boolean };
}
-
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.ts
index 437cc539a..98238656e 100644
--- a/packages/core/src/markdown/lint/validation-counts.ts
+++ b/packages/core/src/markdown/lint/validation-counts.ts
@@ -1,4 +1,3 @@
-
export interface ValidationSourceCounts {
errorCount: number;
warningCount: number;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index bd79424c7..a5b511f25 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index 00fbc0035..ed89371d0 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index df788a80d..8ce2b2492 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index fa3cfcd86..bfd7e3109 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 17ed2b829..1a897fca8 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index 4aa0490c4..d988f4b8b 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,7 +168,6 @@ export function parseRecursive(
}
}
-
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
-
interface Region {
start: number;
end: number;
@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
-
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
-
interface SourceBlock {
src: string;
start: number;
@@ -456,7 +452,6 @@ function tryPerBlockFallback(
};
}
-
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index 43d420187..e6ab4fd57 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,4 +1,3 @@
-
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 55736041c..0e3224206 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index ccf06e94d..91cdf658f 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,4 +1,3 @@
-
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
import { isBlankLineParagraph } from './zero-emission-blocks.ts';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index e5b4c9eba..0f399d34c 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -477,8 +476,7 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- }
- else if (first === '[') {
+ } else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index ca225ce9b..db10fa54b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 3a2524a9a..34068d103 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 2279a0189..93151d43b 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index a0f467c42..188f02d83 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4e8542a21..4ba2c3418 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index a3c96b24a..1a74b1272 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index e95cf43d6..de35e7b79 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index ffdb4d5b5..b4be1b2ea 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index e2a96d1a7..3c8d88b7c 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index 0389575ac..cf2c9da8e 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,4 +1,3 @@
-
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 8be632ba4..4d3250d3a 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,4 +1,3 @@
-
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 96304e7a5..0dd54070e 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,4 +1,3 @@
-
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { expect } from 'vitest';
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 93798cf83..7cac5b042 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,4 +1,3 @@
-
import type { Node as PmNode } from '@tiptap/pm/model';
import type {
MdxJsxAttribute,
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index 8c08b7a04..b012a5aff 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index 83d4af672..b50bea5ec 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.ts
index 6e6d73400..0f1b0f27d 100644
--- a/packages/core/src/markdown/underline-promoter.ts
+++ b/packages/core/src/markdown/underline-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index 932d7d2a8..1a082bda7 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,4 +1,3 @@
-
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index ac9f5239b..d578476a7 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,4 +1,3 @@
-
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index afd9936fe..6dad26200 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {
}
}
-
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {
};
}
-
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
-
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {