Navigation

Scrollspy Contents

A table of contents that highlights the section in view: tracking runs on IntersectionObserver, not a scroll handler.

  • scrollspy
  • toc
  • reading
  • observer

Preview

1440pxHost theme

Use it with AI

  1. 1. Copy the link.
  2. 2. Write to your agent in your own words and drop the link into the sentence.
  3. 3. The agent opens the link and installs the component from the registry.

put this in the header: https://vibeui.ru/c/scrollspy-001?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-001" (Scrollspy 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-001.json

Registry item: https://vibeui.ru/r/scrollspy-001.json
Installs to: components/vibeui/scrollspy-001.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 table of contents that highlights the section in view: tracking runs on IntersectionObserver, not a scroll handler.

A table of contents with current-section highlighting: the list on the left, scrollable text on the right, a bar on the active item. Zero dependencies, one file.

## 3. How to use it
import { Scrollspy001 } from "@/components/vibeui/scrollspy-001"

<Scrollspy001 sections={[{ id: "install", title: "Install", text: "…" }]} />

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-001-* palette — do not swap it for your theme tokens
- IntersectionObserver instead of a scroll handler: the browser decides when to recompute
- the rootMargin cutting off the bottom: otherwise a barely visible section becomes active
- the tail space under the last section — without it it never scrolls into view
- the bar on the active item rather than colour alone
- plain links with href: the contents must work without JS too

## 6. You may change
- the sections array and their text
- title — the contents heading
- the text area height
- the accent through the accent prop

## 7. Rules
- The component watches its own scroll area: drop root to watch the page instead.
- The highlight lags a frame on an instant jump — that is observer behaviour, not a bug.
- A two-item contents list is pointless: it pays off from four sections up.
- 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-001.json
https://vibeui.ru/r/scrollspy-001.json

Компонент самодостаточен: один файл, без зависимостей, собственная палитра в локальных переменных --vibeui-scrollspy-001-*. Клиентский: "use client" ради IntersectionObserver. Наблюдатель ограничен областью текста через root, а rootMargin отрезает нижние 60%, иначе активным становится раздел, который только показался снизу. У последнего раздела есть запас снизу — без него он не долистывается.

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 Scrollspy001Section = {
  id: string
  title: string
  text?: string
}

export type Scrollspy001Props = Omit<
  ComponentPropsWithoutRef<"div">,
  "children"
> & {
  sections?: Scrollspy001Section[]
  title?: string
  accent?: string
}

