Reading progress contents
An anchor-based reading guide marks the current section, read headings and estimated minutes remaining.
pnpm dlx shadcn@latest add @haze/toc-progress---
import { cn } from "../../../lib/haze/utils";
interface Heading { id: string; label: string; level?: 1 | 2 }
interface Props {
id: string;
items?: Heading[];
title?: string;
scrollContainer?: string;
offset?: number;
minutes?: number;
class?: string;
}
const { id, items = [], title = "Reading guide", scrollContainer, offset = 64, minutes = 4, class: className } = Astro.props;
---
<nav id={id} data-haze-toc-progress data-scroll-container={scrollContainer} data-offset={offset} data-minutes={minutes} aria-labelledby={`${id}-title`} class={cn("grid min-w-0 gap-3", className)}>
<div class="flex flex-wrap items-baseline justify-between gap-2"><p id={`${id}-title`} class="text-[0.8125rem]/5 font-medium">{title}</p><span data-toc-remaining class="text-xs tabular-nums text-muted-foreground">{minutes} min left</span></div>
<progress data-toc-meter max="100" value="0" aria-label="Article reading progress" class="h-1 w-full overflow-hidden rounded-full bg-input accent-primary [&::-moz-progress-bar]:bg-primary [&::-webkit-progress-bar]:bg-input [&::-webkit-progress-value]:rounded-full [&::-webkit-progress-value]:bg-primary"></progress>
<div class="relative"><span data-toc-indicator aria-hidden="true" class="pointer-events-none absolute top-0 left-0 h-(--toc-h) w-0.5 translate-y-(--toc-y) rounded-full bg-foreground opacity-0 data-[on]:opacity-100 [[data-ready]_&]:transition-[translate,height,opacity] [[data-ready]_&]:duration-300 [[data-ready]_&]:ease-snappy motion-reduce:[[data-ready]_&]:transition-none forced-colors:forced-color-adjust-none forced-colors:bg-[Highlight]"></span><ol class="grid gap-0.5 border-s border-border ps-1.5">{items.map(item => <li class={cn("min-w-0", item.level === 2 && "ms-3")}><a href={`#${encodeURIComponent(item.id)}`} data-toc-link class="flex min-h-8 items-center gap-2 rounded-md px-2 py-1.5 text-[0.8125rem]/5 text-muted-foreground transition-colors duration-150 ease-snappy motion-reduce:transition-none hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring data-[read]:text-foreground aria-[current=location]:bg-accent aria-[current=location]:font-medium aria-[current=location]:text-foreground"><span aria-hidden="true" class="size-1.5 shrink-0 rounded-full border border-current [[data-read]_&]:bg-current [[aria-current=location]_&]:bg-current"></span><span class="wrap-anywhere">{item.label}</span><span data-toc-read-label class="sr-only"></span></a></li>)}</ol></div>
</nav>
<script>
function updateTocProgress() {
document.querySelectorAll<HTMLElement>("[data-haze-toc-progress][data-enhanced]").forEach(root => {
const links = Array.from(root.querySelectorAll<HTMLAnchorElement>("[data-toc-link]"));
const headings = links.map(link => document.getElementById(decodeURIComponent(link.hash.slice(1))));
const container = root.dataset.scrollContainer ? document.getElementById(root.dataset.scrollContainer) : null;
const top = (container?.getBoundingClientRect().top ?? 0) + (Number(root.dataset.offset) || 0);
const scrollTop = container?.scrollTop ?? window.scrollY;
const scrollHeight = container?.scrollHeight ?? document.documentElement.scrollHeight;
const viewport = container?.clientHeight ?? window.innerHeight;
const bottom = scrollTop > 0 && scrollTop + viewport >= scrollHeight - 2;
let index = headings.reduce((last, heading, i) => heading && heading.getBoundingClientRect().top <= top + 1 ? i : last, -1);
if (bottom && headings.length) index = headings.length - 1;
links.forEach((link, i) => {
if (i === index) link.setAttribute("aria-current", "location"); else link.removeAttribute("aria-current");
link.toggleAttribute("data-read", i < index);
const readLabel = link.querySelector<HTMLElement>("[data-toc-read-label]");
if (readLabel) readLabel.textContent = i < index ? " (read)" : "";
});
const bar = root.querySelector<HTMLElement>("[data-toc-indicator]");
const active = links[index];
if (bar) {
if (active) {
bar.style.setProperty("--toc-y", `${active.offsetTop}px`);
bar.style.setProperty("--toc-h", `${active.offsetHeight}px`);
bar.setAttribute("data-on", "");
} else bar.removeAttribute("data-on");
}
const current = headings[index];
const next = headings[index + 1];
const fraction = current && next ? Math.max(0, Math.min(1, (top - current.getBoundingClientRect().top) / Math.max(1, next.getBoundingClientRect().top - current.getBoundingClientRect().top))) : 0;
const progress = bottom ? 1 : Math.max(0, Math.min(1, (index + fraction) / Math.max(1, headings.length)));
const meter = root.querySelector<HTMLProgressElement>("[data-toc-meter]");
if (meter) meter.value = progress * 100;
const remaining = root.querySelector<HTMLElement>("[data-toc-remaining]");
if (remaining) remaining.textContent = progress >= 1 ? "Finished" : `${Math.max(1, Math.ceil((Number(root.dataset.minutes) || 1) * (1 - progress)))} min left`;
});
}
function initTocProgress() {
document.querySelectorAll<HTMLElement>("[data-haze-toc-progress]").forEach(root => {
if (root.hasAttribute("data-enhanced")) return;
root.querySelectorAll<HTMLAnchorElement>("[data-toc-link]").forEach(link => link.addEventListener("click", event => {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
const heading = document.getElementById(decodeURIComponent(link.hash.slice(1)));
if (!heading) return;
event.preventDefault();
if (!heading.hasAttribute("tabindex")) heading.tabIndex = -1;
heading.scrollIntoView({ block: "start", behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
heading.focus({ preventScroll: true });
history.replaceState(history.state, "", link.hash);
updateTocProgress();
}));
root.setAttribute("data-enhanced", "");
});
updateTocProgress();
// The bar slides only after its first placement, so it does not sweep in from the top on load.
requestAnimationFrame(() => requestAnimationFrame(() => document.querySelectorAll<HTMLElement>("[data-haze-toc-progress]").forEach(root => root.setAttribute("data-ready", ""))));
}
initTocProgress();
if (!document.documentElement.hasAttribute("data-haze-toc-progress-listener")) {
document.documentElement.setAttribute("data-haze-toc-progress-listener", "");
let frame = 0;
document.addEventListener("scroll", () => { if (!frame) frame = requestAnimationFrame(() => { frame = 0; updateTocProgress(); }); }, true);
window.addEventListener("resize", updateTocProgress);
window.addEventListener("hashchange", updateTocProgress);
document.addEventListener("astro:page-load", initTocProgress);
}
</script>When to use
- A long article needs a reading guide that follows the reader's position
- An embedded reading panel needs section links and local progress
When not to use
- Use table-of-contents when static anchor links are sufficient
- Use scroll-progress for a reading bar without a heading list
Installation
Add the Haze registry to components.json once, then install Reading progress contents with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/toc-progressnpx shadcn@latest add @haze/toc-progressyarn dlx shadcn@latest add @haze/toc-progressbunx --bun shadcn@latest add @haze/toc-progressFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique caller-supplied prefix for this component and its related elements. |
| items | { id: string; label: string; level?: 1 | 2 }[] | [] | Heading IDs and labels; level 2 adds indentation. |
| title | string | "Reading guide" | Navigation title. |
| scrollContainer | string | – | Optional ID of a locally scrollable article; otherwise tracks the document. |
| offset | number | 64 | Pixels from the top used to determine the current heading. |
| minutes | number | 4 | Initial reading estimate; decreases with section progress. |
| class | string | – | Additional classes for the component root. |
Keyboard interactions
- Tab, Enter
- Reach a section link and move focus to its article heading.
Accessibility
- The ordered list contains real anchors before enhancement and the current heading uses aria-current location.
- Read headings also have a text label, while remaining time is deliberately outside a live region.
- Following a section link focuses its target heading and respects reduced-motion scrolling.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Reading progress contents" with `npx shadcn@latest add @haze/toc-progress`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import TocProgress from "@/components/haze/ui/toc-progress.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/toc-progress.md
Customize with real content
Adapt the Haze toc-progress ui for our product. Replace the demo values of these props with our real content: id, items, title, scrollContainer, offset, minutes, class. Keep the layout, the heading level rules and these accessibility details: The ordered list contains real anchors before enhancement and the current heading uses aria-current location. Read headings also have a text label, while remaining time is deliberately outside a live region. Following a section link focuses its target heading and respects reduced-motion scrolling. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using toc-progress, check it fits: use it when a long article needs a reading guide that follows the reader's position; an embedded reading panel needs section links and local progress. Avoid it when use table-of-contents when static anchor links are sufficient; use scroll-progress for a reading bar without a heading list. Alternatives: @haze/table-of-contents, @haze/scroll-progress.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.