A better Substack table of contents
Most documentation sites reserve a permanent 250-pixel column on the side of the screen for a table of contents. That works for a reference manual, but in a writing app it is visual noise. While you are trying to think, a list of your own headings stares back at you.
Substack solved this nicely. When you read a long post on Substack, the table of contents collapses into a tiny stack of horizontal lines floating in the right margin. Hover over those lines and a subtle pill frames them with a Table of contents tooltip on the left. Click the pill and it opens a compact CONTENT card. And if two short sections happen to fit on your screen at the same time, both of them light up in the list at once.
When I built TableOfContents.tsx for eLNotes, I started from Substack’s design and pushed it a bit further for a live note editor:
- The collapsed bars vary in width and opacity to show heading hierarchy (
H1throughH4) before you even open the menu. - Long notes slide through a 5-bar window with overflow dots so a 30-heading document never turns the right margin into a barcode.
- Clicking a heading in the menu temporarily highlights that heading inside the editor itself, so your eyes do not have to hunt for it when multiple headings are on screen.
If you are newer to React or browser APIs like IntersectionObserver, a component like this is a great project to learn from because the naive version looks like it works for five minutes and then breaks in four subtle ways. Let’s build it step by step.
Step 1: Turn headings into plain data and debounce keystrokes
Before we can render a table of contents, we need a list of headings in the document: their unique id, their nesting level (1 for <h1> down to 4 for <h4>), their text, and their position in the editor.
export type TableOfContentsItem = {
id: string;
level: number;
textContent: string;
pos: number;
};
On a static blog page, you could collect these once on mount with document.querySelectorAll("h1, h2, h3, h4"). In eLNotes, the document is a live Tiptap (ProseMirror) editor where headings are created, edited, and deleted as you type. We use @tiptap/extension-table-of-contents, which stamps a data-toc-id attribute onto each heading element in the DOM and runs an onUpdate callback whenever the document changes.
There are two traps here that trip up almost everyone building an editor outline for the first time.
First, raw items from an editor plugin often contain references to live DOM nodes and the editor instance itself. If you store those raw objects directly in React state, React can hold onto detached DOM trees after the editor re-renders, leaking memory. In Tiptap.tsx, we strip every item down to plain strings and numbers before calling setTocItems:
const handleTocUpdate = useCallback((data: TableOfContentData) => {
const nextItems = data.map(({ id, level, textContent, pos }) => ({
id,
level,
textContent,
pos,
}));
// Debounce TOC updates to avoid state updates on every keystroke
if (tocUpdateTimerRef.current) {
clearTimeout(tocUpdateTimerRef.current);
}
tocUpdateTimerRef.current = setTimeout(() => {
setTocItems(nextItems);
}, 300);
}, []);
Second, notice the 300ms timer stored in tocUpdateTimerRef. Without it, typing a 25-character heading fires 25 state updates and re-renders the entire TableOfContents tree on every keystroke. Storing the timer ID in a useRef (instead of useState) lets us cancel and restart the countdown on each key press without triggering extra renders.
When TableOfContents.tsx later needs to measure a heading in the DOM, it looks up the element by data-toc-id. During rapid editor updates, ProseMirror can briefly leave an empty placeholder node in the DOM sharing the same ID as the real heading, so getHeadingElement prefers the node that actually contains text:
const getHeadingElement = useCallback((id: string) => {
const elements = document.querySelectorAll(`[data-toc-id="${id}"]`);
// If multiple elements share an ID, prefer the real rendered heading over an empty ghost node.
if (elements.length > 1) {
return Array.from(elements).find((el) => el.textContent?.trim()) ?? null;
}
return elements[0] ?? null;
}, []);
There's an interactive demo here: Extract plain data & debounce.
Step 2: Encode hierarchy in the collapsed rail (and cap it at 5 bars)
In Substack’s collapsed view, every horizontal tick mark has the exact same width. That keeps the graphic simple, but it throws away useful structure. If your note has top-level H1 sections with H2 and H3 subsections underneath, the collapsed rail can show that shape right away.
In TableOfContents.tsx, three tiny helper functions map a heading’s level (1 to 4) to Tailwind classes for bar width, bar opacity, and expanded text indentation:
const getIndentation = (level: number) => {
switch (level) {
case 1:
return "ml-0";
case 2:
return "ml-3";
case 3:
return "ml-6";
case 4:
return "ml-9";
default:
return "ml-0";
}
};
const getLineWidth = (level: number) => {
switch (level) {
case 1:
return "w-4";
case 2:
return "w-3";
case 3:
return "w-2";
case 4:
return "w-1.5";
default:
return "w-4";
}
};
const getLineOpacity = (level: number) => {
switch (level) {
case 1:
return "opacity-60";
case 2:
return "opacity-50";
case 3:
return "opacity-40";
case 4:
return "opacity-35";
default:
return "opacity-60";
}
};
Because the rail button uses flex flex-col items-end, all the bars align against the right edge. An H1 (w-4, 16px) sticks out furthest to the left, while an H3 (w-2, 8px) tucks in underneath it. Active bars also step up from 1px tall (h-px) to 2px tall (h-0.5) with a darker fill.
That works great for four or five headings. But what happens when a note has 25 headings? Rendering 25 stacked lines turns the rail into a tall Ladder that clutters the margin.
To keep the collapsed button compact, eLNotes caps the rail at maxVisible = 5 bars and slides that 5-item window along with your scroll position so the active headings stay in view:
const maxVisible = 5;
const activeIndexes = items
.map((item, index) => (activeHeadingIds.includes(item.id) ? index : -1))
.filter((index) => index !== -1);
let startIndex = 0;
if (items.length > maxVisible && activeIndexes.length > 0) {
const firstActiveIndex = activeIndexes[0];
const lastActiveIndex = activeIndexes[activeIndexes.length - 1];
startIndex = Math.min(firstActiveIndex, items.length - maxVisible);
if (lastActiveIndex >= startIndex + maxVisible) {
startIndex = Math.min(
lastActiveIndex - maxVisible + 1,
items.length - maxVisible,
);
}
}
const visibleItems = items.slice(startIndex, startIndex + maxVisible);
const hasItemsBefore = startIndex > 0;
const hasItemsAfter = startIndex + maxVisible < items.length;
Whenever hasItemsBefore or hasItemsAfter is true, we render a faint w-1.5 dot above or below the 5 bars as a quiet hint that the document continues in that direction.
There's an interactive demo here: Hierarchy bars & 5-item window.
Step 3: Highlight every visible section at once
Look closely at how Substack highlights items when you open the CONTENT card: if two short sections are on screen at the same time, both rows get a light blue highlight.
In React, that starts with a simple state choice. Instead of storing a single activeHeadingId: string | null, we store an array:
const [activeHeadingIds, setActiveHeadingIds] = useState<string[]>([]);
Now for the hard part: how do we know which sections are currently on screen?
If you search for “React table of contents IntersectionObserver”, most examples tell you to observe every <h2> tag and mark a heading active when entry.isIntersecting is true. Try that on a real document and you will hit a wall right away:
- In HTML produced by Markdown or a rich-text editor, headings do not wrap their paragraphs like
<section><h2>Title</h2><p>...</p></section>. Instead, headings and paragraphs are flat siblings:<h2>Title</h2>followed by<p>...</p>,<p>...</p>, and then the next<h2>. - As soon as you scroll two paragraphs down into a long section, the
<h2>tag itself scrolls off the top of the screen. If you only check whether the heading tag is intersecting the viewport, your table of contents un-highlights everything while you are right in the middle of reading that section.
The fix is to think in section intervals instead of heading tags. Even in a flat DOM, every section has a clear start and end:
- A section starts at its own heading’s top edge:
sectionTop = element.getBoundingClientRect().top. - A section ends where the next heading begins:
nextSectionTop = headingSections[index + 1]?.element.getBoundingClientRect().top ?? Number.POSITIVE_INFINITY.
Meanwhile, the readable area of the screen runs from viewportTop (SCROLL_OFFSET, which is 40px below the top edge) down to viewportBottom (window.innerHeight).
Two vertical ranges [sectionTop, nextSectionTop) and [viewportTop, viewportBottom) overlap if and only if the section ends below the top of the viewport and starts above the bottom of the viewport:
const getVisibleHeadingIds = useCallback(() => {
const viewportTop = SCROLL_OFFSET;
const viewportBottom =
window.innerHeight || document.documentElement.clientHeight;
const headingSections = items
.map((item) => ({
id: item.id,
element: getHeadingElement(item.id),
}))
.filter(
(section): section is { id: string; element: Element } =>
section.element !== null,
);
const visibleIds = new Set<string>();
for (let index = 0; index < headingSections.length; index += 1) {
const { id, element } = headingSections[index];
const sectionTop = element.getBoundingClientRect().top;
const nextSectionTop =
headingSections[index + 1]?.element.getBoundingClientRect().top ??
Number.POSITIVE_INFINITY;
if (nextSectionTop > viewportTop && sectionTop < viewportBottom) {
visibleIds.add(id);
}
}
return items
.map((item) => item.id)
.filter((id) => visibleIds.has(id));
}, [getHeadingElement, items]);
Look at what that single if (nextSectionTop > viewportTop && sectionTop < viewportBottom) check gives us:
- Long sections stay highlighted. When a heading scrolls above the top of the screen,
sectionTopbecomes negative (which is still< viewportBottom). As long as the next heading has not yet crossedviewportTop,nextSectionTop > viewportTopremains true and the section stays highlighted. - Short sections highlight together. When two or three short sections sit in the viewport at the same time, all of them satisfy the condition, so
activeHeadingIdscontains all of their IDs at once.
Why do we still use IntersectionObserver if getVisibleHeadingIds uses getBoundingClientRect()? Because running getBoundingClientRect() inside a window scroll listener executes on every single frame of scrolling. By attaching an IntersectionObserver to the heading elements with rootMargin: "-40px 0px 0px 0px", the browser only wakes our code up at the exact moments when a heading crosses the top or bottom boundary of the viewport:
useEffect(() => {
if (!isVisible || items.length === 0) return;
if (observerRef.current) {
observerRef.current.disconnect();
}
const headingElements = getHeadingElements();
if (headingElements.length === 0) return;
setActiveHeadingIds(getVisibleHeadingIds());
observerRef.current = new IntersectionObserver(
() => {
if (manualSelectionLockRef.current) return;
setActiveHeadingIds(getVisibleHeadingIds());
},
{
rootMargin: `-${SCROLL_OFFSET}px 0px 0px 0px`,
threshold: 0,
},
);
for (const element of headingElements) {
observerRef.current.observe(element);
}
return () => {
if (observerRef.current) {
observerRef.current.disconnect();
}
};
}, [getHeadingElements, getVisibleHeadingIds, isVisible, items]);
There's an interactive demo here: Multi-target section highlight.
Step 4: Smooth scroll without the observer flicker
When a user opens the table of contents and clicks a heading, we want to smoothly scroll that heading to 40px from the top of the editor and highlight the clicked item.
In a real web app, calling window.scrollTo often does nothing at all because the page itself is 100vh tall and the editor lives inside a scrollable <div> with overflow-y: auto. Instead of hardcoding a selector, getScrollParent walks up the DOM tree from the heading element until it finds the ancestor that actually scrolls:
const getScrollParent = (el: HTMLElement): HTMLElement => {
let parent = el.parentElement;
while (parent) {
const style = getComputedStyle(parent);
if (style.overflowY === "auto" || style.overflowY === "scroll") {
return parent;
}
parent = parent.parentElement;
}
return document.documentElement;
};
Once we have scrollContainer, we convert the heading’s viewport-relative getBoundingClientRect().top into a scroll offset inside that container and call scrollTo({ behavior: "smooth" }):
const scrollContainer = getScrollParent(element);
const containerRect = scrollContainer.getBoundingClientRect();
const elementRect = element.getBoundingClientRect();
const scrollTop =
scrollContainer.scrollTop +
elementRect.top -
containerRect.top -
SCROLL_OFFSET;
scrollContainer.scrollTo({
top: scrollTop,
behavior: "smooth",
});
Here is the next beginner trap. Suppose you are at Heading 1 and click Heading 6. You immediately call setActiveHeadingIds([id]) so Heading 6 turns blue, and you start the smooth scroll. Over the next 400 milliseconds, the viewport glides past Headings 2, 3, 4, and 5.
As each intermediate heading crosses the screen, IntersectionObserver fires! Without protection, the observer overwrites your selection with Heading 2, then 3, then 4, causing the highlight to flicker down the list while the scroll is in flight.
To stop the observer from fighting the smooth scroll, we flip manualSelectionLockRef.current = true for 600ms (just longer than a smooth scroll animation) and re-sync when the timer finishes:
setActiveHeadingIds([id]);
manualSelectionLockRef.current = true;
if (manualSelectionTimeoutRef.current) {
clearTimeout(manualSelectionTimeoutRef.current);
}
manualSelectionTimeoutRef.current = setTimeout(() => {
manualSelectionLockRef.current = false;
manualSelectionTimeoutRef.current = null;
setActiveHeadingIds(getVisibleHeadingIds());
}, 600);
Just like the debounce timer in Step 1, manualSelectionLockRef is a useRef rather than useState because flipping the lock does not change anything on screen by itself; it is just a gate that the IntersectionObserver callback checks before updating state.
There's an interactive demo here: Prevent smooth-scroll flicker.
Step 5: Highlight the target heading inside the editor
Multi-section highlighting creates one last UX puzzle. Imagine the bottom of your note has three short sections visible at the same time. You open the table of contents and click the second one. Because the section is already near the bottom of the scroll container, the page barely moves, and three headings are still on screen. Which one did you just jump to?
In eLNotes, clicking a table of contents item also highlights the heading inside the editor itself with a soft light-blue background (.toc-heading-focus) using a small ProseMirror decoration plugin (setTocFocusHeading(pos)):
setActiveHeadingIds([id]);
editor.chain().setTocFocusHeading(pos).run();
tocClickInProgressRef.current = true;
That in-editor highlight stays visible until you click anywhere in the note to continue typing, which triggers Tiptap’s selectionUpdate event and clears the decoration.
Notice tocClickInProgressRef.current = true. Why is that needed? Because at the end of handleHeadingClick, we also move the editor cursor to the heading you clicked:
editor.chain().setTextSelection(pos).run();
setIsExpanded(false);
Calling setTextSelection(pos) fires selectionUpdate synchronously! Without tocClickInProgressRef, our own selectionUpdate listener would immediately erase the focus highlight we just turned on:
useEffect(() => {
const handleSelectionUpdate = () => {
if (tocClickInProgressRef.current) {
tocClickInProgressRef.current = false;
return;
}
editor.chain().setTocFocusHeading(null).run();
};
editor.on("selectionUpdate", handleSelectionUpdate);
return () => {
editor.off("selectionUpdate", handleSelectionUpdate);
};
}, [editor]);
Finally, three small useEffect hooks handle the everyday popover ergonomics:
- Auto-centering the active item: When
isExpandedflips totrue, we wait50msfor the menu DOM to mount, find[data-toc-item-id="${activeHeadingId}"], and callscrollIntoView({ behavior: "smooth", block: "center" })so long menus open right to your current spot. - Click outside to close: A
mousedownlistener ondocumentchecks!containerRef.current.contains(event.target as Node)and collapses the card. - Escape to close: A
keydownlistener collapses the card whenevent.key === "Escape".
There's an interactive demo here: Complete floating Table of Contents.
Wrapping up
What makes Substack’s table of contents feel so good is restraint. It stays out of your way as a tiny stack of lines until you ask for it, and when you open it, it tells the truth about every section currently on your screen.
Building a production version in React comes down to a handful of small details:
- Store plain data in state and debounce editor updates so typing stays fast.
- Map heading levels (
H1toH4) to bar widths and slide a 5-bar window so the collapsed rail scales to any document length. - Compute section intervals (
[sectionTop, nextSectionTop)) instead of checking whether individual heading tags are on screen, usingIntersectionObserveronly as the trigger to recalculate. - Use
useRefflags to coordinate async browser behavior, locking out the observer during smooth scrolling and ignoring the initial programmatic cursor jump.