Dizhan Xue 6a038a67df
fix(docs): light the contents rail between headings and use raven.evermind.ai's favicon (#734)
## Summary

Two fixes to the documentation site.

**The contents rail went dark between headings.** The right-hand table
of contents lit an entry only while its heading was inside the viewport.
Partway through a section longer than the screen every heading sits
above or below it, so nothing was lit, the gold stretch collapsed to
zero height, and the column stopped following the reader. On the built
site before this change, 18 of 28 English pages had such stretches: 114
of 1264 scroll positions sampled every 120px. `sync()` in
`docs-site/docs/javascripts/toc-progress.js` now falls back to the
nearest heading above when none is in view and lights that entry alone.
The lit stretch and the column follow read the same list, so both pick
it up with no further change. Above the first heading nothing is lit,
since no section has begun there. The design spec states the rule, and
the rail's section comment in `evermind.css`, which still credited
Material with marking the section, now names what does.

**The tab icon differed from raven.evermind.ai.** The site drew its own
simplified EverMind mark, a single heavy lemniscate without the rings.
raven.evermind.ai links one 192px PNG of the full mark for its light,
dark and apple-touch icons alike. `theme.favicon` in
`docs-site/mkdocs.yml` now inlines that PNG byte for byte as a data URI,
since AGENTS.md section 7 keeps image files out of `docs-site/`. For
whoever refreshes it: that site's CDN answers any `Accept` naming
`image/avif` with a lossy AVIF re-encode (5178 bytes), and only a plain
`Accept: */*` returns the original PNG (5184 bytes). The comment above
the value says so.

Checked and deliberately left alone:

- The mark at the top of the navigation rail (`--em-mark` in
`evermind.css`) is a separate drawing and still the simplified one. This
change is the tab icon only.
- raven.evermind.ai also sets an apple-touch icon. Material emits no
such link, and adding one needs a template override, which is an `.html`
file that section 7 blocks.
- The favicon's identity is verified by the measurements below rather
than pinned by a test: a pinned hash would only detect change, and
comparing against the live site would put the network in the suite.
- `tests/integration/` is outside every CI job (`norecursedirs`), so the
e2e results below are local runs.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

- `uv run --frozen --extra browser --group docs pytest
tests/integration/test_docs_site_controls_e2e.py
tests/integration/test_docs_site_search_e2e.py -n 0 -q`: 63 passed.
- `uv run --frozen --extra browser --group docs pytest
tests/test_docs_site.py -q`: 16 passed.
- The new
`test_table_of_contents_keeps_the_section_above_lit_between_headings`
computes, from the Sandbox page's own layout, every stretch between two
headings (or after the last) with none on screen, and checks the middle
of each. Against the unfixed script it fails (`at 1354px: assert [] ==
[2]`), and with the fix it passes.
- A sweep of every built page in headless Chrome at 1440x900, one sample
every 120px, checking the rule at each position: 0 violations over 1264
English, 1145 Chinese and 21 Overview positions after the change, and
wherever an entry is lit, the first one sits inside the contents column.
The unfixed script gives 114 violations over the same English positions.
- Favicon: each of the 63 built HTML files carries exactly one icon
link, and its decoded bytes match the PNG raven.evermind.ai links
(sha256 `4a5051e1781fac64...`). Drawn in Chrome at 16, 32 and 192px, the
docs icon and that PNG differ in 0 pixels.
- `mkdocs build --strict`, `scripts/check_source_language.py
origin/main...HEAD`, `scripts/check_large_files.py origin/main...HEAD`,
`scripts/check_commit_messages.py origin/main..HEAD`, commitlint,
`pre-commit run --from-ref origin/main --to-ref HEAD`, ruff and `git
diff --check`: all pass.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

The last box is left blank because nothing needed it: no documentation
page describes the rail or the icon, and the design spec is updated in
this change.

## Risk

