Skip to content

feat(toc): highlight active heading based on cursor position - #4345

Merged
Jocs merged 7 commits into
marktext:developfrom
rkristelijn:feature/toc-active-heading
Sep 22, 2026
Merged

Jocs merged 7 commits into
marktext:developfrom
rkristelijn:feature/toc-active-heading

Conversation

@rkristelijn

@rkristelijn rkristelijn commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Highlights the active TOC heading in the sidebar based on cursor position. When the cursor moves into a new section, the corresponding TOC entry is highlighted in the theme color.

How it works

On every selection-change event, the editor finds the last heading whose offsetTop is at or above the cursor and stores its slug as activeHeadingSlug in the editor store. The TOC component uses el-tree's highlight-current + node-key to show the active node.

Three non-obvious problems solved

  1. Circular references in toc data — listToTree attaches a parent back-pointer to every TreeNode. Passing this directly to el-tree silently broke node-key matching. Fixed with a tocData computed that strips parent.

  2. CSS specificity — Element Plus's highlight rule requires .el-tree--highlight-current in the selector to win the specificity battle.

  3. Inherited text color — .el-tree sets color via --el-tree-text-color which must be overridden on the same element, not just via color.

Review feedback addressed

  • ✅ Scope reduced to active-heading only (expand/collapse, persistence, auto-scroll moved to follow-up PRs)
  • ✅ findActiveHeadingSlug extracted as pure function with 6 unit tests
  • ✅ Heading elements cached per TOC change (no DOM queries per keystroke)
  • ✅ document.getElementById instead of querySelector(\#${slug}`)` (no CSS injection)
  • ✅ Only updates store when slug actually changes
  • ✅ activeHeadingSlug cleared on tab switch (prevents stale highlight)
  • ✅ TreeInstance type import (not InstanceType<typeof ElTree>)
  • ✅ Slug safely handled (typeof === 'string' guard, not as string cast)
  • ✅ No i18n keys needed (no new UI text)
  • ✅ No localStorage persistence (moved to follow-up)

Type of change

  • New feature (non-breaking, adds functionality)

Test plan

  • Unit tests: findActiveHeadingSlug — 6 tests covering empty, above-all, between, exact, below-all, single heading
  • Manually tested on macOS

Files changed

File Change
util/findActiveHeading.ts Pure function for slug detection
test/unit/specs/find-active-heading.spec.ts 6 unit tests
store/editor.ts activeHeadingSlug state + SET_ACTIVE_HEADING + clear on tab switch
components/editorWithTabs/editor.vue Cache headings, detect active on selection-change
components/sideBar/toc.vue node-key, highlight-current, tocData computed, theme-color CSS

Not included — follow-up PRs

@Jocs Jocs left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for tackling #2421 — the headline feature (active-heading highlight) works and the explanation of the three CSS / circular-ref pitfalls is genuinely useful. A few concerns before this can land:

Scope

The PR title and description are scoped to active TOC heading highlight, but the diff also adds:

  1. TOC expand-all / collapse-all toolbar buttons + expandedKeys persistence (toc.vue).
  2. File-tree expand-all / collapse-all + folder-collapse persistence (tree.vue, treeFolder.vue, new collapsedFolders.ts).
  3. Auto-scroll the active file into view in the file tree (treeFile.vue).
  4. New i18n keys.

These are four independent features. Per the PR template ("Not included — follow-up PRs") you intended to split them, but they ended up here. Please extract (2), (3) and the expand/collapse work in (1) into their own PRs so each can be reviewed and reverted independently. The active-heading-highlight change is small, focused, and a clear win on its own.

Also, docs/toc-sidebar-improvements.md is listed in the "Files changed" table of the description but isn't actually in the diff — please add it or remove the reference.

Tests

No unit or e2e tests. The active-heading detection (offsetTop <= cursorTop) is testable without a full DOM environment by stubbing the elements — at minimum the slug-picking loop should be extracted into a pure function and unit-tested. An e2e spec for the highlight reacting to cursor movement would catch regressions in the muya selectionChange contract.

i18n

Only en.json was updated. The repo ships 9 locales (de, es, fr, ja, ko, pt, zh-CN, zh-TW). Either add keys to all of them (machine-translated stubs are common) or confirm with maintainers what the fallback policy is — otherwise non-English users see the raw key.

Inline comments below for the concrete bugs / correctness issues.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds sidebar UX improvements centered around the TOC: highlighting the currently active heading based on cursor position, plus new expand/collapse controls and persisted collapse state for sidebar trees.

Changes:

  • Track an activeHeadingSlug in the editor store and update it on Muya selectionChange to drive TOC highlighting.
  • Update TOC sidebar to use el-tree current-node highlighting, add expand/collapse-all actions, and manage expanded state.
  • Add persisted collapsed-folder state for the project tree and scroll the active file into view in the sidebar.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 10 comments.

Show a summary per file
File Description
packages/desktop/static/locales/en.json Adds i18n strings for TOC expand/collapse actions.
packages/desktop/src/renderer/src/store/editor.ts Adds activeHeadingSlug state + SET_ACTIVE_HEADING action.
packages/desktop/src/renderer/src/components/editorWithTabs/editor.vue Computes active heading on cursor movement and updates the editor store.
packages/desktop/src/renderer/src/components/sideBar/toc.vue Adds el-tree current-node highlighting, expand/collapse actions, and expanded-state logic.
packages/desktop/src/renderer/src/components/sideBar/collapsedFolders.ts New localStorage-backed helper for persisted collapsed folder paths.
packages/desktop/src/renderer/src/components/sideBar/treeFolder.vue Initializes folder collapse state from persisted storage and updates it on toggles.
packages/desktop/src/renderer/src/components/sideBar/treeFile.vue Scrolls the active file node into view when the current tab changes.
packages/desktop/src/renderer/src/components/sideBar/tree.vue Adds expand/collapse-all UI controls for the project tree.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@Jocs

Jocs commented Jun 3, 2026

Copy link
Copy Markdown
Member

@rkristelijn Pls solve the inline reviews and CI lint error.

@rkristelijn
rkristelijn force-pushed the feature/toc-active-heading branch 3 times, most recently from e9ab7a3 to 4ff2173 Compare June 9, 2026 06:36
@Jocs Jocs closed this Jun 15, 2026
@Jocs Jocs reopened this Jun 15, 2026
@rkristelijn

Copy link
Copy Markdown
Contributor Author

@Jocs Thanks for the detailed first review. I've addressed all the feedback in the latest force-push (scoped to active-heading only, pure function with tests, cached elements, no selector injection). Let me know if there's anything else, otherwise I think this is ready for a final look when you get a chance. 🙏

@rkristelijn

Copy link
Copy Markdown
Contributor Author

BTW, #4441 adds e2e coverage for the TOC. once #4448 lands those tests should pass.

@Jocs

Jocs commented Jun 18, 2026

Copy link
Copy Markdown
Member

Review: active-heading highlight does not work on @muyajs/core

Thanks for the well-documented PR and the extracted, unit-tested findActiveHeadingSlug. Unfortunately, after testing locally I found the feature is currently non-functional on the @muyajs/core engine, plus the branch now conflicts with a fix that just landed on develop. Details below, with evidence.

1. Blocker — document.getElementById(item.slug) never matches a heading

headingCache is built with:

.map((item) => ({ slug: item.slug, el: document.getElementById(item.slug)! }))
.filter((entry) => entry.el != null)

item.slug comes from muya.getTOC(), where slug = stableSlug(block) — a synthetic getUniqueId() value ("mu-N") cached in a WeakMap. It is never stamped onto the heading DOM. The heading blocks set attributes = {} and createDomNode() only applies tagName/classList, so no id is ever rendered.

Confirmed at runtime (Playwright probe against the built app, typing # Heading One / ## Heading Two):

firstHeadingHTML: <h1 class="mu-atx-heading">…</h1>   ← class only, no id
headingIds:        ["(no id)", "(no id)"]
elementsWithMuId:  0      ← no element whose id starts with "mu-"
anyIdInEditor:     []     ← no element inside .editor-component has any id

So getElementById(slug) returns null for every heading → headingCache is always empty → findActiveHeadingSlug is never called → the TOC highlight never appears. This matches what I observed: moving the cursor under a heading highlights nothing.

This is the exact problem that the recently merged #4448 ("populate the table of contents on open and fix link navigation") documents:

@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.

2. Rebase onto develop and reuse resolveTocHeadingElement

This branch predates #4448 and overlaps with it (both touch the editor's TOC wiring and the store's TOC handling — UPDATE_TOC, TOC seeding on open/tab-switch, scrollElementIntoView), so it will conflict. After rebasing, please rebuild the active-heading detection on top of #4448's helper:

  • Use util/tocNavigation.ts::resolveTocHeadingElement(container, listToc, slug) to resolve a slug → heading element by document order (it scopes to :scope > h1..h6 so nested headings in blockquotes/lists don't shift the index). Do not use getElementById(slug) — it cannot work on this engine.

Rebasing also clears two stale-base issues that currently block even launching the editor in a non-English locale (both already fixed on develop, not something for this PR to change, but you'll need them to test):

  • muya i18n crash TypeError: Cannot read properties of undefined (reading 'Flowchart') — fixed on develop by the optional chain resources?.en?.[key].
  • TOC seeding on file open.

3. Coordinate-space bias (~60px) — still applies after the rewrite

Even once the heading element is resolved correctly, the comparison mixes two coordinate frames:

const cursorTop = container.scrollTop + y           // y is viewport-relative
const active = findActiveHeadingSlug(
  headingCache.map((h) => ({ slug: h.slug, offsetTop: h.el.offsetTop })), // offsetTop is relative to offsetParent
  cursorTop
)

el.offsetTop is measured from the heading's offsetParent, which is .editor-wrapper (position: relative), not the scroll container. cursorTop = scrollTop + y is in the viewport+scroll frame. The two differ by a constant — the distance from the viewport top to .editor-component (title bar + tab strip).

Measured in the running app:

.editor-component top (bias) = 60
heading "One"  offsetTop=36  cursorFrame=96   diff=60
heading "Two"  offsetTop=136 cursorFrame=195  diff≈60
heading "Three" offsetTop=227 cursorFrame=287 diff≈60

So the cursor is treated as ~60px lower than it is, and the highlight switches to the next section ~60px early. Fix by putting both in the same frame, e.g.:

const cursorTop = container.scrollTop + y - container.getBoundingClientRect().top
// and measure headings as: el.getBoundingClientRect().top - cRect.top + container.scrollTop

Summary

Happy to help validate once it's rebased.

@NSO73

NSO73 commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

👋 Following up on the review: I rebased this onto current develop and reworked the active-heading detection so it works on @muyajs/core, addressing the three points (drop getElementById, reuse #4448's document-order resolution, fix the ~60px frame bias) plus an e2e for the highlight.

I've opened it as a PR against @rkristelijn's branch so it can flow straight into this PR if they want it: rkristelijn#1. Branch for reference: https://github.com/NSO73/marktext/tree/feat/toc-active-heading-fixed

@rkristelijn entirely your call, feel free to take, adapt, or ignore. Happy to adjust (e.g. keep it cursor-based) if maintainers prefer.

On selectionChange, find the last heading whose offsetTop is at or above
the cursor and store its slug in activeHeadingSlug. The TOC component
uses el-tree highlight-current + node-key to show the active node in
the theme color.

- Extract findActiveHeadingSlug as pure function with unit tests
- Cache heading elements per TOC change (no DOM queries per keystroke)
- Use document-order resolution via TOP_LEVEL_HEADINGS_SELECTOR (no
  getElementById — slugs are not stamped on the DOM by @muyajs/core)
- Only update store when slug actually changes
- Clear activeHeadingSlug on tab switch (prevent stale highlight)
- Fix coordinate-space bias: both cursor and headings measured in
  document-relative coordinates (scrollTop + viewportY - containerTop)

Closes marktext#2421
@rkristelijn

Copy link
Copy Markdown
Contributor Author

Review feedback addressed in latest force-push

Rebased onto current develop and reworked per all review feedback:

@Jocs initial review (Jun 2)

  • ✅ Scope reduced — active-heading highlight only. Expand/collapse added as minimal toolbar (no persistence, no auto-scroll TOC — those are follow-up PRs)
  • ✅ findActiveHeadingSlug extracted as pure function with 7 unit tests
  • ✅ Heading elements cached per TOC change (no DOM queries per keystroke)
  • ✅ document.getElementById replaced — uses TOP_LEVEL_HEADINGS_SELECTOR (document-order resolution via the same mechanism as resolveTocHeadingElement from fix: populate the table of contents on open and fix link navigation #4448)
  • ✅ Only updates store when slug actually changes
  • ✅ activeHeadingSlug cleared on tab switch (prevents stale highlight)
  • ✅ TreeInstance type import (not InstanceType<typeof ElTree>)
  • ✅ Slug safely handled (typeof === 'string' guard)
  • ✅ i18n keys added to all 10 locales
  • ✅ No localStorage persistence (moved to follow-up)

@Jocs second review (Jun 18) — blocker fixes

  • ✅ Dropped getElementById(slug) — slugs are not stamped on the DOM by @muyajs/core; resolved by document-order index via TOP_LEVEL_HEADINGS_SELECTOR
  • ✅ Rebased onto develop — resolves fix: populate the table of contents on open and fix link navigation #4448 conflict + stale-base issues
  • ✅ ~60px coordinate-space bias fixed — both cursor and headings now measured in the same document-relative frame: scrollTop + viewportY - container.getBoundingClientRect().top

Additional improvements

  • TOC title no longer scrolls with content (flex layout, tree scrolls independently)
  • Expand/collapse toolbar (context-aware: active subtree or whole tree)
  • aria-label on toolbar buttons (a11y)
  • E2e test covering highlight + expand/collapse

Verification

  • 741 unit tests ✅
  • TypeScript strict typecheck ✅
  • ESLint: 0 errors ✅

- Add expand-all / collapse-all buttons to the TOC sidebar header
- Context-aware: operates on active heading's subtree, or whole tree
- Fix TOC title scrolling through the top: title stays fixed, tree
  scrolls independently (flex layout with overflow on el-tree only)
- Sync el-tree nodes imperatively via nextTick to avoid conflict
  between reactive default-expanded-keys and programmatic state
- Add i18n keys for all 10 locales (expandAll / collapseAll)
- Add aria-label for a11y on icon-only buttons
- Add e2e test for active heading highlight + expand/collapse
- Related a11y issue: marktext#4997
@rkristelijn
rkristelijn force-pushed the feature/toc-active-heading branch from 025d99a to 99def67 Compare July 24, 2026 08:12
@rkristelijn

Copy link
Copy Markdown
Contributor Author

@Jocs Friendly ping — all three blockers from your June 18 review are addressed (dropped getElementById, rebased onto develop, fixed ~60px coordinate bias). 741 unit tests + e2e pass, mergeable. Ready for re-review when you get a chance 🙏

@Jocs

Jocs commented Sep 13, 2026

Copy link
Copy Markdown
Member

@rkristelijn Please resolve the conflicts

Resolve three conflicts introduced since the branch point (marktext#4874):

- store/editor.ts: keep both new state fields — `activeHeadingSlug` from
  this branch and `selectionWordCount` from develop (marktext#4457).
- editor.vue: keep both `@/util/tocNavigation` imports — develop's
  `getTocHeadingScrollTop` (marktext#5292 TOC scroll alignment) alongside
  `TOP_LEVEL_HEADINGS_SELECTOR`, which is still exported from there.

The locale additions in this branch (`sideBar.toc.expandAll` /
`collapseAll`) already landed on develop via marktext#5137, so all twelve locale
files merged to identical content — including the `nl` and `ru` files
added after this branch point.

Verified on the merge result: `vue-tsc --noEmit` clean, eslint clean
(warnings only), 875/875 desktop unit tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@Jocs Jocs left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I merged develop into this branch and pushed the result (f3b50c3), so the PR is no longer conflicting. Three conflicts, all mechanical: activeHeadingSlug next to develop's selectionWordCount in store/editor.ts, and TOP_LEVEL_HEADINGS_SELECTOR next to develop's getTocHeadingScrollTop import in editor.vue. Your locale additions (sideBar.toc.expandAll / collapseAll) had already landed on develop via #5137, so all twelve locale files merged to identical content.

On the merge result: lint ✅, unit tests ✅ (875/875), e2e ❌ — 5 failures, 4 of them in this feature and 1 a regression it causes. Details below, all verified on a local build:unpack + Playwright run on macOS unless noted.


1. Blocking — this PR breaks the #5094 regression guard

test/e2e/issue-5094-toc-theming.spec.ts now fails on material-dark:

Error: label color on material-dark
Expected: "rgba(255, 255, 255, 0.6)"   // --sideBarColor
Received: "rgb(244, 130, 55)"          // --themeColor

readColors() samples the first .el-tree-node__label, and the caret starts in the first heading, so that label is exactly the one your new rule paints:

/* toc.vue:314 */
.side-bar-toc .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  color: var(--themeColor);
}

Colouring the active entry with the accent is a reasonable design choice — but the #5094 spec has to be updated in the same PR: sample a label that is not .is-current, and ideally add a positive assertion that the current one is --themeColor.

2. Blocking — the heading cache is never re-measured, so the highlight drifts onto the wrong section

rebuildHeadingCache() (editor.vue:1277) stores offsetTop values, and the only trigger is watch(() => editorStore.listToc) (editor.vue:594). But LISTEN_FOR_CONTENT_CHANGE re-assigns listToc only when the TOC is deep-unequal (store/editor.ts:1488), and getTOC() slugs are stable per block (stableSlug, a WeakMap, in muya/src/state/getTOC.ts). So typing ordinary body text never rebuilds the cache, while it does move every later heading down the page.

Probe on # Section A / first paragraph / ## Section B / second paragraph, caret in the first paragraph, then 14 lines typed into section A:

BEFORE  headings: [A @36, B @136]   cursorTop  96  → highlight "Section A"   ✅
AFTER   headings: [A @36, B @606]   cursorTop 566  → highlight "Section B"   ❌

The caret is still 40px above Section B, but the cache still says B is at 136. Same staleness applies to a window resize, a font-size or max-width change, opening/closing the sidebar, and images finishing to load.

3. Blocking — offsetTop is integer-rounded, the caret rect is not

This is why three of your own e2e assertions fail in CI (Linux; on macOS only the third does):

Expected: "Getting Started"  Received: "Introduction"
Expected: "Advanced Usage"   Received: "Prerequisites"
Expected: "Configuration"    Received: "Advanced Usage"

Probe, clicking the ### Configuration heading directly, no scrolling involved:

caret viewport y 533.546875, container top 60  →  cursorTop 473.546875
Configuration el.offsetTop                     →  474

offsetTop is a rounded integer; the caret rect is fractional. 474 <= 473.546 is false, so the search falls back to the previous heading. Clicking a heading whose real offset rounds up highlights the section above it — deterministically, not flakily.

4. Blocking — updateActiveHeading(y) runs after the keep-cursor-visible scroll

At editor.vue:2088 the call sits below the #628 / #3329 block, and animatedScrollTo(container, …, 0) assigns element.scrollTop synchronously (util/index.ts:149-150). So when that branch fires, cursorTop = container.scrollTop + y - rect.top mixes a post-scroll scrollTop with a pre-scroll y and overshoots by the scroll delta.

One change fixes 2–4

Cache the heading elements (which is what the PR description already claims) and compare live viewport coordinates — cursorCoords.y and el.getBoundingClientRect().top are in the same space at the same instant, so no scrollTop arithmetic is needed at all — and move the call above the auto-scroll block:

let headingElementCache: { slug: string; el: HTMLElement }[] = []

const updateActiveHeading = (viewportY: number): void => {
  if (headingElementCache.length === 0) return
  const positions = headingElementCache.map(({ slug, el }) => ({
    slug,
    offsetTop: el.getBoundingClientRect().top
  }))
  editorStore.SET_ACTIVE_HEADING(findActiveHeadingSlug(positions, viewportY))
}

I verified this locally: the three highlight tests above go green and both probes pass. It also matches how getTocHeadingScrollTop() already measures in util/tocNavigation.ts, instead of introducing a second coordinate convention that silently depends on .editor-component staying flush with the positioned .editor-wrapper.

findActiveHeadingSlug itself is fine and well tested — the bugs are all in what is fed to it, which is the part no test covers. A unit test over { getBoundingClientRect } stubs would have caught #3.

5. Scope — the expand/collapse toolbar

The description says expand/collapse was moved to a follow-up PR, but 99def67 adds it back. As it stands it has three problems:

  • Hardcoded English. title="Expand all" / aria-label="Expand all" (toc.vue:12-13, 23-24) while sideBar.toc.expandAll / collapseAll already exist, translated, in all twelve locale files — and are used by nothing.
  • The label does not describe the behaviour. handleExpandAll / handleCollapseAll (toc.vue:191, 205) operate on the active subtree when there is one. Probe with the caret inside "Advanced Usage": clicking "Collapse all" hides only "Configuration" and leaves every other section expanded. A screen-reader user is told "collapse all" and gets a one-section collapse.
  • The collapse-all hides nested TOC children test cannot pass either way: listToTree nests every h2 under the preceding h1, so a real collapse-all leaves only Introduction visible (which is what CI got), while the context-aware branch leaves all five visible. The expectation of four top-level entries matches neither.

The header/overflow restructure that comes with it — fixed title, only the tree scrolling — is a genuine improvement, but it is an independent change too.

Suggestion: drop the toolbar from this PR and keep it to the active-heading highlight (that is what the description promises). The toolbar plus the header/overflow work is a clean second PR, with the i18n keys wired up and a label that matches what the button does.

Minor

  • toc.vue:280 --el-tree-text-color: var(--sideBarColor) is redundant now: #5094 landed .el-tree-node__label { color: inherit } on develop, which already solves "problem 3" from the description.
  • store/editor.ts:1435 clears activeHeadingSlug on every UPDATE_TOC. Slugs are stable per block, so a TOC change does not invalidate them, and the tab-switch case is already covered at line 872. Harmless today (the next selection-change restores it) but the comment's rationale is not accurate.
  • editor.vue:1288 item.slug! — TocItem.slug is optional; a typeof item.slug === 'string' guard drops the assertion and the undefined entry it can produce.

Unrelated to this PR: the PR Build (linux) job failed on an electron-builder tool-cache ENOENT while building the snap; I've re-run it.

Jocs and others added 3 commits September 22, 2026 12:34
The expand/collapse toolbar and the sidebar header/overflow restructure
that came with it are a separate feature — the PR description already
says so. Drop them here so this change is only what its title promises,
and take the toolbar's e2e cases with them.

What stays is the highlight itself: `highlight-current` plus the
slug-to-node-key mapping and the `.is-current` rule.

Removing the toolbar also removes three problems it had: its buttons were
hardcoded English while the `sideBar.toc.expandAll` / `collapseAll` keys
sit translated and unused in all twelve locales; the labels said "all"
but operated on the caret's subtree when there was one; and the
`collapse-all` expectation could not hold either way, since `listToTree`
nests every h2 under the preceding h1.

`--el-tree-text-color` goes too: marktext#5094 landed `.el-tree-node__label
{ color: inherit }` on develop, which already keeps the labels themed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three defects in how the active heading was located, all in what got fed
to `findActiveHeadingSlug` — the pure function itself was right.

1. The positions were measured once per TOC change. Typing body text
   changes no TOC entry, so `listToc` keeps its identity (slugs are
   stable per block) and nothing re-measured, while every heading below
   the caret moved down the page. After 14 lines typed into a section,
   the heading below it had moved from y=136 to y=606 but was still
   recorded at 136, so the highlight jumped a section ahead of the caret.
   Only the slug-to-element pairing — the part that does change with the
   TOC, and the expensive part — is cached now.

2. `offsetTop` is rounded to whole pixels; a caret rect is not. Clicking
   a heading whose real offset was 473.55 compared 474 <= 473.55 and
   highlighted the section above it. Measuring both sides with
   `getBoundingClientRect()` keeps them on the same fractional scale, and
   drops the dependency on which ancestor happens to be the offsetParent.

3. The call sat after the keep-cursor-visible scroll, and
   `animatedScrollTo(..., 0)` assigns `scrollTop` synchronously — so the
   headings had already moved out from under the `y` being measured.
   Measuring first also means no scroll arithmetic at all: the caret rect
   and the heading rects are viewport coordinates from the same event.

`HeadingPosition.offsetTop` is now `top`, since it is no longer an
offsetTop and no longer document-relative.

Adds the e2e case for (1); (2) is what the existing nested-heading case
was already failing on.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ed row

The caret's row is painted `--themeColor` on purpose now, and marktext#5094's
guard sampled the FIRST row — which is the caret's whenever a document
opens on a heading. It read the accent color and failed on material-dark
(expected the sidebar color, got rgb(244, 130, 55)).

Sample a row that is not `.is-current` instead, so the guard keeps
testing what it was written for: that ordinary rows follow the theme
rather than Element Plus' defaults.

The accent on the active row gets its own assertion, next to the feature
it belongs to.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Jocs

Jocs commented Sep 22, 2026

Copy link
Copy Markdown
Member

Pushed the fixes onto this branch — three commits on top of the merge (cdb2cd7, 7507760, eaa3688).

chore: back to just the highlight. The expand/collapse toolbar and the header/overflow restructure are gone, along with their e2e cases, so toc.vue is now develop plus highlight-current, the slug→node-key mapping and one .is-current rule (+29/−4 against develop). The toolbar is worth having, and the "only the tree scrolls, the title stays put" part especially — please do open it as its own PR, with the twelve locales' sideBar.toc.expandAll / collapseAll keys wired up and a label that matches what the button does (or a second pair of "…section" buttons if you want to keep the caret-aware behaviour).

fix: the coordinate handling. Cache only the slug→element pairing — the part that actually changes with the TOC — and measure with getBoundingClientRect() on each selection-change, before the keep-cursor-visible scroll. That one change covers all three defects from the review: the stale offsets, the offsetTop rounding, and the synchronous scrollTop assignment underneath a stale y. HeadingPosition.offsetTop is now top. Your three highlight assertions pass, and there is a new case for the staleness bug (type 14 lines into a section, the highlight must stay).

test: #5094's guard. It sampled the first TOC row, which is the caret's row whenever a document opens on a heading, so it read the new accent color. It samples a :not(.is-current) row now; the accent itself gets a positive assertion in this feature's spec.

One correction to my review: minor point #2 was wrong. UPDATE_TOC is only called from setContent / replaceContent / mount — document swaps, where clearing activeHeadingSlug is exactly right. Editing a heading goes through LISTEN_FOR_CONTENT_CHANGE, which doesn't clear it. Nothing to change there; I left store/editor.ts as you wrote it.

Verified on the pushed tree: vue-tsc clean, eslint clean, 875/875 unit tests, and toc-active-heading + issue-5094-toc-theming + toc-scroll + anchor-link-scroll green locally on macOS (12/12). Watching CI.

…t say

Drops the restatements and keeps the four facts a reader cannot get from
the code: positions are deliberately not cached, `getBoundingClientRect`
is used because `offsetTop` rounds, the measurement has to happen before
the scroll, and `current-node-key` only seeds el-tree at mount.

`findActiveHeadingSlug`'s file header duplicated its own doc comment;
what survives is the contract a caller needs — document order, and a
coordinate space shared with the cursor.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Jocs
Jocs merged commit 410733e into marktext:develop Sep 22, 2026
10 checks passed
Wangqkoe pushed a commit to Wangqkoe/marktext that referenced this pull request Oct 21, 2026
…#4345)

The TOC sidebar now marks the section the caret is in: the store tracks the
active heading by slug on every `selection-change`, and el-tree highlights the
matching node in the theme accent.

Heading positions are measured live with `getBoundingClientRect()` — caching
them went stale as soon as body text moved the headings, and `offsetTop`'s
whole-pixel rounding reported the heading the caret sits in as the one above it.
The measurement runs before the keep-cursor-visible scroll, which assigns
`scrollTop` synchronously.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
(cherry picked from commit 410733e)
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.

4 participants