Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Track the active heading in the outline in source mode (#3030)
Nick Gomezdb6bb4f8363e
diff --git a/.changeset/outline-active-heading-source-mode.md b/.changeset/outline-active-heading-source-mode.mdnew file mode 100644index 000000000..dc3dc646a--- /dev/null+++ b/.changeset/outline-active-heading-source-mode.md@@ -0,0 +1,9 @@+---+'@inkeep/open-knowledge': patch+---++Fix the outline not following your scroll position in Markdown source mode++The outline pane now highlights the heading you are reading while you scroll the Markdown source view, the same way it already did in the rich-text view. The position marker, the highlighted row, and the row's accessibility state all keep up as you scroll, and clicking an outline row leaves that heading highlighted once the view settles.++Headings written with Windows line endings are also recognized now. Previously a document saved with CRLF line endings produced an empty outline.diff --git a/packages/app/package.json b/packages/app/package.jsonindex 342cc81b7..ca309055d 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -26,7 +26,7 @@"measure:fuzz": "bash scripts/measure-fuzz.sh","measure:stress": "bash scripts/measure-stress.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts",+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox","test:visual": "playwright test --config playwright.visual.config.ts","test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",diff --git a/packages/app/src/components/OutlinePanel.tsx b/packages/app/src/components/OutlinePanel.tsxindex ffa4570da..614305f24 100644--- a/packages/app/src/components/OutlinePanel.tsx+++ b/packages/app/src/components/OutlinePanel.tsx@@ -146,7 +146,7 @@ function OutlinePanelInner({}, [activeProvider, activeDocName, docName, queryClient]);const slugs = headings.map((h) => h.slug);- const activeSlug = useActiveHeading(slugs, isSourceMode);+ const activeSlug = useActiveHeading(slugs, { isSourceMode, docName });const activeIndex = activeSlug ? headings.findIndex((h) => h.slug === activeSlug) : -1;function handleNav(index: number, slug: string) {diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsxindex 66bf65686..da7ad2837 100644--- a/packages/app/src/editor/SourceEditor.tsx+++ b/packages/app/src/editor/SourceEditor.tsx@@ -4,7 +4,6 @@ import { Compartment, EditorSelection, EditorState, StateEffect } from '@codemirimport { placeholder as cmPlaceholder, EditorView, keymap } from '@codemirror/view';import type { HocuspocusProvider } from '@hocuspocus/provider';import {- createCodeFenceTracker,DEFAULT_LINTER_CONFIG,type PersistedLinterConfig,toEffectiveBase,@@ -45,10 +44,10 @@ import {consumePendingSourceNavigation,peekPendingSourceNavigation,} from './source-editor-navigation';+import { sourceHeadingLines } from './source-heading-lines';import { createMarkdownLintExtension } from './source-lint/markdown-lint-source';import { sourceModeSetup } from './source-mode-setup';import { createSourcePolishExtension } from './source-polish';-import { FM_FENCE_LINE_RE } from './source-polish/view-plugin';import { attachTypingBurstDetector } from './typing-burst-detector';// Toolbar exclusion zone in px (= 3.5rem, EditorToolbar's rendered height). CM6@@ -75,42 +74,18 @@ interface SourceEditorProps {}function applyOutlineNavigation(view: EditorView, detail: OutlineNavDetail, docName: string): void {- const doc = view.state.doc;- let startLine = 1;- // FM fence recognition must agree with the server's extractHeadings (core- // fence contract), which produces the outline this index maps onto —- // otherwise YAML `#` lines shift the heading count and clicks jump wrong.- if (doc.lines >= 1 && FM_FENCE_LINE_RE.test(doc.line(1).text)) {- for (let i = 2; i <= doc.lines; i++) {- if (FM_FENCE_LINE_RE.test(doc.line(i).text)) {- startLine = i + 1;- break;- }- }- }+ // The outline row's index maps 1:1 onto this enumeration, which shares its+ // line-admission rules with the server producer that emitted the row.+ const heading = sourceHeadingLines(view.state.doc)[detail.index];+ if (!heading) return;- // Skip `#` comments inside fenced code blocks — they render as code, not- // headings, so they must stay out of the heading count that maps 1:1 onto- // the outline index.- const isInCodeFence = createCodeFenceTracker();- let seen = 0;- for (let i = startLine; i <= doc.lines; i++) {- const line = doc.line(i);- if (isInCodeFence(line.text)) continue;- if (/^#{1,6}\s/.test(line.text)) {- if (seen === detail.index) {- runScrollNavigation(docName, () => {- view.dispatch({- selection: EditorSelection.cursor(line.from),- effects: EditorView.scrollIntoView(line.from, { y: 'start' }),- });- view.focus();- });- return;- }- seen++;- }- }+ runScrollNavigation(docName, () => {+ view.dispatch({+ selection: EditorSelection.cursor(heading.from),+ effects: EditorView.scrollIntoView(heading.from, { y: 'start' }),+ });+ view.focus();+ });}export function applyRawMdxNavigation(@@ -400,7 +375,8 @@ export function SourceEditor({cmEntryRef.current = entry;viewRef.current = entry.view;// Publish the live view so a source-to-WYSIWYG flip can read its viewport- // synchronously at flip time, before this editor is hidden.+ // synchronously at flip time, before this editor is hidden, and so outline+ // active-heading tracking can measure this document's line geometry.registerSourceView(docName, entry.view);} catch (err) {// Surface mount failures through DocumentErrorBoundary.@@ -414,6 +390,8 @@ export function SourceEditor({const cur = cmEntryRef.current;if (cur) {parkCmEditor(cur);+ // A parked view is off screen, so it must stop answering geometry+ // questions for this document even though the view itself stays alive.unregisterSourceView(docName, cur.view);}// Listener cleanup is implicit when evictCmEditor calls view.destroy().diff --git a/packages/app/src/editor/active-source-view.test.ts b/packages/app/src/editor/active-source-view.test.tsnew file mode 100644index 000000000..15d4a4b46--- /dev/null+++ b/packages/app/src/editor/active-source-view.test.ts@@ -0,0 +1,147 @@+/**+ * Module-level registry mapping docName → the mounted CodeMirror view.+ *+ * Active-heading tracking reads the view out of this registry to measure line+ * geometry, so the registry's answer is what decides whether the outline can+ * track at all. Two properties carry the weight: the entry means "mounted"+ * (a stale entry produces measurements from a view that is no longer on screen),+ * and subscribers are notified on every transition (a missed notification+ * leaves the outline frozen until some unrelated render happens to recompute).+ */++import type { EditorView } from '@codemirror/view';+import { afterEach, describe, expect, test } from 'vitest';+import {+ getSourceViewForDoc,+ registerSourceView,+ subscribeSourceViewRegistry,+ unregisterSourceView,+} from './active-source-view';++const fakeView = (id: string): EditorView => ({ __id: id }) as unknown as EditorView;++const TOUCHED_DOCS = ['doc-a', 'doc-b', 'doc-remounted'];++describe('active-source-view registry', () => {+ afterEach(() => {+ // Registry state is module-scoped and outlives each test, so clear every+ // docName any test may have touched rather than letting bleed hide a bug.+ for (const docName of TOUCHED_DOCS) {+ const current = getSourceViewForDoc(docName);+ if (current) unregisterSourceView(docName, current);+ }+ });++ test('hands back the view registered for a docName', () => {+ const view = fakeView('a');++ registerSourceView('doc-a', view);++ expect(getSourceViewForDoc('doc-a')).toBe(view);+ });++ test('reports null for a docName with no mounted view', () => {+ expect(getSourceViewForDoc('doc-a')).toBeNull();+ });++ test('unregisters the matching view', () => {+ const view = fakeView('a');+ registerSourceView('doc-a', view);++ unregisterSourceView('doc-a', view);++ expect(getSourceViewForDoc('doc-a')).toBeNull();+ });++ test('a stale unregister does not evict the live successor', () => {+ // A StrictMode or HMR double-invoke runs the previous mount's cleanup after+ // the next mount has already registered its view. Deleting by docName alone+ // would leave the live view unreachable and tracking permanently dead.+ const previous = fakeView('previous');+ const current = fakeView('current');+ registerSourceView('doc-remounted', previous);+ registerSourceView('doc-remounted', current);++ unregisterSourceView('doc-remounted', previous);++ expect(getSourceViewForDoc('doc-remounted')).toBe(current);+ });++ test('the most recent registration wins for one docName', () => {+ const first = fakeView('first');+ const second = fakeView('second');++ registerSourceView('doc-a', first);+ registerSourceView('doc-a', second);++ expect(getSourceViewForDoc('doc-a')).toBe(second);+ });++ test('keeps document names isolated', () => {+ const viewA = fakeView('a');+ const viewB = fakeView('b');+ registerSourceView('doc-a', viewA);+ registerSourceView('doc-b', viewB);++ unregisterSourceView('doc-a', viewA);++ expect(getSourceViewForDoc('doc-a')).toBeNull();+ expect(getSourceViewForDoc('doc-b')).toBe(viewB);+ });++ test('notifies subscribers when a view mounts and when it unmounts', () => {+ const view = fakeView('a');+ let notifications = 0;+ const unsubscribe = subscribeSourceViewRegistry(() => {+ notifications++;+ });++ registerSourceView('doc-a', view);+ expect(notifications).toBe(1);++ unregisterSourceView('doc-a', view);+ expect(notifications).toBe(2);++ unsubscribe();+ });++ test('stops notifying after unsubscribe', () => {+ let notifications = 0;+ const unsubscribe = subscribeSourceViewRegistry(() => {+ notifications++;+ });++ unsubscribe();+ registerSourceView('doc-a', fakeView('a'));++ expect(notifications).toBe(0);+ });++ test('does not notify when a stale unregister changes nothing', () => {+ const previous = fakeView('previous');+ const current = fakeView('current');+ registerSourceView('doc-remounted', previous);+ registerSourceView('doc-remounted', current);+ let notifications = 0;+ const unsubscribe = subscribeSourceViewRegistry(() => {+ notifications++;+ });++ unregisterSourceView('doc-remounted', previous);++ expect(notifications).toBe(0);+ unsubscribe();+ });++ test('notifies every subscriber', () => {+ const seen: string[] = [];+ const unsubscribeFirst = subscribeSourceViewRegistry(() => seen.push('first'));+ const unsubscribeSecond = subscribeSourceViewRegistry(() => seen.push('second'));++ registerSourceView('doc-a', fakeView('a'));++ expect(seen).toEqual(['first', 'second']);+ unsubscribeFirst();+ unsubscribeSecond();+ });+});diff --git a/packages/app/src/editor/active-source-view.ts b/packages/app/src/editor/active-source-view.tsindex e8e5be013..7853e141a 100644--- a/packages/app/src/editor/active-source-view.ts+++ b/packages/app/src/editor/active-source-view.ts@@ -1,32 +1,59 @@/*** Module-level registry mapping docName → the doc's live CodeMirror source view.- *- * The mode-toggle chokepoint captures the outgoing editor's viewport at flip- * time, before React hides it. For a source-to-WYSIWYG flip the outgoing editor- * is CodeMirror, whose view SourceEditor holds in a component-local ref — so it- * publishes the live view here for that synchronous, one-shot capture to read.* The TipTap twin of this registry is `active-editor.ts`.*- * Registration is last-writer-wins per docName; unregister matches on the view- * ref so a StrictMode double-invoke (register-A, register-B, cleanup-A) does not- * leave the map empty. No subscriber channel — unlike the TipTap registry no- * reactive UI reads this, only the capture path.+ * Two consumers, both needing a view that `SourceEditor` otherwise keeps in a+ * component-local ref:+ *+ * - The mode-toggle chokepoint captures the outgoing editor's viewport at flip+ * time, before React hides it. For a source-to-WYSIWYG flip the outgoing+ * editor is CodeMirror, so it reads the live view here for that synchronous,+ * one-shot capture.+ * - Outline active-heading tracking measures heading line geometry off the+ * view's height map. That consumer is reactive, which is why this registry+ * carries a subscriber channel: a view mounting is not a React state change,+ * so a consumer that read the map once per mount would stay frozen when the+ * view arrives later.+ *+ * An entry means "mounted", not merely "constructed" — tracking measures+ * on-screen line positions, so an entry left behind for a parked view would+ * answer with positions that are no longer on screen.*/import type { EditorView } from '@codemirror/view';const sourceViews = new Map<string, EditorView>();+const listeners = new Set<() => void>();++function notifyListeners(): void {+ for (const listener of listeners) listener();+}export function registerSourceView(docName: string, view: EditorView): void {sourceViews.set(docName, view);+ notifyListeners();}+/**+ * Remove the entry for `docName`, but only while the registered view still is+ * `view`. StrictMode and HMR run the previous mount's cleanup after the next+ * mount has already registered, so deleting by docName alone would leave the+ * live view unreachable and tracking permanently dead.+ */export function unregisterSourceView(docName: string, view: EditorView): void {if (sourceViews.get(docName) === view) {sourceViews.delete(docName);+ notifyListeners();}}export function getSourceViewForDoc(docName: string): EditorView | null {return sourceViews.get(docName) ?? null;}++export function subscribeSourceViewRegistry(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}diff --git a/packages/app/src/editor/editor-cache.test.ts b/packages/app/src/editor/editor-cache.test.tsindex 9ff2a32db..2125131a5 100644--- a/packages/app/src/editor/editor-cache.test.ts+++ b/packages/app/src/editor/editor-cache.test.ts@@ -28,6 +28,7 @@ import type { Editor } from '@tiptap/core';import { yUndoPluginKey } from '@tiptap/y-tiptap';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import * as Y from 'yjs';+import { getSourceViewForDoc, registerSourceView } from './active-source-view';import {__consumeRenameSnapshot,__getActivityMountList,@@ -1253,6 +1254,26 @@ describe('CM6 cache — lifecycle', () => {expect(__peekCm(h.docName)).toBeUndefined();});+ test('evict: drops the source-view registry entry', () => {+ // Eviction is the only view-destroy path outside a React cleanup, so nothing+ // else would notice if this call were removed or reordered after destroy().+ // A destroyed view left reachable answers geometry questions with undefined+ // results, which freezes the outline's active heading rather than failing+ // loudly. Asserts the observable outcome rather than spying on the call.+ 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>,+ });+ registerSourceView(h.docName, entry.view);+ expect(getSourceViewForDoc(h.docName)).toBe(entry.view);++ expect(evictCmEditor(h.docName)).toBe(true);++ expect(getSourceViewForDoc(h.docName)).toBeNull();+ });+test('5 park-mount cycles work for CM6', () => {const h = makeCmHarness('cm-doc-a');const entry = mountCmEditor({diff --git a/packages/app/src/editor/editor-cache.ts b/packages/app/src/editor/editor-cache.tsindex 16083cb54..38d47f5df 100644--- a/packages/app/src/editor/editor-cache.ts+++ b/packages/app/src/editor/editor-cache.ts@@ -54,6 +54,7 @@ import { yUndoPluginKey } from '@tiptap/y-tiptap';import type * as Y from 'yjs';import { mark } from '@/lib/perf';import { readNumericOverride } from '@/lib/perf/env-override';+import { unregisterSourceView } from './active-source-view';import { getMountId } from './mount-id-registry';// Cyclic import is intentional and ESM-safe: this module's `mountTiptapEditor`// is consumed by `mount-promise.ts` (the Suspense + use(promise) primitive),@@ -1123,6 +1124,14 @@ export function evictCmEditor(docName: string): boolean {const entry = cmCache.get(docName);if (!entry) return false;+ // Drop the registry entry before destroying the view it points at. The+ // registry's contract is that an entry means a mounted view, and eviction is+ // the one destroy path no React cleanup covers: `parkCmEditor`'s kill-switch+ // branch is always followed by SourceEditor's own unregister, but the LRU+ // calls this independently of any component lifecycle. The identity guard in+ // `unregisterSourceView` makes the park-then-evict double call a no-op.+ unregisterSourceView(docName, entry.view);+try {entry.view.destroy();} catch (err) {diff --git a/packages/app/src/editor/heading-enumeration-alignment.test.ts b/packages/app/src/editor/heading-enumeration-alignment.test.tsnew file mode 100644index 000000000..d961e4bf3--- /dev/null+++ b/packages/app/src/editor/heading-enumeration-alignment.test.ts@@ -0,0 +1,150 @@+/**+ * Cross-producer agreement: the source-mode heading enumerator must see exactly+ * the same headings, in the same order, with the same slugs, as the server's+ * outline producer.+ *+ * The outline rows come from the server; source-mode navigation and+ * active-heading tracking resolve them against client-side line offsets. The+ * two are joined by ordinal alone, so any line one producer admits and the+ * other skips shifts every row after it — a silent off-by-N that looks like a+ * scroll bug rather than a scan bug.+ *+ * Expected values come from the independent producer, never from a slug array+ * written here, so the test cannot be satisfied by back-fitting a constant to+ * whatever the client happens to do.+ */++import { EditorState } from '@codemirror/state';+import { extractHeadings } from '@inkeep/open-knowledge-server';+import { describe, expect, test } from 'vitest';+import { type SourceHeadingLine, sourceHeadingLines } from './source-heading-lines';++interface Case {+ name: string;+ lines: string[];+}++const CASES: Case[] = [+ {+ name: 'an ordinary document spanning every heading level',+ lines: [+ '# Title',+ '',+ 'Intro prose.',+ '',+ '## Section',+ '',+ '### Subsection',+ '',+ '#### Deeper',+ '',+ '##### Deeper still',+ '',+ '###### Deepest',+ '',+ 'Closing prose.',+ ],+ },+ {+ name: 'duplicate heading text, ASCII and non-ASCII',+ lines: ['# Notes', '', '## Notes', '', '## 東京', '', '## 東京', '', '## notes'],+ },+ {+ name: 'hashes with no heading text',+ lines: ['# Real', '', '### ', '', '### ', '', '## After'],+ },+ {+ name: 'heading text that slugs to nothing',+ lines: ['# Real', '', '## ---', '', '## ***', '', '## After'],+ },+ {+ name: 'hashes with no separating whitespace',+ lines: ['# Real', '', '#NoSpace', '', '## After'],+ },+ {+ name: 'a seventh hash',+ lines: ['# Real', '', '####### Seven', '', '## After'],+ },+ {+ name: 'an indented hash line',+ lines: ['# Real', '', ' ## Indented', '', '## After'],+ },+ {+ name: 'frontmatter containing a YAML comment',+ lines: ['---', 'title: Doc', '# yaml comment, not a heading', '---', '', '# Real Heading'],+ },+ {+ name: 'frontmatter whose opening fence carries a trailing space',+ lines: ['--- ', 'title: Doc', '# yaml comment, not a heading', '---', '', '# Real Heading'],+ },+ {+ name: 'frontmatter whose closing fence carries a trailing tab',+ lines: ['---', 'title: Doc', '# yaml comment, not a heading', '---\t', '', '# Real Heading'],+ },+ {+ name: 'an unclosed leading fence, which is body for both producers',+ lines: ['---', 'title: Never closed', '# Looks like yaml', '', '## After'],+ },+ {+ name: 'a mid-document thematic break',+ lines: ['# Real', '', '---', '', '## After'],+ },+ {+ name: 'a backtick code fence containing a hash line',+ lines: [+ '# Top',+ '',+ '```yaml',+ '# electron-builder.yml',+ 'appId: com.example',+ '```',+ '',+ '## After',+ ],+ },+ {+ name: 'a tilde code fence containing a hash line',+ lines: ['# Top', '', '~~~bash', '# not a heading', '~~~', '', '## After'],+ },+ {+ name: 'an unclosed code fence swallowing the rest of the document',+ lines: ['# Real', '', '```js', '# inside', '## still inside'],+ },+ {+ // A CRLF document. The client builds its doc the way production does (see the+ // `EditorState.create` below), which splits on CodeMirror's DefaultSplit and+ // drops the `\r` before the enumerator runs — while the server scans the raw+ // `\r`-bearing bytes. Both must still agree.+ name: 'CRLF line endings',+ lines: ['# Intro\r', '\r', '## Details\r', ''],+ },+ {+ // CRLF plus frontmatter whose body carries a hash line: the client's+ // frontmatter partition and the server's must agree on skipping it, or that+ // in-frontmatter `# …` surfaces as a phantom heading and shifts every ordinal.+ name: 'CRLF line endings with an in-frontmatter hash',+ lines: ['---\r', 'title: Doc\r', '# yaml comment, not a heading\r', '---\r', '\r', '# Real\r'],+ },+];++describe('client/server heading enumeration agreement', () => {+ for (const { name, lines } of CASES) {+ test(name, () => {+ const md = lines.join('\n');++ // Build the client doc exactly as the running editor does: `EditorState.create`+ // splits the string on CodeMirror's DefaultSplit (`/\r\n?|\n/`), so a CRLF+ // document reaches `sourceHeadingLines` with the `\r` already stripped.+ // Splitting on `\n` alone here would feed the enumerator a `\r` production+ // never delivers, testing a path the editor cannot take.+ const clientDoc = EditorState.create({ doc: md }).doc;+ const client = sourceHeadingLines(clientDoc).map((entry: SourceHeadingLine) => entry.slug);+ const server = extractHeadings(md).map((heading) => heading.slug);++ // Every fixture carries at least one real heading, so a case cannot pass+ // by both producers finding nothing.+ expect(server.length).toBeGreaterThan(0);+ expect(client).toEqual(server);+ });+ }+});diff --git a/packages/app/src/editor/source-heading-lines.test.ts b/packages/app/src/editor/source-heading-lines.test.tsnew file mode 100644index 000000000..64ab8572f--- /dev/null+++ b/packages/app/src/editor/source-heading-lines.test.ts@@ -0,0 +1,229 @@+/**+ * The source-mode heading enumerator: one entry per heading line, in document+ * order, keyed to the line's start offset.+ *+ * Two consumers depend on the ordinal being exact. Outline navigation maps the+ * clicked outline row's index onto the nth entry, and active-heading tracking+ * measures the nth entry's line geometry — so a line admitted or skipped here+ * that the server's outline producer treats differently shifts every subsequent+ * row. Expected offsets are written as `doc.line(n).from` so a fixture edit+ * cannot silently invalidate hand-computed integers.+ */++import { Text } from '@codemirror/state';+import { describe, expect, test } from 'vitest';+import { type SourceHeadingLine, sourceHeadingLines } from './source-heading-lines';++// Each call allocates a fresh `Text`, so the module-level cache in+// `sourceHeadingLines` (keyed by `Text` identity) never carries one test's+// result into another. Do not hoist a `Text` to module scope — that would share+// one cache slot across tests.+function docOf(lines: string[]): Text {+ return Text.of(lines);+}++function slugs(entries: readonly SourceHeadingLine[]): string[] {+ return entries.map((entry) => entry.slug);+}++function froms(entries: readonly SourceHeadingLine[]): number[] {+ return entries.map((entry) => entry.from);+}++function lineStarts(doc: Text, lineNumbers: number[]): number[] {+ return lineNumbers.map((n) => doc.line(n).from);+}++describe('sourceHeadingLines', () => {+ test('returns one entry per heading line in document order', () => {+ const doc = docOf([+ '# Title',+ '',+ 'Intro prose.',+ '',+ '## First',+ '',+ '### Nested',+ '',+ '## Second',+ ]);++ const entries = sourceHeadingLines(doc);++ expect(slugs(entries)).toEqual(['title', 'first', 'nested', 'second']);+ expect(froms(entries)).toEqual(lineStarts(doc, [1, 5, 7, 9]));+ });++ test('points `from` at the line start, before the hashes', () => {+ // Outline navigation places the cursor at this offset; landing after the+ // hashes would put the caret inside the heading marker.+ const doc = docOf(['Prose.', '', '## Heading']);++ const [entry] = sourceHeadingLines(doc);++ expect(entry.from).toBe(doc.line(3).from);+ expect(doc.sliceString(entry.from, entry.from + 2)).toBe('##');+ });++ test('returns nothing for a document with no headings', () => {+ expect(sourceHeadingLines(docOf(['Just prose.', '', 'More prose.']))).toEqual([]);+ });++ test('skips the frontmatter region so a YAML comment is not heading zero', () => {+ const doc = docOf([+ '---',+ 'title: Fence hazard',+ '# yaml comment, not a heading',+ '---',+ '',+ '# Real Heading',+ ]);++ const entries = sourceHeadingLines(doc);++ expect(slugs(entries)).toEqual(['real-heading']);+ expect(froms(entries)).toEqual(lineStarts(doc, [6]));+ });++ test('skips frontmatter whose opening fence carries a trailing space', () => {+ // `--- ` is one in-tolerance keystroke away from `---`; frontmatter+ // recognition must not flip on it, or the YAML comment leaks in.+ const doc = docOf([+ '--- ',+ 'title: Fence hazard',+ '# yaml comment, not a heading',+ '---',+ '',+ '# Real Heading',+ ]);++ expect(slugs(sourceHeadingLines(doc))).toEqual(['real-heading']);+ });++ test('skips frontmatter whose closing fence carries a trailing tab', () => {+ const doc = docOf([+ '---',+ 'title: Fence hazard',+ '# yaml comment, not a heading',+ '---\t',+ '',+ '# Real Heading',+ ]);++ expect(slugs(sourceHeadingLines(doc))).toEqual(['real-heading']);+ });++ test('skips frontmatter whose fences carry Windows line endings', () => {+ // The heading predicate and the code-fence tracker both tolerate a trailing+ // CR, so the frontmatter fence check has to as well or the three disagree+ // about where the body starts. CodeMirror strips CR when it builds a+ // document, so no production caller arrives here with one — but a caller+ // constructing `Text` by hand would otherwise silently take the YAML+ // comment as heading zero and shift every ordinal after it.+ const doc = docOf(['---\r', 'title: Windows\r', '# yaml comment\r', '---\r', '\r', '# Real\r']);++ expect(slugs(sourceHeadingLines(doc))).toEqual(['real']);+ });++ test('treats an unclosed leading fence as body, not frontmatter', () => {+ // A closing fence is mandatory for the server's frontmatter partition too,+ // so an unclosed opener leaves the whole document as body for both.+ const doc = docOf(['---', 'title: Never closed', '# Looks like yaml', '']);++ expect(slugs(sourceHeadingLines(doc))).toEqual(['looks-like-yaml']);+ });++ test('does not start a frontmatter skip at a mid-document thematic break', () => {+ const doc = docOf(['# Real', '', '---', '', '## After']);++ const entries = sourceHeadingLines(doc);++ expect(slugs(entries)).toEqual(['real', 'after']);+ expect(froms(entries)).toEqual(lineStarts(doc, [1, 5]));+ });++ test('skips hash lines inside a backtick code fence', () => {+ const doc = docOf([+ '# Top',+ '',+ '```yaml',+ '# electron-builder.yml',+ 'appId: com.example',+ '```',+ '',+ '## After',+ ]);++ const entries = sourceHeadingLines(doc);++ expect(slugs(entries)).toEqual(['top', 'after']);+ expect(froms(entries)).toEqual(lineStarts(doc, [1, 8]));+ });++ test('skips hash lines inside a tilde code fence', () => {+ const doc = docOf(['# Top', '~~~bash', '# not a heading', '~~~', '## After']);++ expect(slugs(sourceHeadingLines(doc))).toEqual(['top', 'after']);+ });++ test('an unclosed code fence swallows the rest of the document', () => {+ const doc = docOf(['# Real', '```js', '# inside', '## still inside']);++ expect(slugs(sourceHeadingLines(doc))).toEqual(['real']);+ });++ test('disambiguates duplicate slugs across the whole document', () => {+ const doc = docOf(['# Intro', '', '## Intro', '', '## 東京', '', '## 東京']);++ expect(slugs(sourceHeadingLines(doc))).toEqual(['intro', 'intro-1', '東京', '東京-1']);+ });++ test('does not count hashes with no heading text', () => {+ const doc = docOf(['# Real', '', '### ', '', '## After']);++ const entries = sourceHeadingLines(doc);++ expect(slugs(entries)).toEqual(['real', 'after']);+ expect(froms(entries)).toEqual(lineStarts(doc, [1, 5]));+ });++ test('does not count a heading whose text slugs to nothing', () => {+ const doc = docOf(['# Real', '', '## ---', '', '## After']);++ const entries = sourceHeadingLines(doc);++ expect(slugs(entries)).toEqual(['real', 'after']);+ expect(froms(entries)).toEqual(lineStarts(doc, [1, 5]));+ });++ test('reuses the previous result for the same document instance', () => {+ // Tracking re-resolves every heading on each animation frame, so a rescan+ // per frame is the cost this cache exists to avoid. Returning the identical+ // array is the only externally observable proof the scan was skipped.+ const doc = docOf(['# One', '', '## Two']);++ const first = sourceHeadingLines(doc);++ expect(sourceHeadingLines(doc)).toBe(first);+ });++ test('rescans after the document changes', () => {+ const doc = docOf(['# One', '', '## Two']);+ const first = sourceHeadingLines(doc);++ const grown = doc.append(docOf(['', '## Three']));+ const second = sourceHeadingLines(grown);++ expect(second).not.toBe(first);+ expect(slugs(second)).toEqual(['one', 'two', 'three']);+ expect(froms(second)).toEqual(lineStarts(grown, [1, 3, 4]));+ });++ test('answers correctly for a document that has fallen out of the cache', () => {+ const doc = docOf(['# One', '', '## Two']);+ sourceHeadingLines(doc);+ sourceHeadingLines(doc.append(docOf(['', '## Three'])));++ expect(slugs(sourceHeadingLines(doc))).toEqual(['one', 'two']);+ });+});diff --git a/packages/app/src/editor/source-heading-lines.ts b/packages/app/src/editor/source-heading-lines.tsnew file mode 100644index 000000000..5a9d8a545--- /dev/null+++ b/packages/app/src/editor/source-heading-lines.ts@@ -0,0 +1,80 @@+import type { Text } from '@codemirror/state';+import {+ createCodeFenceTracker,+ FM_FENCE_LINE_RE,+ scanHeadingLine,+} from '@inkeep/open-knowledge-core';++export interface SourceHeadingLine {+ /** Matches the slug of the server-produced outline row at the same ordinal. */+ slug: string;+ /** Line start, before the hashes, which is where outline navigation puts the caret. */+ from: number;+}++let cachedDoc: Text | null = null;+let cachedEntries: SourceHeadingLine[] = [];++/**+ * Enumerate a source document's heading lines in document order.+ *+ * Both source-mode consumers join onto the server's outline by ordinal: a+ * clicked outline row navigates to the nth entry, and active-heading tracking+ * measures the nth entry's line geometry. Admitting a line the server skips (or+ * the reverse) shifts every entry after it, so line admission is delegated+ * wholesale to `scanHeadingLine` and the shared code-fence tracker rather than+ * re-decided here.+ *+ * The result is cached against the `Text` instance. Tracking re-resolves every+ * heading per animation frame, and `Text` is immutable, so instance identity is+ * a sound document-version key. The return is `readonly` because it is the very+ * cached array — a caller mutation would corrupt every later same-`Text` read.+ */+export function sourceHeadingLines(doc: Text): readonly SourceHeadingLine[] {+ if (doc === cachedDoc) return cachedEntries;+ const entries = scanDoc(doc);+ cachedDoc = doc;+ cachedEntries = entries;+ return entries;+}++function scanDoc(doc: Text): SourceHeadingLine[] {+ const entries: SourceHeadingLine[] = [];+ const slugCounts = new Map<string, number>();+ const isInCodeFence = createCodeFenceTracker();++ for (let i = frontmatterBodyStart(doc); i <= doc.lines; i++) {+ const line = doc.line(i);+ if (isInCodeFence(line.text)) continue;+ const heading = scanHeadingLine(line.text, slugCounts);+ if (heading) entries.push({ slug: heading.slug, from: line.from });+ }++ return entries;+}++/**+ * Number of the first body line: past the frontmatter region when the document+ * opens with a closed `---` fence, else line 1. An unclosed opener is body, the+ * same reading the server's frontmatter partition takes, so `# …` lines under it+ * count as headings for both producers.+ */+function frontmatterBodyStart(doc: Text): number {+ if (!isFenceLine(doc.line(1).text)) return 1;+ for (let i = 2; i <= doc.lines; i++) {+ if (isFenceLine(doc.line(i).text)) return i + 1;+ }+ return 1;+}++/**+ * Tolerate a trailing CR, as `scanHeadingLine` and `createCodeFenceTracker` both+ * do. CodeMirror strips CR when it builds a document, so no production caller+ * reaches here with one — but leaving the third predicate in this file the only+ * CR-intolerant one makes correctness depend on that, and a caller handing over a+ * hand-built `Text` would silently mis-partition frontmatter and shift every+ * ordinal after it.+ */+function isFenceLine(line: string): boolean {+ return FM_FENCE_LINE_RE.test(line.endsWith('\r') ? line.slice(0, -1) : line);+}diff --git a/packages/app/src/editor/source-polish/view-plugin.ts b/packages/app/src/editor/source-polish/view-plugin.tsindex 2d88629f3..328d9d8dc 100644--- a/packages/app/src/editor/source-polish/view-plugin.ts+++ b/packages/app/src/editor/source-polish/view-plugin.ts@@ -51,12 +51,9 @@ function countLeadingIndent(text: string): number {// Line-scoped shape of the fence contract, sourced from core so the FM// region the user sees styled as YAML matches what the bridge recognizes by-// construction (no local regex copy to drift). Re-exported for-// SourceEditor's outline-navigation FM skip.+// construction (no local regex copy to drift).import { FM_FENCE_LINE_RE } from '@inkeep/open-knowledge-core';-export { FM_FENCE_LINE_RE };-function frontmatterRange(state: EditorState): { from: number; to: number } | null {if (state.doc.lines < 2) return null;const firstLine = state.doc.line(1);diff --git a/packages/app/src/hooks/useActiveHeading.dom.test.tsx b/packages/app/src/hooks/useActiveHeading.dom.test.tsxnew file mode 100644index 000000000..bf84b29a8--- /dev/null+++ b/packages/app/src/hooks/useActiveHeading.dom.test.tsx@@ -0,0 +1,143 @@+/**+ * Selection-predicate pin for the WYSIWYG path, where the active heading is+ * derived from real heading-element geometry.+ *+ * Scope is deliberately WYSIWYG-only. jsdom performs no layout, so every rect+ * here is a stub — that is legitimate for pinning the PRIORITY ORDER between+ * candidate headings (which is arithmetic over rects the caller supplies), and+ * illegitimate for anything that depends on where the browser actually places+ * content. Source-mode tracking is geometric by nature, so it is pinned in the+ * browser tier (`tests/stress/outline-active-heading.e2e.ts`), never here: a+ * jsdom assertion about source-mode position would be a green over fabricated+ * measurements.+ */++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, test } from 'vitest';+import { useActiveHeading } from './useActiveHeading';++/** jsdom's default viewport height; the predicate's "top half" is above the midpoint. */+const MID_Y = window.innerHeight / 2;++interface Fixture {+ slugs: string[];+ /** The nested element scroll events are dispatched from. */+ scrollport: HTMLElement;+ /** Move a heading and return, so a test can re-measure without remounting. */+ setTop: (slug: string, top: number) => void;+}++/**+ * Mount `<h2 id={slug}>` elements inside a scroll container and give each a+ * stubbed viewport-relative `top`. Real elements with real ids, so the hook+ * resolves them through `document.getElementById` exactly as in production.+ */+function mountHeadings(tops: Array<[slug: string, top: number]>): Fixture {+ const scrollport = document.createElement('div');+ document.body.append(scrollport);+ for (const [slug, top] of tops) {+ const el = document.createElement('h2');+ el.id = slug;+ el.textContent = slug;+ scrollport.append(el);+ setRectTop(el, top);+ }+ return {+ slugs: tops.map(([slug]) => slug),+ scrollport,+ setTop: (slug, top) => {+ const el = document.getElementById(slug);+ if (el) setRectTop(el, top);+ },+ };+}++function setRectTop(el: HTMLElement, top: number) {+ el.getBoundingClientRect = () => ({ top, height: 30, bottom: top + 30 }) as DOMRect;+}++afterEach(() => {+ cleanup();+ document.body.replaceChildren();+});++describe('useActiveHeading (WYSIWYG geometry)', () => {+ test('picks the first heading visible in the top half of the viewport', () => {+ const { slugs } = mountHeadings([+ ['alpha', -400],+ ['beta', MID_Y - 50],+ ['gamma', MID_Y - 10],+ ['delta', MID_Y + 500],+ ]);++ const { result } = renderHook(() => useActiveHeading(slugs));++ expect(result.current).toBe('beta');+ });++ test('falls back to the last heading scrolled above the viewport when none is in the top half', () => {+ const { slugs } = mountHeadings([+ ['alpha', -900],+ ['beta', -300],+ ['gamma', MID_Y + 100],+ ['delta', MID_Y + 700],+ ]);++ const { result } = renderHook(() => useActiveHeading(slugs));++ expect(result.current).toBe('beta');+ });++ test('falls back to the first heading when the reader is above every heading', () => {+ const { slugs } = mountHeadings([+ ['alpha', MID_Y + 40],+ ['beta', MID_Y + 400],+ ]);++ const { result } = renderHook(() => useActiveHeading(slugs));++ expect(result.current).toBe('alpha');+ });++ test('reports no active heading when the document has no headings', () => {+ const { result } = renderHook(() => useActiveHeading([]));++ expect(result.current).toBeUndefined();+ });++ test('skips slugs with no corresponding element', () => {+ const { slugs } = mountHeadings([+ ['alpha', -200],+ ['gamma', MID_Y + 900],+ ]);++ const { result } = renderHook(() => useActiveHeading([slugs[0], 'never-rendered', slugs[1]]));++ expect(result.current).toBe('alpha');+ });++ test('re-measures on a scroll event from a nested scroll container', async () => {+ // `scroll` does not bubble from an element, so only a CAPTURE-phase document+ // listener observes the editor scrollport scrolling. Dropping capture leaves+ // the highlight frozen wherever it happened to land on mount.+ const { slugs, scrollport, setTop } = mountHeadings([+ ['alpha', MID_Y - 20],+ ['beta', MID_Y + 600],+ ['gamma', MID_Y + 1200],+ ]);++ const { result } = renderHook(() => useActiveHeading(slugs));+ expect(result.current).toBe('alpha');++ setTop('alpha', -500);+ setTop('beta', MID_Y - 20);+ setTop('gamma', MID_Y + 600);+ act(() => {+ scrollport.dispatchEvent(new Event('scroll'));+ });++ await waitFor(() => {+ expect(result.current).toBe('beta');+ });+ });+});diff --git a/packages/app/src/hooks/useActiveHeading.source-mode.dom.test.tsx b/packages/app/src/hooks/useActiveHeading.source-mode.dom.test.tsxnew file mode 100644index 000000000..0fbfbb4a4--- /dev/null+++ b/packages/app/src/hooks/useActiveHeading.source-mode.dom.test.tsx@@ -0,0 +1,240 @@+/**+ * Source-mode guard and view-arrival channel for `useActiveHeading`.+ *+ * In source mode the hook measures a CodeMirror view it reads out of an ambient+ * module-level registry rather than receiving as an argument, so the view can+ * legitimately be absent — during a mode toggle, a document switch, or an+ * editor-pool eviction. Two things follow, and this file pins both: an absent+ * view must yield no answer rather than a wrong one, and a view that arrives+ * after render must be picked up rather than leaving the outline frozen at its+ * mount-time answer.+ *+ * Geometry is pinned here only where the assertion is arithmetic over numbers the+ * stub supplies — the resolver's own transform, and which branch of the priority+ * order wins for a given set of positions. What is NOT pinned here is where a+ * browser actually places content: jsdom performs no layout, so any assertion+ * that depended on real measurement would be a green over fabricated numbers.+ * That belongs to the browser tier, which stays the oracle for the end-to-end+ * question of which heading is active as a reader scrolls.+ */++import { Text } from '@codemirror/state';+import type { EditorView } from '@codemirror/view';+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, test } from 'vitest';+import {+ getSourceViewForDoc,+ registerSourceView,+ unregisterSourceView,+} from '../editor/active-source-view';+import { useActiveHeading } from './useActiveHeading';++const DOC_NAME = 'source-mode-guard-doc';+const SOURCE_LINES = ['# Alpha', '', 'Prose.', '', '## Beta', '', '## Gamma'];+const SLUGS = ['alpha', 'beta', 'gamma'];++/** jsdom's default viewport height; the predicate's "top half" is above the midpoint. */+const MID_Y = window.innerHeight / 2;++/**+ * A view carrying only the members the source resolver reads. `documentTop` sits+ * at the bottom edge of the viewport and every line block is at a non-negative+ * offset, so no heading resolves into the top half and none has scrolled past —+ * the reader is above the whole document.+ */+function stubView(): EditorView {+ return {+ state: { doc: Text.of(SOURCE_LINES) },+ documentTop: window.innerHeight,+ scaleY: 1,+ lineBlockAt: (pos: number) => ({ from: pos, to: pos, top: pos, height: 20, bottom: pos + 20 }),+ } as unknown as EditorView;+}++/** 1-based lines of `SOURCE_LINES` carrying `# Alpha`, `## Beta`, `## Gamma`. */+const HEADING_LINES = [1, 5, 7];+/**+ * Deliberately not 1. `documentTop` and `BlockInfo.top` are both already in scaled+ * screen space, so the resolver must combine them by plain addition; exposing a+ * non-unit `scaleY` means a resolver that multiplies by it answers differently and+ * gets caught here rather than only under a CSS transform in production.+ */+const SCALE_Y = 2;+/** Tall enough that reading `.bottom` instead of `.top` changes which heading wins. */+const BLOCK_HEIGHT = 800;++/**+ * A view whose geometry is fully controlled, so the resolver's arithmetic becomes+ * observable without layout. Callers state where each heading should land in+ * SCREEN space; the document-space tops are back-computed through the transform+ * CodeMirror itself uses (`documentTop + BlockInfo.top`, no scaling), so an+ * arithmetic change in the resolver moves the answer.+ */+function geometryStub(documentTop: number, screenTops: readonly number[]): EditorView {+ const doc = Text.of(SOURCE_LINES);+ const topByFrom = new Map<number, number>();+ HEADING_LINES.forEach((lineNo, i) => {+ topByFrom.set(doc.line(lineNo).from, screenTops[i] - documentTop);+ });++ return {+ state: { doc },+ documentTop,+ scaleY: SCALE_Y,+ lineBlockAt: (pos: number) => {+ const top = topByFrom.get(pos) ?? 0;+ return { from: pos, to: pos, top, height: BLOCK_HEIGHT, bottom: top + BLOCK_HEIGHT };+ },+ } as unknown as EditorView;+}++function mountHeading(slug: string, top: number): void {+ const el = document.createElement('h2');+ el.id = slug;+ el.textContent = slug;+ el.getBoundingClientRect = () => ({ top, height: 30, bottom: top + 30 }) as DOMRect;+ document.body.append(el);+}++afterEach(() => {+ cleanup();+ const registered = getSourceViewForDoc(DOC_NAME);+ if (registered) unregisterSourceView(DOC_NAME, registered);+ document.body.replaceChildren();+});++describe('useActiveHeading (source mode)', () => {+ test('reports no active heading while no view is registered for the document', () => {+ const { result } = renderHook(() =>+ useActiveHeading(SLUGS, { isSourceMode: true, docName: DOC_NAME }),+ );++ expect(result.current).toBeUndefined();+ });++ test('reports no active heading when no document name is supplied', () => {+ const { result } = renderHook(() => useActiveHeading(SLUGS, { isSourceMode: true }));++ expect(result.current).toBeUndefined();+ });++ test('reports no active heading for a document with no headings', () => {+ registerSourceView(DOC_NAME, stubView());++ const { result } = renderHook(() =>+ useActiveHeading([], { isSourceMode: true, docName: DOC_NAME }),+ );++ expect(result.current).toBeUndefined();+ });++ test('picks up a view registered after the hook rendered', async () => {+ const { result } = renderHook(() =>+ useActiveHeading(SLUGS, { isSourceMode: true, docName: DOC_NAME }),+ );+ expect(result.current).toBeUndefined();++ act(() => {+ registerSourceView(DOC_NAME, stubView());+ });++ await waitFor(() => {+ expect(result.current).toBe('alpha');+ });+ });++ test('measures a view that was already registered at render time', () => {+ registerSourceView(DOC_NAME, stubView());++ const { result } = renderHook(() =>+ useActiveHeading(SLUGS, { isSourceMode: true, docName: DOC_NAME }),+ );++ expect(result.current).toBe('alpha');+ });++ test('returns to no answer when the view unregisters', async () => {+ const view = stubView();+ registerSourceView(DOC_NAME, view);+ const { result } = renderHook(() =>+ useActiveHeading(SLUGS, { isSourceMode: true, docName: DOC_NAME }),+ );+ expect(result.current).toBe('alpha');++ act(() => {+ unregisterSourceView(DOC_NAME, view);+ });++ await waitFor(() => {+ expect(result.current).toBeUndefined();+ });+ });++ test('selects the last heading scrolled above the viewport when none is in the top half', () => {+ // Alpha and Beta are above the viewport, Gamma is below the midpoint, so the+ // scrolled-past branch decides and the answer is Beta rather than Gamma.+ //+ // This case is the unit-tier oracle for the resolver's arithmetic+ // (`documentTop + lineBlockAt(from).top`), which the browser tier otherwise+ // pins alone — and which is inert to error while `scaleY` is 1, so production+ // would not catch a scaling mistake. Each plausible regression lands on a+ // different heading: scaling either term by `scaleY` answers Alpha, reading+ // `.bottom` instead of `.top` answers Alpha, and flipping `documentTop`'s sign+ // puts every heading below the fold so the first-heading fallback answers Alpha.+ registerSourceView(DOC_NAME, geometryStub(-2 * MID_Y, [-2 * MID_Y, -0.1 * MID_Y, 1.5 * MID_Y]));++ const { result } = renderHook(() =>+ useActiveHeading(SLUGS, { isSourceMode: true, docName: DOC_NAME }),+ );++ expect(result.current).toBe('beta');+ });++ test('prefers a heading in the viewport top half over one already scrolled past', () => {+ // Same geometry except Gamma now sits inside the top half. Both modes share+ // one predicate, so this is the source-side twin of the WYSIWYG priority pin+ // in useActiveHeading.dom.test.tsx: top-half wins over scrolled-past.+ registerSourceView(DOC_NAME, geometryStub(-2 * MID_Y, [-2 * MID_Y, -0.1 * MID_Y, 0.5 * MID_Y]));++ const { result } = renderHook(() =>+ useActiveHeading(SLUGS, { isSourceMode: true, docName: DOC_NAME }),+ );++ expect(result.current).toBe('gamma');+ });++ test('resolves heading elements in WYSIWYG mode even while a source view is registered', () => {+ // Both editors are mounted at once, so a registered source view is the NORMAL+ // state in WYSIWYG mode, not an edge case. Mode therefore has to select the+ // resolver — a selection keyed on view presence alone would silently measure+ // CodeMirror line positions for the rich-text pane.+ //+ // The two resolvers are set up to disagree: the DOM places Alpha in the top+ // half, while the registered stub's geometry would answer Gamma. Asserting+ // Alpha is what makes this a real pin rather than a coincidence.+ registerSourceView(DOC_NAME, geometryStub(-2 * MID_Y, [-2 * MID_Y, -0.1 * MID_Y, 0.5 * MID_Y]));+ mountHeading('alpha', MID_Y - 10);+ mountHeading('beta', MID_Y + 600);+ mountHeading('gamma', MID_Y + 900);++ const { result } = renderHook(() =>+ useActiveHeading(SLUGS, { isSourceMode: false, docName: DOC_NAME }),+ );++ expect(result.current).toBe('alpha');+ });++ test('still resolves heading elements in WYSIWYG mode with an empty registry', () => {+ // The guard declines only where the answer is unobtainable. Widening it to+ // "no registered view" would kill the WYSIWYG path, which never consults+ // the registry at all.+ mountHeading('alpha', MID_Y - 10);+ mountHeading('beta', MID_Y + 600);++ const { result } = renderHook(() =>+ useActiveHeading(['alpha', 'beta'], { isSourceMode: false, docName: DOC_NAME }),+ );++ expect(result.current).toBe('alpha');+ });+});diff --git a/packages/app/src/hooks/useActiveHeading.ts b/packages/app/src/hooks/useActiveHeading.tsindex 8b2bdb7ad..8baeb038c 100644--- a/packages/app/src/hooks/useActiveHeading.ts+++ b/packages/app/src/hooks/useActiveHeading.ts@@ -1,39 +1,105 @@-import { useEffect, useRef, useState } from 'react';+import type { EditorView } from '@codemirror/view';+import { useEffect, useRef, useState, useSyncExternalStore } from 'react';+import { getSourceViewForDoc, subscribeSourceViewRegistry } from '@/editor/active-source-view';+import { sourceHeadingLines } from '@/editor/source-heading-lines';++/** Screen-space top of a rendered heading element, or null when it is not in the DOM. */+function domHeadingTop(slug: string): number | null {+ const el = document.getElementById(slug);+ return el ? el.getBoundingClientRect().top : null;+}++/**+ * Resolve each heading's screen-space top from its source line rather than a DOM+ * node. CodeMirror renders only the lines near the viewport, so most heading+ * lines have no element at all; `lineBlockAt` answers from the height map for+ * every document position, measured or interpolated.+ *+ * `documentTop` and `BlockInfo.top` are both already in scaled screen space, so+ * they combine by plain addition and the sum lands in the space+ * `getBoundingClientRect().top` reports. Do NOT scale either term: the height map+ * is populated from `getBoundingClientRect().height`, CodeMirror divides block+ * values by `scaleY` when converting back to CSS pixels, and its own+ * `moveVertically` and `posAtCoords` combine the two with no multiply. Scaling+ * here would double-scale, which is inert while `scaleY` is 1 but wrong under any+ * CSS transform on an ancestor.+ *+ * Falling back to the heading elements in the hidden WYSIWYG pane would be worse+ * than having no answer: that pane keeps its layout while hidden but is+ * absolutely positioned, so it contributes nothing to the shared scrollport's+ * scroll range, and its taller content means the trailing headings can never+ * come into range at any scroll position.+ */+function sourceHeadingTop(view: EditorView): (slug: string) => number | null {+ const offsets = new Map<string, number>();+ for (const heading of sourceHeadingLines(view.state.doc)) {+ offsets.set(heading.slug, heading.from);+ }+ // Read once per resolver rather than once per slug: this getter is an uncached+ // `getBoundingClientRect()`, and nothing in the caller's loop mutates the DOM.+ const documentTop = view.documentTop;++ return (slug) => {+ const from = offsets.get(slug);+ if (from === undefined) return null;+ return documentTop + view.lineBlockAt(from).top;+ };+}/*** Tracks which heading is currently "active" based on scroll position.** Uses a capturing scroll listener on document to catch scrolling inside any- * container (including the editor's inner overflow-y-auto div). A heading is- * active when it is the last one whose top edge has scrolled past the viewport- * top (top <= 0). When nothing has scrolled past yet the first heading is used- * as the default, so the top heading is always highlighted at the top of the page.+ * container (including the editor's inner overflow-y-auto div). Priority is the+ * first heading visible in the top half of the viewport, else the last heading+ * scrolled past, else the first heading, so the top heading is always+ * highlighted at the top of the page.*- * Requires heading DOM elements to have `id` attributes matching the slugs,- * which the HeadingAnchors TipTap extension provides.- *- * Disabled (returns undefined) in source mode since CodeMirror headings- * don't have real DOM id attributes.+ * The two editing modes share the scrollport but not the geometry source.+ * WYSIWYG headings are real elements carrying `id` attributes, which the+ * HeadingAnchors TipTap extension provides. Source mode measures CodeMirror line+ * positions from the view registered for `docName`; that view can legitimately be+ * absent (mid mode-toggle, doc switch, editor-pool eviction) and there is no+ * answer to give then, so the hook reports none. Without the guard a source-mode+ * read falls through to `domHeadingTop`, which either finds no element and sticks+ * at the first heading, or — mid mode-toggle, while the hidden WYSIWYG pane is+ * still mounted — reads that pane's absolutely-positioned geometry and reports a+ * wrong active heading (the trap `sourceHeadingTop` documents above).*/-export function useActiveHeading(slugs: string[], isSourceMode = false): string | undefined {+export function useActiveHeading(+ slugs: string[],+ options: { isSourceMode?: boolean; docName?: string } = {},+): string | undefined {+ const { isSourceMode = false, docName } = options;const [activeSlug, setActiveSlug] = useState<string | undefined>(undefined);const rafRef = useRef<number | null>(null);+ // A view mounting is not a React state change, so tracking subscribes to the+ // registry instead of reading it once per mount — a view that arrives after+ // this hook first ran must still be picked up.+ const sourceView = useSyncExternalStore(+ subscribeSourceViewRegistry,+ () => (docName ? getSourceViewForDoc(docName) : null),+ () => null,+ );+useEffect(() => {- if (isSourceMode || slugs.length === 0) {+ if (slugs.length === 0 || (isSourceMode && !sourceView)) {setActiveSlug(undefined);return;}function compute() {+ // Rebuilt per frame: the source resolver reads the document it was handed,+ // and heading offsets move as the user types.+ const resolveTop = isSourceMode && sourceView ? sourceHeadingTop(sourceView) : domHeadingTop;const midY = window.innerHeight / 2;let scrolledPast: string | undefined; // last heading above the viewportlet topHalf: string | undefined; // first heading visible in the top halffor (const slug of slugs) {- const el = document.getElementById(slug);- if (!el) continue;- const top = el.getBoundingClientRect().top;+ const top = resolveTop(slug);+ if (top === null) continue;if (top < 0) {scrolledPast = slug;} else if (topHalf === undefined && top < midY) {@@ -65,7 +131,7 @@ export function useActiveHeading(slugs: string[], isSourceMode = false): stringrafRef.current = null;}};- }, [slugs, isSourceMode]);+ }, [slugs, isSourceMode, sourceView]);return activeSlug;}diff --git a/packages/app/tests/stress/outline-active-heading.e2e.ts b/packages/app/tests/stress/outline-active-heading.e2e.tsnew file mode 100644index 000000000..43216e8eb--- /dev/null+++ b/packages/app/tests/stress/outline-active-heading.e2e.ts@@ -0,0 +1,361 @@+/**+ * The outline pane's ACTIVE-heading indication — position marker, row+ * highlight, and `aria-current="location"` — must track the reader's scroll+ * position in BOTH editor modes. All three affordances render off one value, so+ * they are asserted together at every sample.+ *+ * STOP: do not "fix" source-mode tracking by reading heading rects out of the+ * DOM. In source mode every heading slug still resolves via+ * `document.getElementById` — to the HIDDEN WYSIWYG pane, which stays mounted+ * under `content-visibility: hidden` (painting is skipped but descendant layout+ * is preserved, so its rects are real, non-zero, and move as you scroll) and is+ * `position: absolute` (so it contributes nothing to the shared scrollport's+ * scrollHeight). Measuring it while the source pane scrolls yields confidently+ * WRONG tracking, not working tracking: the hidden pane is taller than the+ * scrollable range, so the last headings can never activate and mid-document+ * picks skew by the pane-height ratio. That is exactly why the two source-mode+ * assertions below are pinned to an EXACT expected heading at the bottom of the+ * document and at a clicked mid-document target, rather than to "something+ * became active".+ *+ * Both modes run through the same `expectTracksScroll` contract. The WYSIWYG+ * case is a protective pin (it passes today; nothing else in the suite asserts+ * the outline's active state), the source case is the target behavior.+ */++import { randomUUID } from 'node:crypto';+import type { Page } from '@playwright/test';+import {+ type ApiHelpers,+ expect,+ primeFullLayout,+ test,+ waitForActiveProviderSynced,+} from './_helpers';++const sourceToggle = (page: Page) => page.getByRole('radio', { name: 'Markdown source' });++const SCROLLPORT = '[data-testid="editor-scroll-container"]';++const HEADING_COUNT = 12;+const label = (ordinal: number) => `Heading ${String(ordinal).padStart(2, '0')}`;+const FIRST_LABEL = label(1);+const LAST_LABEL = label(HEADING_COUNT);++/**+ * Mid-document target for the click oracle. Deep enough that the hidden-pane+ * skew lands several headings short of it, shallow enough to stay clear of the+ * document's last section.+ */+const CLICK_TARGET_ORDINAL = 9;++const SWEEP_FRACTIONS = [0, 0.2, 0.4, 0.6, 0.8, 1] as const;++/**+ * Uniform section heights are load-bearing, not incidental. The hidden WYSIWYG+ * pane renders this document taller than the source pane, so with equal+ * sections a hidden-pane read tops out several headings short of the end. A+ * deliberately tall FINAL section would let that wrong read reach the last+ * heading anyway and silently drain the bottom-of-document assertion of its+ * discriminating power.+ */+const FILLER = 'Filler paragraph to force scrollable content. '.repeat(12);++const DOC = [+ '---',+ 'title: Outline Active Heading',+ '---',+ '',+ ...Array.from({ length: HEADING_COUNT }, (_, i) => {+ const level = i === 0 ? '#' : i % 3 === 0 ? '##' : '###';+ return [`${level} ${label(i + 1)}`, '', FILLER, FILLER, FILLER, ''];+ }).flat(),+].join('\n');++const headingLineText = (ordinal: number) => {+ const i = ordinal - 1;+ const level = i === 0 ? '#' : i % 3 === 0 ? '##' : '###';+ return `${level} ${label(ordinal)}`;+};++/** Await two animation frames: one for the hook's rAF-coalesced recompute, one for React's commit. */+const nextFrame = (page: Page) =>+ page.evaluate(+ () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ }),+ );++interface OutlineSample {+ /** Text of the row carrying `aria-current="location"`, or null when none does. */+ activeLabel: string | null;+ /** Must be exactly 1 — a set of navigation items has one current item. */+ ariaCurrentCount: number;+ /** The position marker, rendered only when an active row was resolved. */+ markerPresent: boolean;+ /** Rendered colour of the active row and of a non-active row: the visual highlight. */+ activeColor: string | null;+ inactiveColor: string | null;+ rowCount: number;+ scrollTop: number;+}++async function readOutline(page: Page): Promise<OutlineSample> {+ return page.evaluate((scrollport) => {+ const panel = document.querySelector('#panel-outline');+ const rows = [...(panel?.querySelectorAll('nav button') ?? [])];+ const current = rows.filter((r) => r.getAttribute('aria-current') === 'location');+ const active = current[0];+ const inactive = rows.find((r) => r !== active);+ const scroller = document.querySelector(scrollport);+ return {+ activeLabel: active?.textContent?.trim() ?? null,+ ariaCurrentCount: current.length,+ markerPresent: Boolean(panel?.querySelector('nav > div[aria-hidden="true"]')),+ activeColor: active ? getComputedStyle(active).color : null,+ inactiveColor: inactive ? getComputedStyle(inactive).color : null,+ rowCount: rows.length,+ scrollTop: scroller instanceof HTMLElement ? Math.round(scroller.scrollTop) : -1,+ };+ }, SCROLLPORT);+}++/**+ * Read the outline until two consecutive frames agree on both the active row+ * and the scroll offset. CodeMirror swaps estimated line heights for measured+ * ones as content enters the viewport and re-anchors `scrollTop` when it does,+ * so a single read can catch the pane mid-adjustment.+ */+async function readSettledOutline(page: Page): Promise<OutlineSample> {+ let last = await readOutline(page);+ await expect+ .poll(+ async () => {+ await nextFrame(page);+ const next = await readOutline(page);+ const stable = next.activeLabel === last.activeLabel && next.scrollTop === last.scrollTop;+ last = next;+ return stable;+ },+ { timeout: 10_000, intervals: [50, 100, 200] },+ )+ .toBe(true);+ return last;+}++/**+ * Park the scrollport at a fraction of its range, re-applying until the offset+ * stops moving — the same CodeMirror height re-measurement that `scrollTop` is+ * re-anchored by also changes `scrollHeight` underneath the target.+ */+async function scrollToFraction(page: Page, fraction: number): Promise<void> {+ await expect+ .poll(+ () =>+ page.evaluate(+ ([scrollport, frac]) => {+ const s = document.querySelector(scrollport as string);+ if (!(s instanceof HTMLElement)) return false;+ const target = (s.scrollHeight - s.clientHeight) * (frac as number);+ if (Math.abs(s.scrollTop - target) <= 2) return true;+ s.scrollTop = target;+ return false;+ },+ [SCROLLPORT, fraction] as const,+ ),+ { timeout: 10_000, intervals: [100, 150, 250] },+ )+ .toBe(true);+}++async function sweepOutline(page: Page): Promise<Array<{ f: number; sample: OutlineSample }>> {+ const samples: Array<{ f: number; sample: OutlineSample }> = [];+ for (const f of SWEEP_FRACTIONS) {+ await scrollToFraction(page, f);+ samples.push({ f, sample: await readSettledOutline(page) });+ }+ return samples;+}++const formatSweep = (samples: Array<{ f: number; sample: OutlineSample }>) =>+ samples+ .map(+ ({ f, sample }) =>+ ` f=${f.toFixed(1)} scrollTop=${sample.scrollTop} active=${JSON.stringify(+ sample.activeLabel,+ )} ariaCurrent=${sample.ariaCurrentCount} marker=${sample.markerPresent} rows=${+ sample.rowCount+ }`,+ )+ .join('\n');++const ordinalOf = (activeLabel: string | null) => {+ const match = /(\d+)$/.exec(activeLabel ?? '');+ return match ? Number(match[1]) : Number.NaN;+};++/**+ * The mode-independent contract. Both editor modes owe the reader the same+ * behaviour, so both run these assertions verbatim.+ */+function expectTracksScroll(+ samples: Array<{ f: number; sample: OutlineSample }>,+ mode: 'WYSIWYG' | 'source',+) {+ const table = `\n${mode} sweep:\n${formatSweep(samples)}\n`;++ // The sweep must actually have moved the reader through the document,+ // otherwise everything below is vacuous.+ expect(+ samples.at(-1)?.sample.scrollTop,+ `${mode}: the scrollport did not scroll — the assertions below would be vacuous.${table}`,+ ).toBeGreaterThan(1000);++ for (const { f, sample } of samples) {+ const at = `${mode} at f=${f.toFixed(1)}`;+ expect(sample.rowCount, `${at}: outline row count.${table}`).toBe(HEADING_COUNT);+ expect(+ sample.ariaCurrentCount,+ `${at}: exactly one row must carry aria-current="location".${table}`,+ ).toBe(1);+ expect(sample.markerPresent, `${at}: the position marker must render.${table}`).toBe(true);+ expect(+ sample.activeColor,+ `${at}: the active row must have a rendered colour.${table}`,+ ).not.toBeNull();+ expect(+ sample.activeColor,+ `${at}: the active row must be visually distinguished from a non-active row.${table}`,+ ).not.toBe(sample.inactiveColor);+ }++ // Bottom of the document is THE discriminating position: a hidden-pane read+ // tops out short of the end and can never reach the last heading.+ expect(+ samples.at(-1)?.sample.activeLabel,+ `${mode}: at maximum scroll the LAST heading must be active.${table}`,+ ).toBe(LAST_LABEL);++ expect(+ samples[0]?.sample.activeLabel,+ `${mode}: at the top of the document the first heading must be active.${table}`,+ ).toBe(FIRST_LABEL);++ const ordinals = samples.map(({ sample }) => ordinalOf(sample.activeLabel));+ expect(+ ordinals,+ `${mode}: the active heading must not move backwards while scrolling down.${table}`,+ ).toEqual([...ordinals].sort((a, b) => a - b));++ // Kills an implementation that reports a constant (or near-constant) heading+ // while still satisfying the two endpoint assertions by accident.+ expect(+ new Set(ordinals).size,+ `${mode}: the active heading must advance through the document, not sit on one row.${table}`,+ ).toBeGreaterThanOrEqual(4);+}++async function seed(api: ApiHelpers, page: Page, baseURL: string): Promise<string> {+ const docName = `outline-active-${randomUUID().slice(0, 8)}`;+ await api.createPage(`${docName}.md`);+ await page.addInitScript(() => {+ try {+ localStorage.setItem('ok-acp-follow-file-v1', '0');+ } catch {}+ });+ await page.goto(`/#/${docName}`);+ await waitForActiveProviderSynced(page);+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');+ await api.replaceDoc(docName, DOC);+ await expect+ .poll(+ async () => {+ const r = await fetch(`${baseURL}/api/page-headings?docName=${docName}`);+ if (!r.ok) return 0;+ const d = (await r.json()) as { headings?: unknown[] };+ return d.headings?.length ?? 0;+ },+ { timeout: 15_000, intervals: [200, 500, 1000] },+ )+ .toBe(HEADING_COUNT);+ await page.waitForFunction(+ (n) =>+ document.querySelectorAll('.ProseMirror h1, .ProseMirror h2, .ProseMirror h3').length === n,+ HEADING_COUNT,+ { timeout: 15_000 },+ );+ await primeFullLayout(page);+ await expect(page.locator('#panel-outline')).toBeVisible();+ return docName;+}++/** Switch to CodeMirror and re-prime: the source pane has its own layout. */+async function enterSourceMode(page: Page): Promise<void> {+ await sourceToggle(page).click();+ await page.waitForSelector('.cm-content');+ await page.waitForFunction(() => document.querySelectorAll('.cm-line').length > 5, null, {+ timeout: 15_000,+ });+ await primeFullLayout(page);+}++test.describe('outline active-heading tracking', () => {+ test('tracks scroll position in source mode', async ({ page, api, baseURL }) => {+ test.setTimeout(180_000);+ await seed(api, page, baseURL ?? '');+ await enterSourceMode(page);++ expectTracksScroll(await sweepOutline(page), 'source');+ });++ test('activates the clicked heading in source mode', async ({ page, api, baseURL }) => {+ test.setTimeout(180_000);+ await seed(api, page, baseURL ?? '');+ await enterSourceMode(page);++ const target = label(CLICK_TARGET_ORDINAL);+ await page.locator('#panel-outline nav button', { hasText: target }).click();++ // Outline navigation scrolls the heading's source line to the top of the+ // viewport, which is the independent oracle for this assertion: wait for+ // the line to actually be parked there before sampling.+ const lineText = headingLineText(CLICK_TARGET_ORDINAL);+ await expect+ .poll(+ () =>+ page.evaluate(+ ([scrollport, text]) => {+ const scroller = document.querySelector(scrollport as string);+ const line = [...document.querySelectorAll('.cm-line')].find(+ (l) => l.textContent?.trim() === text,+ );+ if (!(scroller instanceof HTMLElement) || !line) return -1;+ return Math.round(+ line.getBoundingClientRect().top - scroller.getBoundingClientRect().top,+ );+ },+ [SCROLLPORT, lineText] as const,+ ),+ { timeout: 15_000, intervals: [150, 250, 400] },+ )+ .toBeLessThan(200);++ const sample = await readSettledOutline(page);+ expect(+ sample.activeLabel,+ `source: after clicking "${target}" its own source line is parked at the top of the ` ++ `viewport, so it must be the active heading. Got ${JSON.stringify(sample.activeLabel)} ` ++ `at scrollTop=${sample.scrollTop}.`,+ ).toBe(target);+ expect(sample.ariaCurrentCount, 'source: exactly one row must be current.').toBe(1);+ expect(sample.markerPresent, 'source: the position marker must render.').toBe(true);+ });++ test('tracks scroll position in WYSIWYG mode', async ({ page, api, baseURL }) => {+ test.setTimeout(180_000);+ await seed(api, page, baseURL ?? '');++ expectTracksScroll(await sweepOutline(page), 'WYSIWYG');+ });+});diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 734a01da8..888f0bcc5 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1527,6 +1527,7 @@ export type {export { applyByPrefixSuffix } from './utils/apply-by-prefix-suffix.ts';export { ChunkedInsertError, chunkedYTextInsert } from './utils/chunked-insert.ts';export { createCodeFenceTracker } from './utils/code-fence-tracker.ts';+export { scanHeadingLine } from './utils/heading-scan.ts';export {AGENT_COLORS,AGENT_ICON_COLORS,diff --git a/packages/core/src/utils/heading-scan.test.ts b/packages/core/src/utils/heading-scan.test.tsnew file mode 100644index 000000000..4e41cbda2--- /dev/null+++ b/packages/core/src/utils/heading-scan.test.ts@@ -0,0 +1,110 @@+/**+ * The single heading-line admission predicate, shared by the server's outline+ * producer and the source-mode client scan. Both producers must agree on every+ * line, so this pins the accept/reject boundary directly rather than through+ * either caller.+ */++import { describe, expect, test } from 'vitest';+import { scanHeadingLine } from './heading-scan.ts';++/** Callers own the counter map; a fresh one means "first heading in a document". */+function counts(): Map<string, number> {+ return new Map();+}++describe('scanHeadingLine', () => {+ test('reports level, trimmed text, and slug for an accepted line', () => {+ expect(scanHeadingLine('## Section 8.9', counts())).toEqual({+ level: 2,+ text: 'Section 8.9',+ slug: 'section-8-9',+ });+ });++ test('accepts every ATX level from 1 to 6', () => {+ const levels = ['# One', '## Two', '### Three', '#### Four', '##### Five', '###### Six'].map(+ (line) => scanHeadingLine(line, counts())?.level,+ );++ expect(levels).toEqual([1, 2, 3, 4, 5, 6]);+ });++ test('rejects a seventh hash', () => {+ expect(scanHeadingLine('####### Seven', counts())).toBeNull();+ });++ test('trims padding around the heading text', () => {+ expect(scanHeadingLine('## Padded heading ', counts())).toEqual({+ level: 2,+ text: 'Padded heading',+ slug: 'padded-heading',+ });+ });++ test('accepts a tab between the hashes and the text', () => {+ expect(scanHeadingLine('#\tTabbed', counts())?.slug).toBe('tabbed');+ });++ test('tolerates a trailing carriage return', () => {+ // CRLF documents keep the `\r` on every line once split on `\n`.+ expect(scanHeadingLine('# Intro\r', counts())).toEqual({+ level: 1,+ text: 'Intro',+ slug: 'intro',+ });+ });++ test('rejects hashes with no separating whitespace', () => {+ expect(scanHeadingLine('#NoSpace', counts())).toBeNull();+ });++ test('rejects an indented hash line', () => {+ // CommonMark §4.2 allows up to three leading spaces; this predicate does+ // not, and the two producers must share that narrower rule so their+ // heading counts stay 1:1.+ expect(scanHeadingLine(' # Indented', counts())).toBeNull();+ });++ test('rejects hashes followed by no text', () => {+ expect(scanHeadingLine('### ', counts())).toBeNull();+ expect(scanHeadingLine('### ', counts())).toBeNull();+ expect(scanHeadingLine('#', counts())).toBeNull();+ });++ test('rejects a heading whose text slugs to nothing', () => {+ // The slug is the outline's identity; a heading that cannot produce one is+ // not addressable, so it is not a heading for either producer.+ expect(scanHeadingLine('## ---', counts())).toBeNull();+ expect(scanHeadingLine('## ***', counts())).toBeNull();+ expect(scanHeadingLine('## 🎉', counts())).toBeNull();+ });++ test('rejects a line with no hashes at all', () => {+ expect(scanHeadingLine('Plain paragraph', counts())).toBeNull();+ expect(scanHeadingLine('', counts())).toBeNull();+ });++ test('disambiguates repeated slugs through the caller-supplied counter map', () => {+ const shared = counts();++ expect(scanHeadingLine('# Intro', shared)?.slug).toBe('intro');+ expect(scanHeadingLine('## Intro', shared)?.slug).toBe('intro-1');+ expect(scanHeadingLine('### intro', shared)?.slug).toBe('intro-2');+ });++ test('a rejected line does not consume a slug count', () => {+ // An unaddressable heading must not shift the suffix of a later real one,+ // or the client and server outlines drift by a suffix.+ const shared = counts();++ expect(scanHeadingLine('## ---', shared)).toBeNull();+ expect(scanHeadingLine('#NotAHeading', shared)).toBeNull();+ expect(scanHeadingLine('# Intro', shared)?.slug).toBe('intro');+ });++ test('slugs non-ASCII text without transliterating it away', () => {+ expect(scanHeadingLine('## 東京', counts())?.slug).toBe('東京');+ expect(scanHeadingLine('## Café', counts())?.slug).toBe('cafe');+ });+});diff --git a/packages/core/src/utils/heading-scan.ts b/packages/core/src/utils/heading-scan.tsnew file mode 100644index 000000000..576b5197a--- /dev/null+++ b/packages/core/src/utils/heading-scan.ts@@ -0,0 +1,38 @@+import { getHeadingSlug, type HeadingEntry } from './slug.ts';++/** ATX heading: 1-6 hashes, whitespace, then non-empty text (CommonMark §4.2). */+const ATX_HEADING_RE = /^(#{1,6})\s+(.+)$/;++/**+ * Decide whether one markdown line is an ATX heading and, if so, produce its+ * entry. The `slugCounts` map is caller-owned so duplicate heading text+ * disambiguates across a whole document.+ *+ * This is the one line-shape predicate shared by the server's outline producer+ * (`extractHeadings`) and the client's source-mode enumerator+ * (`sourceHeadingLines`). Those two are joined by ordinal alone, so a line one+ * admits and the other skips shifts every heading after it — a silent off-by-N+ * that surfaces as outline rows pointing at the wrong place.+ *+ * A line whose text slugs to nothing is rejected and does not consume a slug+ * count, so it cannot shift a later duplicate's suffix.+ *+ * Frontmatter and fenced-code regions are the caller's concern; pair this with+ * `createCodeFenceTracker` and a frontmatter partition.+ */+export function scanHeadingLine(+ line: string,+ slugCounts: Map<string, number>,+): HeadingEntry | null {+ // Tolerate a Windows-style CR at the line end, as `createCodeFenceTracker`+ // does: consumers split on '\n' only, so a CRLF document leaves a trailing+ // '\r' that JS `.` cannot match, which would otherwise defeat the anchor and+ // leave every heading in the file unrecognized.+ const stripped = line.endsWith('\r') ? line.slice(0, -1) : line;+ const match = stripped.match(ATX_HEADING_RE);+ if (!match) return null;+ const text = match[2].trim();+ const slug = getHeadingSlug(text, slugCounts);+ if (!slug) return null;+ return { level: match[1].length, text, slug };+}diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 600aec7a8..e121cac43 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -97,7 +97,6 @@ import {FrontmatterPatchSuccessSchema,FrontmatterSchemasListSuccessSchema,FrontmatterSchemaWriteRequestSchema,- getHeadingSlug,getParseHealth,type HeadingEntry,HistorySuccessSchema,@@ -232,6 +231,7 @@ import {SyncStatusSchema,SyncTriggerRequestSchema,SyncTriggerSuccessSchema,+ scanHeadingLine,searchWorkspaceCorpus,skillLiveDocName,stripFrontmatter,@@ -3018,12 +3018,8 @@ export function extractHeadings(content: string): HeadingEntry[] {const isInCodeFence = createCodeFenceTracker();for (const line of body.split('\n')) {if (isInCodeFence(line)) continue;- const match = line.match(/^(#{1,6})\s+(.+)$/);- if (match) {- const text = match[2].trim();- const slug = getHeadingSlug(text, slugCounts);- if (slug) headings.push({ level: match[1].length, text, slug });- }+ const heading = scanHeadingLine(line, slugCounts);+ if (heading) headings.push(heading);}return headings;}diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex 0335d683f..9bfbd3d32 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -32,6 +32,7 @@ export {__resetShowAllWalkStatsForTesting,type ApiExtensionOptions,createApiExtension,+ extractHeadings,MANAGED_RENAME_ORIGIN,ROLLBACK_ORIGIN,safeSubdir,