- Between headings, the entry of the section above now stays lit and the
contents column keeps it in view. While any heading is on screen the
behaviour is unchanged.
- The tab icon changes to the full mark. Each page's head now carries
about 6.9 KB of base64 for it, against about 0.6 KB for the previous
SVG.
- The new code relies on no browser API newer than
`Array.prototype.includes` (2016).
- The two halves touch disjoint files, so either can be reverted on its
own.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

The inlined PNG was read chunk by chunk: standard chunks plus three
ImageMagick timestamps, and nothing after IEND. Inlining it adds no
third-party request, which hotlinking the CDN copy would have.

## Related Issues

N/A

---------

Co-authored-by: Claude (claude-opus-5-5[1m]) <noreply@anthropic.com>
2026-09-23 22:09:48 +08:00

207 lines
7.7 KiB
JavaScript

/*
* The table-of-contents rail: one continuous polyline through every entry, and
* the stretch of it the reader is currently inside.
*
* The line is a single path walked in document order, not one line per nesting
* level: each entry contributes a vertical run at its own depth, and the 12px
* between two entries is where the line changes column, which draws as a
* diagonal when their depths differ and as plain vertical when they do not.
* Colouring a contiguous stretch of that one path is what makes a parent and
* the children under it read as a single bracket.
*
* The path only moves when the column is laid out again, so it is rebuilt on
* resize and load; scrolling moves the clip rectangle alone.
*/
(() => {
const SVG_NS = "http://www.w3.org/2000/svg";
const CLIP_ID = "raven-toc-progress-clip";
/* Each level sits 10px right of the one above; the first is inset by 1 so a
1px stroke lands whole inside the 12px viewBox. */
const columnFor = (depth) => 1 + depth * 10;
/* Half of the run an entry boundary turns through. Entries butt against each
other, so reserving this at both ends of every run leaves exactly one 12px
gap per boundary for the line to cross columns in. */
const JOIN = 6;
const listSelector = ".md-sidebar--secondary .md-nav--secondary > .md-nav__list";
const entriesOf = (list) => {
const found = [];
const walk = (ul, depth) => {
for (const item of ul.querySelectorAll(":scope > .md-nav__item")) {
const link = item.querySelector(":scope > .md-nav__link");
if (link) found.push({ link, depth });
const nested = item.querySelector(":scope > .md-nav > .md-nav__list");
if (nested) walk(nested, depth + 1);
}
};
walk(list, 0);
return found;
};
const railFor = (list) => {
let rail = list.querySelector(":scope > .raven-toc-progress");
if (rail) return rail;
rail = document.createElementNS(SVG_NS, "svg");
rail.classList.add("raven-toc-progress");
rail.setAttribute("aria-hidden", "true");
const clip = document.createElementNS(SVG_NS, "clipPath");
clip.id = CLIP_ID;
clip.append(document.createElementNS(SVG_NS, "rect"));
const base = document.createElementNS(SVG_NS, "path");
base.classList.add("raven-toc-progress__base");
const lead = document.createElementNS(SVG_NS, "path");
lead.classList.add("raven-toc-progress__active");
lead.setAttribute("clip-path", `url(#${CLIP_ID})`);
rail.append(clip, base, lead);
list.prepend(rail);
return rail;
};
/* Where an entry's own vertical run starts and ends. The outermost ends are
flush: nothing joins onto the first entry from above or the last from
below, so neither reserves a gap there. */
const runOf = (spans, index) => {
const span = spans[index];
return {
start: index === 0 ? span.top : span.top + JOIN,
end: index === spans.length - 1 ? span.bottom : span.bottom - JOIN,
};
};
const state = { list: null, entries: [], spans: [], height: 0 };
const layout = () => {
const list = document.querySelector(listSelector);
if (!list) return false;
const entries = entriesOf(list);
if (!entries.length) return false;
const origin = list.getBoundingClientRect().top;
const spans = entries.map(({ link, depth }) => {
const box = link.getBoundingClientRect();
return { top: box.top - origin, bottom: box.bottom - origin, depth };
});
const commands = [];
spans.forEach((span, index) => {
const run = runOf(spans, index);
const column = columnFor(span.depth);
if (index === 0) commands.push(`M${column} ${run.start}`);
commands.push(`L${column} ${run.end}`);
const next = spans[index + 1];
if (next) {
commands.push(`L${columnFor(next.depth)} ${runOf(spans, index + 1).start}`);
}
});
const height = spans[spans.length - 1].bottom;
const rail = railFor(list);
rail.setAttribute("viewBox", `0 0 12 ${height}`);
rail.setAttribute("width", "12");
rail.setAttribute("height", String(height));
const d = commands.join(" ");
rail.querySelector(".raven-toc-progress__base").setAttribute("d", d);
rail.querySelector(".raven-toc-progress__active").setAttribute("d", d);
Object.assign(state, { list, entries, spans, height });
return true;
};
/* An entry is current while its heading is anywhere in the viewport, which
is why several can be current at once and why the lit stretch grows and
shrinks rather than jumping between entries. Partway through a section
longer than the screen no heading is in view, yet the reader is still
inside the section the nearest heading above opened, so that entry is
current on its own until the next heading comes on screen. */
const sync = () => {
if (!state.list && !layout()) return;
const boxes = state.entries.map(({ link }) => {
const id = (link.getAttribute("href") || "").slice(1);
const heading = id ? document.getElementById(id) : null;
return heading && heading.getBoundingClientRect();
});
const active = [];
boxes.forEach((box, index) => {
if (box && box.bottom > 0 && box.top < window.innerHeight) active.push(index);
});
if (!active.length) {
const above = boxes.reduce(
(last, box, index) => (box && box.top < 0 ? index : last),
-1,
);
if (above !== -1) active.push(above);
}
state.entries.forEach(({ link }, index) => {
link.classList.toggle("md-nav__link--raven-active", active.includes(index));
});
const rect = state.list.querySelector(`.raven-toc-progress clipPath rect`);
if (!rect) return;
const top = active.length ? runOf(state.spans, active[0]).start : 0;
const bottom = active.length ? runOf(state.spans, active[active.length - 1]).end : 0;
const height = Math.max(0, bottom - top);
rect.setAttribute("x", "0");
rect.setAttribute("width", "12");
rect.setAttribute("y", String(top));
rect.setAttribute("height", String(height));
/* The transition runs on the styled value, so both are kept in step. */
rect.style.y = `${top}px`;
rect.style.height = `${height}px`;
follow(active);
};
/*
* The column scrolls on its own, so on a long outline the lit entry walks
* off its bottom edge and the reader loses their place. The reference layout
* centres the first lit entry and clamps at both ends -- the first, not the
* lit stretch, so the anchor does not drift as the stretch grows and shrinks.
*/
const follow = (active) => {
if (!active.length) return;
const scroller = state.list.closest(".md-sidebar__scrollwrap");
if (!scroller) return;
const link = state.entries[active[0]].link;
const box = link.getBoundingClientRect();
const frame = scroller.getBoundingClientRect();
const centre = scroller.scrollTop + (box.top - frame.top) + box.height / 2;
const limit = scroller.scrollHeight - scroller.clientHeight;
const target = Math.max(0, Math.min(limit, centre - scroller.clientHeight / 2));
/* A hair of tolerance: writing scrollTop every frame fights a reader who
is dragging the column, and a sub-pixel correction is never visible. */
if (Math.abs(target - scroller.scrollTop) > 1) scroller.scrollTop = target;
};
const relayout = () => {
layout();
sync();
};
const start = () => {
relayout();
window.addEventListener("scroll", sync, { passive: true });
window.addEventListener("resize", relayout);
if (document.fonts && document.fonts.ready) document.fonts.ready.then(relayout);
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", start, { once: true });
} else {
start();
}
})();