// Идея компонента: оглавление, которое подсвечивает раздел, видимый сейчас.
// Слежение — IntersectionObserver, а не обработчик scroll: браузер сам решает,
// когда пересчитывать, и страница не дёргается при быстрой прокрутке. Полоса
// сверху обрезана rootMargin, иначе активным становится раздел, ушедший вверх.
const STYLES = `
:where([data-vibeui-block="scrollspy-001"]){
--vibeui-scrollspy-001-bg:oklch(1 0 0);
--vibeui-scrollspy-001-fg:oklch(0.24 0.014 265);
--vibeui-scrollspy-001-muted:oklch(0.56 0.014 265);
--vibeui-scrollspy-001-border:oklch(0.91 0.006 265);
--vibeui-scrollspy-001-accent:oklch(0.55 0.2 262);
--vibeui-scrollspy-001-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
[data-vibeui-block="scrollspy-001"]{
display:grid;grid-template-columns:9rem 1fr;gap:1rem;
width:100%;max-width:30rem;box-sizing:border-box;padding:0.875rem;
background:var(--vibeui-scrollspy-001-bg);
border:1px solid var(--vibeui-scrollspy-001-border);border-radius:0.875rem;
font-family:var(--vibeui-scrollspy-001-font);color:var(--vibeui-scrollspy-001-fg);
}
[data-vibeui-block="scrollspy-001"] [data-part="toc"]{
position:sticky;top:0;align-self:start;
display:flex;flex-direction:column;gap:0.125rem;
border-left:2px solid var(--vibeui-scrollspy-001-border);
}
[data-vibeui-block="scrollspy-001"] [data-part="head"]{
margin:0 0 0.375rem 0.625rem;font-size:0.6875rem;letter-spacing:0.04em;
text-transform:uppercase;color:var(--vibeui-scrollspy-001-muted);
}
/* Активный пункт помечен полосой у края, а не только цветом текста. */
[data-vibeui-block="scrollspy-001"] [data-part="link"]{
position:relative;padding:0.25rem 0.5rem 0.25rem 0.625rem;
color:var(--vibeui-scrollspy-001-muted);text-decoration:none;
font-size:0.8125rem;line-height:1.3;
}
[data-vibeui-block="scrollspy-001"] [data-part="link"][aria-current="true"]{color:var(--vibeui-scrollspy-001-fg);font-weight:650}
[data-vibeui-block="scrollspy-001"] [data-part="link"][aria-current="true"]::before{
content:"";position:absolute;left:-2px;top:0.25rem;bottom:0.25rem;
width:2px;background:var(--vibeui-scrollspy-001-accent);
}
[data-vibeui-block="scrollspy-001"] [data-part="link"]:focus-visible{outline:2px solid var(--vibeui-scrollspy-001-accent);outline-offset:-2px;border-radius:0.25rem}
[data-vibeui-block="scrollspy-001"] [data-part="body"]{
height:13rem;overflow-y:auto;overscroll-behavior:contain;
scroll-behavior:smooth;padding-right:0.375rem;
}
[data-vibeui-block="scrollspy-001"] [data-part="section"]{scroll-margin-top:0.5rem}
[data-vibeui-block="scrollspy-001"] [data-part="section"] h3{margin:0 0 0.25rem;font-size:0.875rem;font-weight:650}
[data-vibeui-block="scrollspy-001"] [data-part="section"] p{margin:0 0 1.25rem;font-size:0.8125rem;line-height:1.5;color:var(--vibeui-scrollspy-001-muted)}
/* Запас снизу: без него последний раздел не долистывается и не подсвечивается. */
[data-vibeui-block="scrollspy-001"] [data-part="section"]:last-child p{margin-bottom:9rem}
@media (prefers-reduced-motion:reduce){
[data-vibeui-block="scrollspy-001"] [data-part="body"]{scroll-behavior:auto}
[data-vibeui-block="scrollspy-001"] *{animation:none!important;transition:none!important}
}
`

const DEFAULT_SECTIONS: Scrollspy001Section[] = [
  {
    id: "install",
    title: "Установка",
    text: "Компонент ставится одной командой: файл копируется в проект, зависимостей нет.",
  },
  {
    id: "props",
    title: "Пропсы",
    text: "Каждый проп имеет разумное значение по умолчанию, поэтому компонент рендерится и без единого атрибута.",
  },
  {
    id: "theme",
    title: "Тема",
    text: "Цвета живут в локальных переменных с префиксом компонента и не конфликтуют с темой проекта-хозяина.",
  },
  {
    id: "a11y",
    title: "Доступность",
    text: "Разметка семантическая, фокус виден, состояние передаётся не только цветом.",
  },
]

/**
 * Оглавление с подсветкой видимого раздела: IntersectionObserver вместо scroll.
 * Один файл, ноль зависимостей, собственная палитра.
 */
export function Scrollspy001({
  sections = DEFAULT_SECTIONS,
  title = "На странице",
  accent,
  className,
  style,
  ...props
}: Scrollspy001Props) {
  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 -60% 0px", threshold: 0 },
    )

    root
      .querySelectorAll("[data-part='section']")
      .forEach((section) => watcher.observe(section))
    return () => watcher.disconnect()
  }, [sections])

  const palette = {
    ...(accent ? { "--vibeui-scrollspy-001-accent": accent } : null),
    ...style,
  } as CSSProperties

  return (
    <>
      <style href="vibeui-scrollspy-001" precedence="medium">
        {STYLES}
      </style>
      <div
        {...props}
        data-vibeui-block="scrollspy-001"
        className={className}
        style={palette}
      >
        <nav data-part="toc" aria-label={title}>
          <p data-part="head">{title}</p>
          {sections.map((section) => (
            <a
              key={section.id}
              data-part="link"
              href={`#${section.id}`}
              aria-current={section.id === active}
              onClick={(event) => {
                event.preventDefault()
                body.current
                  ?.querySelector(`#${section.id}`)
                  ?.scrollIntoView({ block: "start" })
              }}
            >
              {section.title}
            </a>
          ))}
        </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">
              <h3>{section.title}</h3>
              <p>{section.text}</p>
            </section>
          ))}
        </div>
      </div>
    </>
  )
}