Navigation
Article Outline
An article outline placed above the text rather than beside it: the items are numbered, the active one gets a filled number, and the row scrolls by touch.
- scrollspy
- toc
- article
- navigation
Preview
Use it with AI
- 1. Copy the link.
- 2. Write to your agent in your own words and drop the link into the sentence.
- 3. The agent opens the link and installs the component from the registry.
put this in the header: https://vibeui.ru/c/scrollspy-002?lang=en
Contents
1 / 4Зачем
Статья объясняет, почему оглавление на длинной странице перестаёт быть украшением: читатель приходит из поиска и попадает в середину текста.
Как устроено
Разделы помечены идентификаторами, ссылки — обычные якоря, а подсветку добавляет наблюдатель пересечений поверх уже работающей навигации.
На телефоне
Оглавление в строку прокручивается пальцем и не отнимает ширину у текста, поэтому его не приходится прятать за кнопкой.
Границы
Для оглавления из пятнадцати пунктов строка перестаёт работать: там нужен вложенный список или боковая колонка.
Show the full instructions
What the link says, spelled out. Use it when your agent cannot open links — paste this text instead.
# Install and place "scrollspy-002" (Article Outline) from VibeUI
## 1. Install first — do not skip, do not recreate
Run this exact command before writing any code:
npx shadcn@latest add https://vibeui.ru/r/scrollspy-002.json
Registry item: https://vibeui.ru/r/scrollspy-002.json
Installs to: components/vibeui/scrollspy-002.tsx (the exact path follows this project's components.json aliases).
npm dependencies: none.
Registry dependencies: none.
Install it from the registry. Do not recreate it from the description,
do not substitute a similar component from another library, and do not
rewrite it to match the project's existing style.
## 2. What it is
An article outline placed above the text rather than beside it: the items are numbered, the active one gets a filled number, and the row scrolls by touch.
A single-row article outline: the anchor links work without JS and an IntersectionObserver adds the current-section highlight. Zero dependencies, one file.
## 3. How to use it
import { Scrollspy002 } from "@/components/vibeui/scrollspy-002"
<Scrollspy002
title="Contents"
sections={[
{ id: "why", title: "Why", text: "Why a long page needs an outline" },
{ id: "how", title: "How it works", text: "Anchors plus an intersection observer" },
]}
/>
Read the installed file for the full prop list.
## 4. Where to place it
This is a small inline component. Put it exactly where the user asked,
inside the existing markup. Do not create a new page, section or
wrapper for it. If a similar control already sits in that spot,
replace it instead of adding a second one.
Placement: ___
(The user fills this line in. If it is still blank, ask where to put it
instead of guessing.)
## 5. Keep exactly as installed
- the local --vibeui-scrollspy-002-* palette — do not swap it for your theme tokens
- plain anchors without preventDefault: the outline must keep working without JS
- the IntersectionObserver instead of a scroll handler — otherwise the browser recomputes layout on every pixel
- the negative bottom rootMargin: without it a section that already scrolled past becomes active
- aria-current on the active link: a filled number is invisible to a screen reader
- the bottom padding on the last section — without it it never scrolls up and never lights up
## 6. You may change
- the outline heading through title
- the sections through sections: id, title and text
- the accent colour through accent
- the reading area height in the height rule of [data-part="body"]
## 7. Rules
- Section ids must be unique on the page: two blocks with the same ids break the anchors.
- A single-row outline suits five or six items: a long list turns into endless scrolling.
- The reading area is local here; for a whole-page outline drop the observer's root.
- Do not lift the CSS variables into globals.css: the component has to stay a single file.
## 8. Verify
- it renders with no console errors;
- it looks like the preview on the VibeUI page you copied this from;
- if it does not, you changed something listed in section 5 — put it back.For developers
npx shadcn@latest add https://vibeui.ru/r/scrollspy-002.jsonhttps://vibeui.ru/r/scrollspy-002.jsonКомпонент самодостаточен: один файл, без зависимостей, палитра в локальных переменных --vibeui-scrollspy-002-*. Клиентский ("use client") — нужен IntersectionObserver. Наблюдатель следит за разделами внутри собственной области прокрутки: root — сам блок текста, rootMargin обрезает нижние 65%, поэтому активным становится раздел у верхней кромки, а не любой видимый. Ссылки — обычные якоря без preventDefault: без JS они по-прежнему доводят до раздела, наблюдатель добавляет только подсветку. Активный пункт помечен aria-current и залитым кружком номера: в горизонтальном ряду цвета текста мало.
Component source
The same file your agent installs. Here in case you would rather copy it by hand.
"use client"
import { useEffect, useRef, useState } from "react"
import type { ComponentPropsWithoutRef, CSSProperties } from "react"
export type Scrollspy002Section = {
id: string
title: string
text?: string
}
export type Scrollspy002Props = Omit<
ComponentPropsWithoutRef<"div">,
"children"
> & {
sections?: Scrollspy002Section[]
title?: string
accent?: string
}
// Идея компонента: оглавление статьи лежит не сбоку, а сверху — так оно
// работает и на телефоне, где боковой колонки просто нет. Пункты
// пронумерованы, у активного номер заливается: в горизонтальном ряду
// подсветка цветом текста теряется, а залитый кружок виден издалека.
// Слежение — IntersectionObserver: обработчик scroll на каждый пиксель
// заставил бы браузер считать раскладку в самый неподходящий момент.
const STYLES = `
:where([data-vibeui-block="scrollspy-002"]){
--vibeui-scrollspy-002-bg:oklch(1 0 0);
--vibeui-scrollspy-002-fg:oklch(0.23 0.014 265);
--vibeui-scrollspy-002-muted:oklch(0.56 0.014 265);
--vibeui-scrollspy-002-border:oklch(0.91 0.006 265);
--vibeui-scrollspy-002-accent:oklch(0.55 0.19 262);
--vibeui-scrollspy-002-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
[data-vibeui-block="scrollspy-002"]{
display:flex;flex-direction:column;gap:0.625rem;
width:100%;max-width:28rem;box-sizing:border-box;padding:0.9375rem;
background:var(--vibeui-scrollspy-002-bg);
border:1px solid var(--vibeui-scrollspy-002-border);border-radius:0.875rem;
font-family:var(--vibeui-scrollspy-002-font);color:var(--vibeui-scrollspy-002-fg);
}
[data-vibeui-block="scrollspy-002"] [data-part="head"]{display:flex;align-items:baseline;justify-content:space-between;gap:0.75rem}
[data-vibeui-block="scrollspy-002"] [data-part="title"]{margin:0;font-size:0.9375rem;font-weight:650}
[data-vibeui-block="scrollspy-002"] [data-part="counter"]{font-size:0.75rem;color:var(--vibeui-scrollspy-002-muted);font-variant-numeric:tabular-nums}
/* Оглавление в строку: на телефоне боковой колонки нет, а список нужен. */
[data-vibeui-block="scrollspy-002"] [data-part="toc"]{
display:flex;gap:0.375rem;margin:0;padding:0 0 0.25rem;list-style:none;
overflow-x:auto;overscroll-behavior-x:contain;scrollbar-width:thin;
}
[data-vibeui-block="scrollspy-002"] [data-part="link"]{
display:inline-flex;align-items:center;gap:0.375rem;flex:none;
padding:0.3125rem 0.5rem 0.3125rem 0.3125rem;border-radius:9999px;
border:1px solid var(--vibeui-scrollspy-002-border);
color:var(--vibeui-scrollspy-002-muted);text-decoration:none;
font-size:0.75rem;line-height:1;white-space:nowrap;
transition:color .16s ease,border-color .16s ease;
}
[data-vibeui-block="scrollspy-002"] [data-part="num"]{
display:flex;align-items:center;justify-content:center;
width:1.125rem;height:1.125rem;border-radius:9999px;
background:color-mix(in oklab,var(--vibeui-scrollspy-002-muted) 14%,transparent);
font-size:0.625rem;font-weight:700;font-variant-numeric:tabular-nums;
}
/* Активный пункт — залитый номер: в ряду одинаковых чипов цвета текста мало. */
[data-vibeui-block="scrollspy-002"] [data-part="link"][aria-current="true"]{
color:var(--vibeui-scrollspy-002-fg);border-color:var(--vibeui-scrollspy-002-accent);
font-weight:600;
}
[data-vibeui-block="scrollspy-002"] [data-part="link"][aria-current="true"] [data-part="num"]{
background:var(--vibeui-scrollspy-002-accent);color:oklch(1 0 0);
}
[data-vibeui-block="scrollspy-002"] [data-part="link"]:focus-visible{outline:2px solid var(--vibeui-scrollspy-002-accent);outline-offset:2px}
[data-vibeui-block="scrollspy-002"] [data-part="body"]{
height:12rem;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;
padding-right:0.375rem;border-top:1px solid var(--vibeui-scrollspy-002-border);
}
[data-vibeui-block="scrollspy-002"] [data-part="body"]:focus-visible{outline:2px solid var(--vibeui-scrollspy-002-accent);outline-offset:2px;border-radius:0.375rem}
[data-vibeui-block="scrollspy-002"] [data-part="section"]{scroll-margin-top:0.75rem;padding-top:0.75rem}
[data-vibeui-block="scrollspy-002"] [data-part="section"] h4{margin:0 0 0.25rem;font-size:0.875rem;font-weight:650}
[data-vibeui-block="scrollspy-002"] [data-part="section"] p{margin:0;font-size:0.8125rem;line-height:1.5;color:var(--vibeui-scrollspy-002-muted)}
/* Запас снизу: без него последний раздел не долистывается до верха и не подсвечивается. */
[data-vibeui-block="scrollspy-002"] [data-part="section"]:last-child{padding-bottom:8rem}
@media (prefers-reduced-motion:reduce){
[data-vibeui-block="scrollspy-002"] [data-part="body"]{scroll-behavior:auto}
[data-vibeui-block="scrollspy-002"] *{animation:none!important;transition:none!important}
}
`
const DEFAULT_SECTIONS: Scrollspy002Section[] = [
{
id: "why",
title: "Зачем",
text: "Статья объясняет, почему оглавление на длинной странице перестаёт быть украшением: читатель приходит из поиска и попадает в середину текста.",
},
{
id: "how",
title: "Как устроено",
text: "Разделы помечены идентификаторами, ссылки — обычные якоря, а подсветку добавляет наблюдатель пересечений поверх уже работающей навигации.",
},
{
id: "mobile",
title: "На телефоне",
text: "Оглавление в строку прокручивается пальцем и не отнимает ширину у текста, поэтому его не приходится прятать за кнопкой.",
},
{
id: "limits",
title: "Границы",
text: "Для оглавления из пятнадцати пунктов строка перестаёт работать: там нужен вложенный список или боковая колонка.",
},
]
/**
* Оглавление статьи в строку: активный пункт помечен залитым номером.
* Один файл, ноль зависимостей, собственная палитра.
*/
export function Scrollspy002({
sections = DEFAULT_SECTIONS,
title = "Содержание",
accent,
className,
style,
...props
}: Scrollspy002Props) {
const body = useRef<HTMLDivElement>(null)
const [active, setActive] = useState(sections[0]?.id)
useEffect(() => {
const root = body.current
if (!root) return
const watcher = new IntersectionObserver(
(entries) => {
const visible = entries
.filter((entry) => entry.isIntersecting)
.sort(
(a, b) => a.boundingClientRect.top - b.boundingClientRect.top,
)[0]
if (visible) setActive(visible.target.id)
},
{ root, rootMargin: "0px 0px -65% 0px", threshold: 0 },
)
root
.querySelectorAll("[data-part='section']")
.forEach((section) => watcher.observe(section))
return () => watcher.disconnect()
}, [sections])
const position = sections.findIndex((section) => section.id === active) + 1
const palette = {
...(accent ? { "--vibeui-scrollspy-002-accent": accent } : null),
...style,
} as CSSProperties
return (
<>
<style href="vibeui-scrollspy-002" precedence="medium">
{STYLES}
</style>
<div
{...props}
data-vibeui-block="scrollspy-002"
className={className}
style={palette}
>
<div data-part="head">
<h3 data-part="title">{title}</h3>
<span data-part="counter">
{position} / {sections.length}
</span>
</div>
<nav aria-label={title}>
<ul data-part="toc">
{sections.map((section, index) => (
<li key={section.id}>
<a
data-part="link"
href={`#${section.id}`}
aria-current={section.id === active}
>
<span data-part="num">{index + 1}</span>
{section.title}
</a>
</li>
))}
</ul>
</nav>
<div
data-part="body"
ref={body}
tabIndex={0}
role="group"
aria-label="Текст статьи"
>
{sections.map((section) => (
<section key={section.id} id={section.id} data-part="section">
<h4>{section.title}</h4>
<p>{section.text}</p>
</section>
))}
</div>
</div>
</>
)
}