Skip to content

fix: populate the table of contents on open and fix link navigation - #4448

Merged
Jocs merged 4 commits into
marktext:developfrom
NSO73:fix/toc-seed-navigation
Jun 18, 2026
Merged

Jocs merged 4 commits into
marktext:developfrom
NSO73:fix/toc-seed-navigation

Conversation

@NSO73

@NSO73 NSO73 commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Refs #2992, #4441

Summary

The @muyajs/core migration broke table-of-contents generation (acknowledged in #4441): the sidebar TOC stayed empty until the first edit, and clicking a TOC entry did not scroll to the heading (the click-to-navigate behaviour requested in #2992). This restores both:

  • Seed the TOC from the engine on file load and on tab switch. The engine emits no json-change in those paths, so listToc/toc stayed empty until a document change occurred.
  • Resolve TOC link clicks by heading order: @muyajs/core slugs are stable per-block ids that are not stamped onto the heading DOM, so a #slug selector never matched. Headings are now walked in document order and the slug mapped to its index.

Type of change

  • Bug fix (non-breaking, fixes an issue)
  • New feature (non-breaking, adds functionality)
  • Breaking change (causes existing functionality to change)
  • Documentation update

Test plan

Notes for reviewers

The slug→index mapping mirrors getTOC(), which walks headings in document order. If heading ids get stamped onto the DOM later (cf. #4412 for export), the #slug path could be restored.


By submitting this pull request, I confirm that my contribution is made under the terms of the MIT license.


fix_toc-compressed.mp4

@Jocs

Jocs commented Jun 15, 2026

Copy link
Copy Markdown
Member

@NSO73 Pls solve this conflicts

The @muyajs/core migration broke table-of-contents generation (see #4441):
the sidebar TOC stayed empty until the first edit, and clicking a TOC entry
did not scroll to the heading (the click-to-navigate behaviour requested in

- Seed the TOC from the engine on file load and on tab switch. The engine
  emits no json-change in those paths, so listToc/toc remained empty until a
  document change occurred.
- Resolve TOC link clicks by heading order. @muyajs/core slugs are stable
  per-block ids that are not stamped onto the heading DOM, so a `#slug`
  selector never matched; walk the headings in document order and map the
  slug to its index instead.

Refs #2992
Refs #4441
@NSO73

NSO73 commented Jun 15, 2026

Copy link
Copy Markdown
Contributor Author

Done — conflicts resolved as requested, following .github/CONTRIBUTING.md (rebased onto upstream/develop and force-pushed).

The only conflict was in editorWithTabs/editor.vue, where develop had meanwhile added preSourceModeSelection handling on the source-mode handoff. I combined both sides: replaceContent(newMarkdown, preSourceModeSelection) is kept and the TOC re-seed (UPDATE_TOC(getTOC())) is layered on top. store/editor.ts merged cleanly.

The PR is now MERGEABLE and pnpm run typecheck passes (exit 0).

@Jocs

Jocs commented Jun 16, 2026

Copy link
Copy Markdown
Member

Review

I verified both bugs against develop — they're real regressions from the muyajs → @muyajs/core migration, and the fix direction is correct.

Bugs confirmed

  • Empty TOC until first edit — listToc/toc are only populated by LISTEN_FOR_CONTENT_CHANGE (store/editor.ts:1384), which is wired solely to the json-change event (editor.vue:1712). File load, tab switch, and the constructor-seeded first document never emit json-change, so the TOC stays empty. Confirmed.
  • Click navigation broken — @muyajs/core slugs are random getUniqueId() values cached in a WeakMap (state/getTOC.ts:26-33) and are never stamped onto the heading DOM (headings only render as h${level}), so #${slug} can never match. Confirmed.

The seeding fix (4 entry points: mount, setMarkdownToEditor, source-mode replaceContent, tab-switch setContent) cleanly covers every "no json-change" path. 👍

Main concern: index mapping misaligns on nested / raw-HTML headings

scrollToHeader resolves the slug to its index in listToc, then indexes container.querySelectorAll('h1..h6')[index]. The two sources don't agree on which headings count:

  • getTOC walks top-level scrollPage.children only and does not recurse (state/getTOC.ts:46).
  • querySelectorAll('h1..h6') matches every heading in the editor root, including ones nested in blockquotes / list items (state/markdownToState.ts:284-361 shows headings can be children of those containers) and <h2>-style headings inside raw-HTML blocks.

If any such heading precedes the target, the DOM index is shifted relative to the listToc index and the click scrolls to the wrong heading. Documents with only top-level headings (the common case) work, but this is a real correctness gap.

Suggested fixes, most robust first:

  1. Stamp the stable slug onto the heading DOM as an id and restore the #slug selector — this keeps the host in sync with getTOC by construction. The PR already notes fix(muya): inline export CSS + heading ids for offline export & TOC anchors (PG7/PG8) #4412 may do this for export; that's the clean path.
  2. Otherwise, scope the query to top-level headings only, so the DOM set matches getTOC's set.

Minor

  • Duplication: scrollToHeader re-implements the getBoundingClientRect + animatedScrollTo math that scrollToElement (editor.vue:1188) already has. Consider extracting a shared scrollElementIntoView(el) helper.
  • Inaccurate comment: the UPDATE_TOC JSDoc says dropping the equal guard avoids keeping a stale TOC "when the new document's TOC was a subset of the old one." equal is deep-equal, so a subset is not deep-equal and the guard would already let the update through. The real rationale is just unconditional re-seed on load/switch — worth rewording to avoid confusion.

Test coverage

The PR cites the e2e TOC smoke test "added in #4441", but #4441 is still open and not merged into develop, so this change lands without a guarding regression test. The existing layout-toggles.spec.ts TOC test only toggles panel visibility and asserts nothing about TOC content or navigation. Please either add a test here or coordinate the merge order with #4441. A small unit test over UPDATE_TOC + the slug→index resolution would be cheap and could pin the nested-heading edge case above.

Verdict

The seeding half is solid. The navigation half works for typical documents but mis-scrolls when nested or raw-HTML headings are present — I'd prefer the DOM-id approach (aligned with #4412) or a top-level-scoped query before merge. Requesting changes on the navigation mapping + the test gap.

Address review on #4448: scrollToHeader resolved a slug to its index in
listToc, then indexed querySelectorAll('h1..h6'). getTOC only walks
top-level scrollPage children (no recursion), so headings nested in
blockquotes/list items or inside raw-HTML blocks were counted by the DOM
but not by getTOC, shifting every later index and scrolling to the wrong
heading.

Scope the DOM query to direct-child headings (:scope > h1..h6) so the DOM
set matches getTOC's set by construction. Extract the resolution into a
pure resolveTocHeadingElement (util/tocNavigation.ts) so it is unit
testable.

Also from the review:
- extract a shared scrollElementIntoView(el) helper, de-duping the
  getBoundingClientRect + animatedScrollTo math between scrollToHeader
  and scrollToElement
- reword the UPDATE_TOC JSDoc: it is an unconditional re-seed on
  load/switch, drop the inaccurate deep-equal 'subset' rationale
- add toc-navigation.spec.ts covering UPDATE_TOC (seed + unconditional
  re-seed) and the slug->index resolution, pinning the nested / raw-HTML
  heading edge case (no longer relying on the unmerged #4441 e2e)

Refs #4448
@NSO73

NSO73 commented Jun 17, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review — both bugs and the index-mapping concern are spot on. I've pushed a follow-up commit.

On the navigation mapping — I went with the top-level-scoped query rather than the DOM-id approach, and want to be transparent about why, because I think the "aligned with #4412" basis doesn't actually hold yet.

I checked: #4412's _injectHeadingIds runs on a throwaway export container built by marked inside renderHtml() — it never stamps ids onto the live editor DOM. The block-tree headings rendered by the editor have no id, so there's no reusable base for live navigation.

Stamping the slug onto the live DOM properly would require, concretely:

  1. An engine-side change in @muyajs/core. The live DOM is re-patched by snabbdom on every edit, so any host-stamped id is wiped on the next patch — the id has to be produced by the render (vnode) or a post-render pass inside the engine.
  2. Global slug dedup. GitHub dedups by document order (heading, heading-1, …), but getTOC currently returns githubSlug undeduped, and a single heading block can't dedup against its siblings — so this needs a whole-document post-pass (like _injectHeadingIds does for export) re-run after each patch.
  3. Switching the sidebar to navigate by githubSlug instead of the random per-block slug, and keeping it consistent with copyGithubSlug / FORMAT_LINK_CLICK.

That's a genuinely nice unification (live navigation + export anchors on one slug scheme), but it's a cross-package change with its own dedup/collision test surface, and it really belongs with the #4412/#4441 lineage rather than a regression fix.

So this PR takes your second suggestion: scope the DOM query to direct-child headings of the container (:scope > h1…h6). That matches the exact set getTOC enumerates (it only walks top-level scrollPage children, no recursion), so nested/raw-HTML headings can no longer shift the index. Correct-by-construction, self-contained, survives re-render.

Is the scoped-query approach acceptable to you for this PR, with the DOM-id unification tracked as follow-up work alongside #4412/#4441? Happy to do the engine-side id approach instead if you'd rather block on it — just wanted to surface the actual cost before committing to it.

Other review items addressed in the same commit:

  • Extracted a shared scrollElementIntoView(el) helper (de-dups the getBoundingClientRect + animatedScrollTo math between scrollToHeader/scrollToElement).
  • Reworded the UPDATE_TOC JSDoc — dropped the inaccurate "subset" rationale; it's just an unconditional re-seed on load/switch.
  • Test gap: added toc-navigation.spec.ts (no longer relying on test(e2e): add image rendering and TOC sidebar smoke tests #4441's e2e). It covers UPDATE_TOC (seed + unconditional re-seed) and the slug→index resolution, with a case that interleaves a blockquote-nested <h2> and a raw-HTML <h2> to pin exactly the edge you flagged — they're skipped, so the slug still resolves to the right top-level heading.

NSO73 added 2 commits June 17, 2026 18:40
Runtime verification (opening a doc and clicking a TOC entry) surfaced
that the previous ':scope > hN' selector matched zero headings: the
scroll container returned by getScrollContainer() is muya's root
(.mu-editor), which WRAPS the scrollPage root (.mu-container) whose
direct children are the top-level blocks. The headings are one level
deeper than ':scope >' looked, so the click resolved to nothing and the
editor never scrolled.

Anchor the selector on '.mu-container > hN' so it matches the top-level
headings wherever .mu-container sits under the scroll container, while
still excluding nested (blockquote/list) and raw-HTML headings. Update
the unit fixture to mirror the real .mu-editor > .mu-container > heading
nesting so a regression to a scroller-scoped selector is caught.

Verified in-app: TOC seeds with the 3 top-level headings on open, and
clicking 'Top Two' scrolls it to the target offset (y=320) past the
interleaved blockquote/raw-HTML headings.

Refs #4448
@NSO73

NSO73 commented Jun 17, 2026

Copy link
Copy Markdown
Contributor Author

Small correction + verification follow-up on the navigation fix.

I verified the change by actually running the app (open a doc, click a TOC entry) and the first version of the scoped selector was wrong: getScrollContainer() returns muya's root (.mu-editor), which wraps the scrollPage root (.mu-container) whose direct children are the top-level blocks. So :scope > h1…h6 on the scroll container matched zero headings — the click resolved to nothing and the editor didn't scroll.

Fixed by anchoring the selector on .mu-container > h1…h6 (pushed in 8af9498). It still matches exactly the set getTOC enumerates (top-level scrollPage children) and excludes blockquote/list-nested and raw-HTML headings, but now it works regardless of where .mu-container sits under the scroll container.

Verified in-app on a doc that interleaves a blockquote ## … and a raw-HTML <h2> between the top-level headings:

  • the sidebar TOC seeds with exactly the 3 top-level headings on open (no edit), and
  • clicking "Top Two" scrolls the real top-level "Top Two" to the target offset (y≈320), past the interleaved nested/raw-HTML headings.

The unit fixture in toc-navigation.spec.ts now mirrors the real .mu-editor > .mu-container > heading nesting so a regression back to a scroller-scoped selector is caught.

Branch is also synced with develop (current as of this comment).

@Jocs
Jocs merged commit a852891 into marktext:develop Jun 18, 2026
9 checks passed
@NSO73
NSO73 deleted the fix/toc-seed-navigation branch June 18, 2026 12:10
hisaboh added a commit to hisaboh/remarks that referenced this pull request Jun 20, 2026
Catch up the fork with upstream's recent work: muya engine refactors
(selection-API rework, private `_`-prefix members, paste/clipboard re-audit,
complexity reduction, quick-insert refactor), desktop fixes (marktext#4448 TOC-on-open +
link nav, folder-search caret reveal, screenshot paste), Turkish locale, and
the configurable PlantUML server URL.

Conflict resolution (22 files):
- Adopted upstream's superseding refactors: paste re-audit, quick-insert
  buildReplacementBlock (carries text → subsumes #7), createTable keep/replace,
  selection-API shape, `_muya`/`_apply` renames, focus-restore (subsumes #2),
  UPDATE_TOC (subsumes #19).
- Preserved fork-only features on top of the refactors: blank-line round-trip
  (preserveEmptyLines + heading recovery + fence-info `meta.info`), PDF
  rasterisation (now lazy-imports pdfjs-dist so the engine import stays Node-safe
  and DOMMatrix no longer breaks tests), `_extendSelectionAcrossBlocks`,
  `flushPendingChanges`, Tauri renderer bootstrap, fresh-doc caret (#15/#16),
  and whole-line paste (df174e6 — re-applied over upstream's paste, real-engine
  spec rewritten for the new selection shape).
- Locales: took upstream's restructured files + re-applied the Remarks rebrand
  (value-only MarkText→Remarks). Regenerated pnpm-lock.yaml.

Verified: muya typecheck/lint/circular clean, unit 1125, CommonMark+GFM 1347;
desktop typecheck clean, unit 571.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Jocs Jocs mentioned this pull request Jul 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants