Repository navigation
feat(toc): highlight active heading based on cursor position - #4345
Conversation
Jocs
left a comment
There was a problem hiding this comment.
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:
- TOC expand-all / collapse-all toolbar buttons +
expandedKeyspersistence (toc.vue). - File-tree expand-all / collapse-all + folder-collapse persistence (
tree.vue,treeFolder.vue, newcollapsedFolders.ts). - Auto-scroll the active file into view in the file tree (
treeFile.vue). - 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.
There was a problem hiding this comment.
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
activeHeadingSlugin the editor store and update it on MuyaselectionChangeto drive TOC highlighting. - Update TOC sidebar to use
el-treecurrent-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.
|
@rkristelijn Pls solve the inline reviews and CI lint error. |
e9ab7a3 to
4ff2173
Compare
|
@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. 🙏 |
Review: active-heading highlight does not work on
|
|
👋 Following up on the review: I rebased this onto current 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
4ff2173 to
025d99a
Compare
Review feedback addressed in latest force-pushRebased onto current @Jocs initial review (Jun 2)
@Jocs second review (Jun 18) — blocker fixes
Additional improvements
Verification
|
- 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
025d99a to
99def67
Compare
|
@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 🙏 |
|
@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
left a comment
There was a problem hiding this comment.
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) whilesideBar.toc.expandAll/collapseAllalready 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 childrentest cannot pass either way:listToTreenests everyh2under the precedingh1, so a real collapse-all leaves onlyIntroductionvisible (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:1435clearsactiveHeadingSlugon everyUPDATE_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 nextselection-changerestores it) but the comment's rationale is not accurate.editor.vue:1288item.slug!—TocItem.slugis optional; atypeof item.slug === 'string'guard drops the assertion and theundefinedentry 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.
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]>
|
Pushed the fixes onto this branch — three commits on top of the merge (
One correction to my review: minor point #2 was wrong. Verified on the pushed tree: |
…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]>
…#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)
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-changeevent, the editor finds the last heading whoseoffsetTopis at or above the cursor and stores its slug asactiveHeadingSlugin the editor store. The TOC component uses el-tree'shighlight-current+node-keyto show the active node.Three non-obvious problems solved
Circular references in toc data —
listToTreeattaches aparentback-pointer to every TreeNode. Passing this directly to el-tree silently brokenode-keymatching. Fixed with atocDatacomputed that stripsparent.CSS specificity — Element Plus's highlight rule requires
.el-tree--highlight-currentin the selector to win the specificity battle.Inherited text color —
.el-treesets color via--el-tree-text-colorwhich must be overridden on the same element, not just viacolor.Review feedback addressed
findActiveHeadingSlugextracted as pure function with 6 unit testsdocument.getElementByIdinstead ofquerySelector(\#${slug}`)` (no CSS injection)activeHeadingSlugcleared on tab switch (prevents stale highlight)TreeInstancetype import (notInstanceType<typeof ElTree>)typeof === 'string'guard, notas stringcast)Type of change
Test plan
findActiveHeadingSlug— 6 tests covering empty, above-all, between, exact, below-all, single headingFiles changed
util/findActiveHeading.tstest/unit/specs/find-active-heading.spec.tsstore/editor.tsactiveHeadingSlugstate +SET_ACTIVE_HEADING+ clear on tab switchcomponents/editorWithTabs/editor.vuecomponents/sideBar/toc.vuenode-key,highlight-current,tocDatacomputed, theme-color CSSNot included — follow-up PRs