Navigation
Nested Contents
A two-level outline that does not dump every sub-item at once: only the chapter the reader is currently inside stays expanded.
- scrollspy
- toc
- nested
- docs
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-003?lang=en
Начало
Короткая глава о том, что понадобится до установки.
Требования
Нужен только пакетный менеджер и проект, куда будет скопирован файл компонента.
Установка
Одна команда копирует исходник в проект: сборка при этом ничего не скачивает из сети.
Интерфейс
Все пропсы имеют значения по умолчанию.
Пропсы
Данные передаются массивом, подписи — строками, а внешний вид меняется одной переменной акцента.
События
Компонент не навязывает обработчиков: он остаётся навигацией, а не хранилищем состояния приложения.
Доступность
Ссылки остаются ссылками, состояние передаётся не только цветом.
Клавиатура
Оглавление обходится табом, у каждой ссылки видимая обводка фокуса.
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-003" (Nested Contents) 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-003.json
Registry item: https://vibeui.ru/r/scrollspy-003.json
Installs to: components/vibeui/scrollspy-003.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
A two-level outline that does not dump every sub-item at once: only the chapter the reader is currently inside stays expanded.
A two-level outline: sub-items show only for the current chapter and the highlight covers both levels. Zero dependencies, one file.
## 3. How to use it
import { Scrollspy003 } from "@/components/vibeui/scrollspy-003"
<Scrollspy003
title="Sections"
chapters={[
{ id: "start", title: "Getting started", text: "What you need first", children: [{ id: "start-install", title: "Install", text: "A single command" }] },
]}
/>
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-003-* palette — do not swap it for your theme tokens
- expanding only the current chapter: a fully expanded tree ends up longer than the text
- observing both levels at once — otherwise a sub-item never becomes active
- plain anchors without preventDefault: the outline must keep working without JS
- aria-current on the current link, not just a bolder weight
- deriving data-open from the active section instead of keeping separate open state
## 6. You may change
- the outline heading through title
- the chapters and sub-items through chapters and the nested children
- the accent colour through accent
- the outline column width in grid-template-columns
## 7. Rules
- The component does not draw a third nesting level: that needs a different layout.
- Chapter and sub-item ids must be unique across the whole page.
- A chapter without children behaves like a plain item — that is intentional.
- 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-003.jsonhttps://vibeui.ru/r/scrollspy-003.jsonКомпонент самодостаточен: один файл, без зависимостей, палитра в локальных переменных --vibeui-scrollspy-003-*. Клиентский ("use client") — нужен IntersectionObserver. Наблюдатель следит за разделами обоих уровней сразу, поэтому активным может стать и глава, и её подпункт. Раскрытие второго уровня не хранится состоянием: список показывается правилом li[data-open="true"] > [data-part="sub"], где data-open вычисляется из того, активна ли глава или любой её потомок. Ссылки — обычные якоря, подсветка идёт через 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 Scrollspy003Child = {
id: string
title: string
text?: string
}
export type Scrollspy003Chapter = Scrollspy003Child & {
children?: Scrollspy003Child[]
}
export type Scrollspy003Props = Omit<
ComponentPropsWithoutRef<"div">,
"children"
> & {
chapters?: Scrollspy003Chapter[]
title?: string
accent?: string
}
// Идея компонента: двухуровневое оглавление, которое не вываливает сразу все
// подпункты. Раскрыта только та глава, внутри которой читатель сейчас, —
// остальные свёрнуты, и список остаётся коротким на любой длине текста.
// Подсветка идёт по обоим уровням: глава помечается как раздел-родитель,
// подпункт — как текущая цель, поэтому видно и «где я», и «в чём».
const STYLES = `
:where([data-vibeui-block="scrollspy-003"]){
--vibeui-scrollspy-003-bg:oklch(1 0 0);
--vibeui-scrollspy-003-fg:oklch(0.23 0.014 265);
--vibeui-scrollspy-003-muted:oklch(0.56 0.014 265);
--vibeui-scrollspy-003-border:oklch(0.91 0.006 265);
--vibeui-scrollspy-003-accent:oklch(0.53 0.16 175);
--vibeui-scrollspy-003-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
[data-vibeui-block="scrollspy-003"]{
display:grid;grid-template-columns:10rem 1fr;gap:0.875rem;
width:100%;max-width:32rem;box-sizing:border-box;padding:0.9375rem;
background:var(--vibeui-scrollspy-003-bg);
border:1px solid var(--vibeui-scrollspy-003-border);border-radius:0.875rem;
font-family:var(--vibeui-scrollspy-003-font);color:var(--vibeui-scrollspy-003-fg);
}
[data-vibeui-block="scrollspy-003"] [data-part="toc"]{position:sticky;top:0;align-self:start}
[data-vibeui-block="scrollspy-003"] [data-part="head"]{
margin:0 0 0.5rem;font-size:0.6875rem;font-weight:700;letter-spacing:0.06em;
text-transform:uppercase;color:var(--vibeui-scrollspy-003-muted);
}
[data-vibeui-block="scrollspy-003"] ul{margin:0;padding:0;list-style:none}
[data-vibeui-block="scrollspy-003"] [data-part="link"]{
display:block;padding:0.25rem 0.375rem;border-radius:0.375rem;
color:var(--vibeui-scrollspy-003-muted);text-decoration:none;
font-size:0.8125rem;line-height:1.3;
}
[data-vibeui-block="scrollspy-003"] [data-part="link"]:hover{color:var(--vibeui-scrollspy-003-fg)}
[data-vibeui-block="scrollspy-003"] [data-part="link"]:focus-visible{outline:2px solid var(--vibeui-scrollspy-003-accent);outline-offset:-2px}
[data-vibeui-block="scrollspy-003"] li[data-open="true"] > [data-part="link"]{color:var(--vibeui-scrollspy-003-fg);font-weight:650}
[data-vibeui-block="scrollspy-003"] [data-part="link"][aria-current="true"]{
color:var(--vibeui-scrollspy-003-fg);font-weight:650;
background:color-mix(in oklab,var(--vibeui-scrollspy-003-accent) 12%,transparent);
}
/* Второй уровень живёт только у раскрытой главы: иначе список длиннее текста. */
[data-vibeui-block="scrollspy-003"] [data-part="sub"]{
display:none;margin:0.125rem 0 0.25rem 0.5rem;
border-left:1px solid var(--vibeui-scrollspy-003-border);padding-left:0.375rem;
}
[data-vibeui-block="scrollspy-003"] li[data-open="true"] > [data-part="sub"]{display:block}
[data-vibeui-block="scrollspy-003"] [data-part="sub"] [data-part="link"]{font-size:0.75rem;padding:0.1875rem 0.375rem}
[data-vibeui-block="scrollspy-003"] [data-part="body"]{
height:13rem;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;
padding-right:0.375rem;
}
[data-vibeui-block="scrollspy-003"] [data-part="body"]:focus-visible{outline:2px solid var(--vibeui-scrollspy-003-accent);outline-offset:2px;border-radius:0.375rem}
[data-vibeui-block="scrollspy-003"] [data-part="section"]{scroll-margin-top:0.5rem}
[data-vibeui-block="scrollspy-003"] [data-part="section"] h4{margin:0 0 0.25rem;font-size:0.875rem;font-weight:650}
[data-vibeui-block="scrollspy-003"] [data-part="section"] h5{margin:0.75rem 0 0.25rem;font-size:0.8125rem;font-weight:600;color:var(--vibeui-scrollspy-003-accent)}
[data-vibeui-block="scrollspy-003"] [data-part="section"] p{margin:0 0 0.5rem;font-size:0.8125rem;line-height:1.5;color:var(--vibeui-scrollspy-003-muted)}
[data-vibeui-block="scrollspy-003"] [data-part="body"] > :last-child{padding-bottom:9rem}
@media (prefers-reduced-motion:reduce){
[data-vibeui-block="scrollspy-003"] [data-part="body"]{scroll-behavior:auto}
[data-vibeui-block="scrollspy-003"] *{animation:none!important;transition:none!important}
}
`
const DEFAULT_CHAPTERS: Scrollspy003Chapter[] = [
{
id: "start",
title: "Начало",
text: "Короткая глава о том, что понадобится до установки.",
children: [
{
id: "start-req",
title: "Требования",
text: "Нужен только пакетный менеджер и проект, куда будет скопирован файл компонента.",
},
{
id: "start-install",
title: "Установка",
text: "Одна команда копирует исходник в проект: сборка при этом ничего не скачивает из сети.",
},
],
},
{
id: "api",
title: "Интерфейс",
text: "Все пропсы имеют значения по умолчанию.",
children: [
{
id: "api-props",
title: "Пропсы",
text: "Данные передаются массивом, подписи — строками, а внешний вид меняется одной переменной акцента.",
},
{
id: "api-events",
title: "События",
text: "Компонент не навязывает обработчиков: он остаётся навигацией, а не хранилищем состояния приложения.",
},
],
},
{
id: "a11y",
title: "Доступность",
text: "Ссылки остаются ссылками, состояние передаётся не только цветом.",
children: [
{
id: "a11y-keys",
title: "Клавиатура",
text: "Оглавление обходится табом, у каждой ссылки видимая обводка фокуса.",
},
],
},
]
/**
* Двухуровневое оглавление: раскрыта только текущая глава, подсветка на обоих уровнях.
* Один файл, ноль зависимостей, собственная палитра.
*/
export function Scrollspy003({
chapters = DEFAULT_CHAPTERS,
title = "Разделы",
accent,
className,
style,
...props
}: Scrollspy003Props) {
const body = useRef<HTMLDivElement>(null)
const [active, setActive] = useState(chapters[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 -70% 0px", threshold: 0 },
)
root
.querySelectorAll("[data-part='section']")
.forEach((section) => watcher.observe(section))
return () => watcher.disconnect()
}, [chapters])
const palette = {
...(accent ? { "--vibeui-scrollspy-003-accent": accent } : null),
...style,
} as CSSProperties
return (
<>
<style href="vibeui-scrollspy-003" precedence="medium">
{STYLES}
</style>
<div
{...props}
data-vibeui-block="scrollspy-003"
className={className}
style={palette}
>
<nav data-part="toc" aria-label={title}>
<p data-part="head">{title}</p>
<ul>
{chapters.map((chapter) => {
const open =
chapter.id === active ||
(chapter.children ?? []).some((child) => child.id === active)
return (
<li key={chapter.id} data-open={open}>
<a
data-part="link"
href={`#${chapter.id}`}
aria-current={chapter.id === active}
>
{chapter.title}
</a>
{chapter.children?.length ? (
<ul data-part="sub">
{chapter.children.map((child) => (
<li key={child.id}>
<a
data-part="link"
href={`#${child.id}`}
aria-current={child.id === active}
>
{child.title}
</a>
</li>
))}
</ul>
) : null}
</li>
)
})}
</ul>
</nav>
<div
data-part="body"
ref={body}
tabIndex={0}
role="group"
aria-label="Текст документации"
>
{chapters.map((chapter) => (
<section key={chapter.id} id={chapter.id} data-part="section">
<h4>{chapter.title}</h4>
<p>{chapter.text}</p>
{chapter.children?.map((child) => (
<section key={child.id} id={child.id} data-part="section">
<h5>{child.title}</h5>
<p>{child.text}</p>
</section>
))}
</section>
))}
</div>
</div>
</>
)
}