Scroll index
Minimal vertical hairline tick rail that tracks scroll progress and reveals floating section label pills on hover or focus.
pnpm dlx shadcn@latest add @haze/scroll-index---
import { cn } from "../../../lib/haze/utils";
interface IndexItem {
id: string;
label: string;
/** Render a medium resting tick for major section headings. */
major?: boolean;
}
interface Props {
/** Unique on the page. Identifies this index rail landmark. */
id: string;
items?: IndexItem[];
/** Optional ID of a scrollable element; tracks the page viewport when omitted. */
scrollContainer?: string;
/** Accessible name for the navigation landmark. */
label?: string;
/** Side of the tick rail where floating label pills appear. */
side?: "left" | "right";
/** Top offset in pixels used to determine the active section. */
offset?: number;
class?: string;
}
const defaultItems: IndexItem[] = [
{ id: "index-rhythm", label: "Rhythm and density", major: true },
{ id: "index-alignment", label: "Optical alignment" },
{ id: "index-motion", label: "Restrained motion", major: true },
{ id: "index-feedback", label: "Micro-feedback" },
{ id: "index-contrast", label: "Surface contrast", major: true },
{ id: "index-closing", label: "Closing notes" },
];
const {
id,
items = defaultItems,
scrollContainer,
label = "Section index",
side = "left",
offset = 28,
class: className,
} = Astro.props;
---
<nav
id={id}
data-haze-scroll-index
data-scroll-container={scrollContainer}
data-offset={offset}
aria-label={label}
class={cn("min-w-0", className)}
>
<ol
role="list"
class={cn("flex flex-col gap-0", side === "left" ? "items-end" : "items-start")}
>
{
items.map((item, index) => {
const isFirst = index === 0;
return (
<li class="relative">
<a
href={`#${encodeURIComponent(item.id)}`}
data-si-link
data-si-index={index}
aria-current={isFirst ? "location" : undefined}
class={cn(
"group relative flex h-6 min-w-7 items-center rounded-sm focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring",
side === "left" ? "justify-end" : "justify-start",
)}
>
<span
aria-hidden="true"
class={cn(
"block h-0.5 shrink-0 rounded-full transition-[width,background-color] duration-200 ease-snappy motion-reduce:transition-none",
item.major ? "w-3.5 bg-border-strong" : "w-2 bg-border",
"group-hover:w-5 group-hover:bg-foreground/80 group-focus-visible:w-5 group-focus-visible:bg-foreground/80",
"[[aria-current=location]_&]:w-6 [[aria-current=location]_&]:bg-foreground",
)}
></span>
<span
class={cn(
"pointer-events-none absolute top-1/2 -translate-y-1/2 whitespace-nowrap rounded-md border border-frame bg-popover px-2 py-0.5 text-xs/4 font-medium text-popover-foreground opacity-0 shadow-key transition-[opacity,translate] duration-150 ease-snappy motion-reduce:transition-none",
"group-hover:translate-x-0 group-hover:opacity-100 group-focus-visible:translate-x-0 group-focus-visible:opacity-100",
side === "left" ? "right-full me-2 translate-x-1" : "left-full ms-2 -translate-x-1",
)}
>
{item.label}
</span>
</a>
</li>
);
})
}
</ol>
</nav>
<script>
function syncScrollIndex(root: HTMLElement) {
const links = Array.from(root.querySelectorAll<HTMLAnchorElement>("[data-si-link]"));
if (!links.length) return;
const targets = links.map((link) => document.getElementById(decodeURIComponent(link.hash.slice(1))));
const container = root.dataset.scrollContainer ? document.getElementById(root.dataset.scrollContainer) : null;
const offset = Number(root.dataset.offset) || 0;
const topEdge = (container?.getBoundingClientRect().top ?? 0) + offset;
const scrollTop = container ? container.scrollTop : window.scrollY;
const scrollHeight = container ? container.scrollHeight : document.documentElement.scrollHeight;
const viewport = container ? container.clientHeight : window.innerHeight;
const atBottom = scrollTop > 0 && scrollTop + viewport >= scrollHeight - 2;
let active = 0;
if (scrollTop <= 2) {
active = 0;
} else if (atBottom) {
active = links.length - 1;
} else {
for (let i = 0; i < targets.length; i++) {
const el = targets[i];
if (el && el.getBoundingClientRect().top <= topEdge + 12) {
active = i;
}
}
}
links.forEach((link, i) => {
if (i === active) link.setAttribute("aria-current", "location");
else link.removeAttribute("aria-current");
});
}
function enhanceScrollIndex(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const links = Array.from(root.querySelectorAll<HTMLAnchorElement>("[data-si-link]"));
if (!links.length) return;
const container = root.dataset.scrollContainer ? document.getElementById(root.dataset.scrollContainer) : null;
const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");
links.forEach((link, index) => {
link.addEventListener("click", (event) => {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
const target = document.getElementById(decodeURIComponent(link.hash.slice(1)));
if (!target) return;
event.preventDefault();
if (!target.hasAttribute("tabindex")) target.tabIndex = -1;
const behavior: ScrollBehavior = reduced.matches ? "auto" : "smooth";
if (container) {
const offset = Number(root.dataset.offset) || 0;
const nextTop = container.scrollTop + target.getBoundingClientRect().top - container.getBoundingClientRect().top - offset + 4;
container.scrollTo({ top: Math.max(0, nextTop), behavior });
} else {
target.scrollIntoView({ block: "start", behavior });
}
links.forEach((item, i) => {
if (i === index) item.setAttribute("aria-current", "location");
else item.removeAttribute("aria-current");
});
target.focus({ preventScroll: true });
history.replaceState(history.state, "", link.hash);
});
link.addEventListener("keydown", (event) => {
let next: number | undefined;
if (event.key === "ArrowDown") next = (index + 1) % links.length;
else if (event.key === "ArrowUp") next = (index - 1 + links.length) % links.length;
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = links.length - 1;
if (next === undefined) return;
event.preventDefault();
links[next].focus();
});
});
if (container) {
let localFrame = 0;
container.addEventListener(
"scroll",
() => {
if (localFrame) return;
localFrame = requestAnimationFrame(() => {
localFrame = 0;
syncScrollIndex(root);
});
},
{ passive: true },
);
}
if ("IntersectionObserver" in window) {
const targets = links
.map((link) => document.getElementById(decodeURIComponent(link.hash.slice(1))))
.filter((el): el is HTMLElement => Boolean(el));
if (targets.length) {
const observer = new IntersectionObserver(() => syncScrollIndex(root), {
root: container,
threshold: [0, 0.25, 0.5, 1],
});
targets.forEach((el) => observer.observe(el));
}
}
root.setAttribute("data-enhanced", "");
syncScrollIndex(root);
}
const updateAllScrollIndices = () => {
document.querySelectorAll<HTMLElement>("[data-haze-scroll-index][data-enhanced]").forEach(syncScrollIndex);
};
const initScrollIndices = () => {
document.querySelectorAll<HTMLElement>("[data-haze-scroll-index]").forEach(enhanceScrollIndex);
};
initScrollIndices();
if (!document.documentElement.hasAttribute("data-haze-scroll-index-listener")) {
document.documentElement.setAttribute("data-haze-scroll-index-listener", "");
let frame = 0;
document.addEventListener(
"scroll",
() => {
if (frame) return;
frame = requestAnimationFrame(() => {
frame = 0;
updateAllScrollIndices();
});
},
true,
);
window.addEventListener("resize", updateAllScrollIndices, { passive: true });
window.addEventListener("hashchange", updateAllScrollIndices);
document.addEventListener("astro:page-load", initScrollIndices);
}
</script>When to use
- An editorial article or scrollable pane needs a right-edge tick-mark rail instead of a full sidebar list
- Readers want instant visual orientation and smooth section jumping with minimal visual footprint
When not to use
- All heading labels must stay permanently visible for scanning; use table-of-contents
- Readers need reading-time estimates and a completion progress bar; use toc-progress
Installation
Add the Haze registry to components.json once, then install Scroll index with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/scroll-indexnpx shadcn@latest add @haze/scroll-indexyarn dlx shadcn@latest add @haze/scroll-indexbunx --bun shadcn@latest add @haze/scroll-indexFirst 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 ID for the index navigation landmark. |
| items | { id: string; label: string; major?: boolean }[] | 6 sample sections | Section anchor IDs and labels; major draws a medium resting tick while minor draws a short hairline. |
| scrollContainer | string | – | Optional ID of a scrollable container element; tracks the window when omitted. |
| label | string | "Section index" | Accessible name for the navigation landmark. |
| side | "left" | "right" | "left" | Side of the tick rail where floating section label pills reveal. |
| offset | number | 28 | Top threshold in pixels used to determine the currently active section. |
| class | string | – | Additional classes on the outer nav element. |
Keyboard interactions
- TabShiftTab
- Enter or leave the vertical tick rail
- ArrowUpArrowDown
- Move focus along the section ticks and reveal each floating label pill
- HomeEnd
- Jump focus to the first or last section marker
- Enter
- Scroll to the target section and move focus to its heading
Accessibility
- Renders real anchor links inside an ordered list so jumping to sections works without JavaScript.
- Marks the active section link with aria-current="location" and moves focus to the target heading on click.
- Falls back to instant scrolling and disables tick animations when prefers-reduced-motion is enabled.
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 "Scroll index" with `npx shadcn@latest add @haze/scroll-index`. 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 ScrollIndex from "@/components/haze/ui/scroll-index.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/scroll-index.md
Customize with real content
Adapt the Haze scroll-index ui for our product. Replace the demo values of these props with our real content: id, items, scrollContainer, label, side, offset, class. Keep the layout, the heading level rules and these accessibility details: Renders real anchor links inside an ordered list so jumping to sections works without JavaScript. Marks the active section link with aria-current="location" and moves focus to the target heading on click. Falls back to instant scrolling and disables tick animations when prefers-reduced-motion is enabled. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using scroll-index, check it fits: use it when an editorial article or scrollable pane needs a right-edge tick-mark rail instead of a full sidebar list; readers want instant visual orientation and smooth section jumping with minimal visual footprint. Avoid it when all heading labels must stay permanently visible for scanning; use table-of-contents; readers need reading-time estimates and a completion progress bar; use toc-progress. Alternatives: @haze/table-of-contents, @haze/toc-progress.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.