GhostScrollSpy specification
Status: Approved for Issue #339 (admin sign-off 2026-11-26). Implementation follows the recommended defaults for the open architectural questions below unless noted in the PR.
Related: GhostLink specification, GhostBreadcrumb specification, GhostScrollArea specification, accessibility standard, and styling architecture.
Purpose and user problems
GhostScrollSpy is a headless section-navigation primitive (@ghostvue/vue) with an optional styled wrapper (@ghostvue/themes) that keeps an in-page table of contents or section rail synchronized with scroll position:
- Renders semantic landmark navigation (
<nav>→<ol>→<li>→<a href="#...">) built onGhostLink, so every section remains reachable as an ordinary fragment link even without JavaScript. - Observes scroll position passively (read-only) to determine which target section is currently active and expose
aria-current="location"on the matching link. - Exposes overall scroll progress and interpolated inter-item progress as CSS custom properties (plus travel direction as a
data-travelhook) so rails, progress bars, and indicators can animate with zero per-frame Vue re-renders. - Handles plain primary activation (click or
Enter) by scrolling smoothly to the target (honoringprefers-reduced-motion: reduce), updating the URL hash without burying browser history, and moving focus to the target so subsequentTabpresses continue inside that section.
The immediate in-repo consumer is the docs home page section rail (apps/docs/.vitepress/theme/LandingSectionRail.vue and landing-motion.ts), which will migrate onto GhostScrollSpy once approved and implemented.
Non-goals
- Scroll-jacking or scroll-snapping:
GhostScrollSpynever intercepts wheel, touch, or keyboard scrolling (preventDefault()is never called on scroll events) and never forces scroll-snap alignment. - Section reveal animations: Intro/outro animations on page sections (such as scroll-driven timelines or
IntersectionObserversection phases) stay owned by the consumer page, notGhostScrollSpy. - Client-side routing / multi-page TOCs: Only same-document fragment targets (
#<id>) are tracked; route matching across pages belongs to the app router orGhostBreadcrumb. - Automatic heading discovery:
GhostScrollSpydoes not scan the DOM forh2/h3headings or generate labels; consumers declare the tracked items. - Nested tree expansion or collapsible sub-TOCs: Flat ordered section lists are in scope; hierarchical expandable outlines belong to
GhostTreeor consumer composition.
Public API
Parts and exports
Headless exports from @ghostvue/vue:
GhostScrollSpy— Root navigation landmark (as="nav"default), scroll measurement coordinator, CSS progress variable host, and context provider.GhostScrollSpyList— Ordered list container (as="ol"default).GhostScrollSpyItem— List item wrapper (as="li"default).GhostScrollSpyLink— Section link (as="a"default, built onGhostLink) registering its target ID, exposingaria-current="location"anddata-state="active"when current, and performing reduced-motion-aware scroll + focus transfer on plain activation.useGhostScrollSpy— Headless composable owning target registration, passive scroll/resize observation, pure position resolution, CSS progress updates, andscrollTo(targetId)navigation. Can be used standalone (for custom layouts or non-compound lists) or behindGhostScrollSpy.- Pure framework-neutral helpers (generalized from
landing-motion.ts):resolveScrollSpyActiveIndex,resolveScrollSpyProgress,resolveScrollSpySegmentProgress,resolveScrollSpyTravelDirection. - Context key & types:
ghostScrollSpyContextKey,GhostScrollSpyProps,GhostScrollSpySlotProps,GhostScrollSpyExposed,GhostScrollSpyListProps,GhostScrollSpyItemProps,GhostScrollSpyLinkProps,GhostScrollSpyHistoryMode,GhostScrollSpyOrientation,GhostScrollSpyTravelDirection,UseGhostScrollSpyOptions,UseGhostScrollSpyReturn.
Themed exports from @ghostvue/themes:
GhostScrollSpy,GhostScrollSpyList,GhostScrollSpyItem,GhostScrollSpyLinkwrapping the headless parts and shipping default navigation rail/TOC recipe styling (ghost-scroll-spy.css).
Props and configuration
GhostScrollSpy / useGhostScrollSpy
| Prop / Option | Type | Default | Contract |
|---|---|---|---|
as | string | Component | 'nav' | Root landmark element (GhostScrollSpy only). |
label | string | 'Page sections' | Default aria-label when neither aria-label nor aria-labelledby is passed via attrs. |
modelValue | string | undefined | undefined | Controlled active target ID (without leading #). |
defaultValue | string | undefined | undefined | Initial active target ID in uncontrolled mode (see Open Question #4 for SSR behavior when omitted). |
orientation | 'vertical' | 'horizontal' | 'vertical' | Layout axis exposed via data-orientation (and arrow/scroll axis if applicable; see Open Questions #1–#2). |
container | HTMLElement | Window | null | undefined | undefined (window) | Scroll container to observe and scroll (see Open Question #3). |
probeOffset | number | 0.4 | Viewport/container activation threshold: values in (0, 1] are treated as a fraction of container height; values > 1 or 0 are pixel offsets from the start edge. |
endThreshold | number | 0.995 | Normalized scroll progress (0..1) at or above which the final target becomes active even if shorter than 1 - probeOffset. |
scrollBehavior | 'smooth' | 'auto' | 'smooth' | Scroll behavior for link activation and scrollTo(). Navigation is instant when prefers-reduced-motion: reduce matches, even with CSS smooth scrolling. |
historyMode | 'replace' | 'push' | 'none' | 'replace' | How URL hash is updated on plain link activation (history.replaceState avoids stacking back-button entries). |
focusTarget | boolean | true | Moves focus (target.focus({ preventScroll: true })) to the resolved section element after activation. |
travelSettleMs | number | 180 | Milliseconds after the last scroll frame before data-travel clears. |
GhostScrollSpyLink
| Prop | Type | Default | Contract |
|---|---|---|---|
target | string | required | Target section ID (normalized by stripping a leading # if passed). |
href | string | undefined | `#${target}` | Native anchor href. Defaults to fragment #<target> so the link works without JS. |
as | GhostLinkElement | 'a' | Passed through to GhostLink. |
disabled | boolean | false | Passed through to GhostLink; disabled items cannot activate and are skipped during active tracking (if not rendered or disabled). |
v-model contracts
modelValue/update:modelValue: owns the active section ID (string | undefined) viauseControllableState.- In uncontrolled mode, scroll measurement updates the internal active ID and emits
update:modelValueonly when the active ID actually changes (Object.isguard — never emits on every scroll frame). - In controlled mode,
update:modelValueis emitted when scroll measurement or activation resolves a different ID; the renderedaria-currentreflects the parent'smodelValueprop. Consecutive measurements of the same section emit once while the parent's selection stays the same. - Calling
scrollTo(id)scrolls to the target and updates/emits the active ID immediately (or lets scroll measurement confirm it; if controlledmodelValuedoes not update,aria-currentremains bound tomodelValue). - Navigation hold. Plain link activation and
scrollTo(id)hold the target while the programmatic scroll travels to it: measurement keeps writing progress and travel direction but does not propose the sections it passes. The hold ends on the container'sscrollend, after 200ms with no scroll event (for engines withoutscrollend, or a scroll that never starts), or on user scroll input (wheel,touchstart,keydown, orpointerdown). A measurement then resolves the section at the final position as usual.
Events, callbacks, slots, and exposed methods
- Events on
GhostScrollSpy:update:modelValue(id: string | undefined)— emitted when active target ID changes.activate({ id: string, element: HTMLElement | null, event: MouseEvent | KeyboardEvent })— emitted on plain activation of a link; cancelable (event.defaultPreventedbefore handling skips scroll/focus/history mutation, or emitted with{ id, preventDefault }).
- Scoped slot on
GhostScrollSpy(default): Exposes{ activeId, travelDirection, itemCount, scrollTo }(progress CSS custom properties live on the root element so reading slot props never forces per-frame re-renders). - Scoped slot on
GhostScrollSpyLink(default): Exposes{ active: boolean, target: string }. - Exposed on
GhostScrollSpytemplate ref (GhostScrollSpyExposed):readonly element: HTMLElement | nullreadonly activeId: string | undefinedscrollTo(targetId: string, options?: { behavior?: ScrollBehavior; focus?: boolean }): voidmeasure(): void— forces an immediate geometry re-read after consumer DOM changes.
State model
- Active target resolution (
resolveScrollSpyActiveIndex):- When the scroll container is not scrollable (
scrollHeight - viewportHeight <= 0), progress is0and the active index is0(first item). - When overall scroll progress
>= endThreshold(0.995), the last item (items.length - 1) is active so short trailing sections are always reachable. - Otherwise, the active item is the last item in registered order whose target element's start edge (
toprelative to the scroll container's viewport) is<= probeY(whereprobeY = viewportHeight * probeOffsetfor fractional offsets orprobeOffsetin pixels). - This guarantees deterministic, symmetric transitions in both scroll directions (downward and upward) and keeps exactly one item active (
aria-current="location") at a time.
- When the scroll container is not scrollable (
- Overall and segment progress:
- Overall progress (
--ghost-scroll-spy-progress):clamp((scrollTop) / (scrollHeight - viewportHeight), 0, 1),0when non-scrollable. - Inter-item segment progress (
--ghost-scroll-spy-section-progress): ForN >= 2items, maps scroll position between adjacent items' activation offsets (start_i = activationOffset(i),start_{i+1} = activationOffset(i+1)) onto[i / (N - 1), (i + 1) / (N - 1)], reachingi / (N - 1)at the exact scroll offset where itemibecomes active and1at the last item. MatchesresolveRailProgressinlanding-motion.ts.
- Overall progress (
- Travel direction (
data-travel):- Computed from
scrollTop - previousScrollTopignoring sub-pixel noise (abs(delta) < 0.5). - Restored initial scroll positions on mount do not trigger
data-travel. - While scrolling,
data-travel="down"ordata-travel="up"is set on the root element and removed aftertravelSettleMs(default180ms) of idle.
- Computed from
Loading, empty, disabled, read-only, and error states
- Empty (
0registered links): Root landmark still renders cleanly;measure()sets--ghost-scroll-spy-progress: 0,--ghost-scroll-spy-section-progress: 0, andactiveIdstaysundefinedwith no runtime errors. - Missing target element (
document.getElementById(target) === null): Silently skipped during scroll measurement (does not throw or crash SSR/hydration or partial renders). On click, if the target element is missing, the browser's native link behavior is preserved (does not callpreventDefault()). - Disabled link (
GhostScrollSpyLinkwithdisabled): Delegatesaria-disabled="true"andtabindex="-1"toGhostLink; never activates on click and does not steal focus. - Non-scrollable page: Progress stays
0, first item stays active,data-travelis absent.
Async behavior
Not directly async, though target sections may mount, resize, or load async content (images, collapsible panels, tabs). Tracking follows the container when a template ref resolves or the element is replaced. Container and activation threshold changes, window resize, link registration changes, navigation subtree changes such as keyed moves, insertion or removal of target sections in the scroll container, and ResizeObserver notifications schedule a coalesced requestAnimationFrame measurement.
Consumer data
- Consumers own the target section elements (
idattributes on<section>or heading anchors) and the list ofGhostScrollSpyLinkchildren. GhostScrollSpynever mutates consumer-owned arrays or data objects.- Link registration preserves DOM / render order across dynamic inserts, conditional
v-iftoggles, and reordering (using DOM order comparison viacompareDocumentPositionor ordered array reconciliation on mount/unmount). - Duplicate
targetvalues in the sameGhostScrollSpywarn in development (GHOST013dev warning). The first enabled link in DOM order owns the active state, and each enabled target contributes only one progress stop.
Accessibility contract
Semantics and relationships
- Root
GhostScrollSpyrenders<nav>(implicitnavigationlandmark) witharia-label(default"Page sections", overridden bylabel,aria-label, oraria-labelledby). GhostScrollSpyListrenders<ol>(ordered section sequence) with<li>items (GhostScrollSpyItem).GhostScrollSpyLinkrenders a native<a href="#<target>">viaGhostLink:- Active item carries
aria-current="location"(present only on the active link; omitted on inactive links). - Real
hrefensures screen-reader links lists, context menus ("Open in new tab"), and zero-JS navigation work natively.
- Active item carries
- Any decorative progress track, rail fill, or traveller icon inside the themed wrapper or consumer slot MUST carry
aria-hidden="true".
Keyboard interaction
- Standard Tab-per-link (proposed default, see Open Question #1):
Tab/Shift+Tabmoves sequentially through each enabledGhostScrollSpyLink.Enter(native anchor activation) triggers the same handler as a plain primary click: scrolls target into view (respectingprefers-reduced-motion) and moves focus to the target element.
- Alternative (roving focus, under review in Open Question #1):
- Single
Tabstop on the list withArrowUp/ArrowDown(vertical) orArrowLeft/ArrowRight(horizontal, RTL-aware) +Home/End.
- Single
Focus behavior
- When a link is activated (click or
Enter):- Target scrolls to the start of the scrollport, respecting the section's vertical scroll margin and the container's vertical scroll padding.
- Target receives focus via
target.focus({ preventScroll: true })(whenfocusTargetistrue), so the nextTabmoves to the first interactive control inside that section rather than continuing through the rest of the nav rail or jumping back to the top of the page. - See Open Question #5 on ensuring target focusability when a section lacks
tabindex="-1".
- Visible focus indicators (
:focus-visible) are styled onGhostScrollSpyLinkin@ghostvue/themesand must meet WCAG 2.2 Focus Appearance (2px+ ring,--ghost-focus-ring-color,forced-colors: activeHighlight).
Assistive technology expectations
- Screen readers announce
<nav aria-label="...">as a navigation landmark, an ordered list of N links, and the active link as"current location". - Passive scroll tracking MUST NOT trigger live-region announcements as the user scrolls past sections (to avoid spamming screen readers during normal reading).
- Only explicit link activation moves focus; passive scrolling never steals focus.
Rendering and customization
Headless @ghostvue/vue parts emit stable styling hooks (data-part, data-state, data-orientation, data-travel) without visual CSS:
GhostScrollSpy:class="ghost-scroll-spy",data-part="root",data-orientation="vertical" | "horizontal",data-travel="down" | "up"(absent when idle), plus inline CSS custom properties--ghost-scroll-spy-progressand--ghost-scroll-spy-section-progress.GhostScrollSpyList:class="ghost-scroll-spy-list",data-part="list".GhostScrollSpyItem:class="ghost-scroll-spy-item",data-part="item",data-state="active"(absent when inactive).GhostScrollSpyLink:class="ghost-scroll-spy-link",data-part="link",data-state="active"(absent when inactive),aria-current="location"(when active).
Themed @ghostvue/themes wraps all four parts with semantic --ghost-* token CSS (ghost-scroll-spy.css, layered in @layer ghostvue-theme with .ghost-theme / .ghost-themed-scope / [data-themed]), supporting:
- A subtle track line and
--ghost-scroll-spy-section-progressfill bar via CSS transforms (scaleY/scaleX) with zero layout thrashing. - Clear active, hover, focus-visible, and
forced-colors: activestates. - Full
@media (prefers-reduced-motion: reduce)handling (no smooth scroll, no transitions).
Consumers needing custom visuals (like the landing page's travelling ghost SVG and numbered floating pills) can either style the headless GhostScrollSpy hooks directly or use the scoped slot props ({ activeId, travelDirection }) + --ghost-scroll-spy-section-progress CSS variable.
Environment behavior
SSR and hydration
- No
window,document,ResizeObserver, ormatchMediaaccess duringsetup()or SSR render. - All scroll listeners,
ResizeObserver, andmatchMedia('(prefers-reduced-motion: reduce)')attach inonMountedand clean up inonBeforeUnmount(canceling any pendingrequestAnimationFrameandtravelSettleMstimer). - On SSR,
--ghost-scroll-spy-progressand--ghost-scroll-spy-section-progressrender as'0'(or are omitted until mount, matchinglanding-rail.cssvar(..., 0)fallback) anddata-travelis absent so initial hydration matches with zero Vue warnings. - See Open Question #4 for initial SSR
aria-currentownership.
Mobile and touch
- Works with native momentum touch scrolling because listeners are
{ passive: true }and read-only. - Themed recipe meets 24x24px minimum target sizing (ideally 32–44px block hit target) and allows consumers to hide/collapse the rail on narrow viewports via media queries without horizontal overflow (as
landing-rail.cssdoes below1100px).
Performance
- Expected scale: 2–50 sections per page (typical docs/landing/settings TOC).
- Scroll handler coalesces work to at most one
requestAnimationFrameper frame (if (frame !== 0) return). - Inside
measure(), all DOM reads (scrollY,innerHeight,scrollHeight,getBoundingClientRect().top) are batched before the single DOM write (root.style.setProperty(...)) to prevent read/write layout thrashing. - Progress values are written directly to element CSS custom properties rather than reactive Vue refs so scrolling does not trigger component tree re-renders; only discrete
activeIdtransitions trigger a reactive update.
Composition
GhostLink/useGhostLink: Reused byGhostScrollSpyLinkfor native anchor semantics,aspolymorphism,disabledhandling, andfocus()/blur().useControllableState: Reused formodelValue/defaultValueactive section ownership.useGhostId: Reused if needed for fallback accessible-label or item IDs.resolveDir/useRovingFocus: Available for reuse if Open Question #1 selects roving focus or opt-in roving mode.- No external dependencies: Pure DOM /
ResizeObserver/matchMediaonly.
Test plan
- Framework-neutral unit tests (
packages/vue/src/):resolveScrollSpyActiveIndex: top of page, probe crossing in both directions, short trailing section clamped atendThreshold, non-scrollable container, empty targets.resolveScrollSpyProgressandresolveScrollSpySegmentProgress: clamping at0and1, exact marker alignment at activation offset, monotonicity.resolveScrollSpyTravelDirection:down,up, sub-pixel jitter< 0.5ignored.
- Vue component & composable tests (
packages/vue/src/):- Controlled (
modelValue+update:modelValue) and uncontrolled (defaultValue) state, including controlled veto on scroll/click. - Dynamic target insertion, removal, and DOM reordering updates tracking order.
- Cleanup on unmount (listeners,
rAF, timers,ResizeObserverdisconnected). - Plain click vs modified click (
Ctrl/Cmd/Shift/Alt/middle click). activateevent cancellation.- Navigation hold: no intermediate section becomes active during a programmatic scroll in either direction; user scroll input,
scrollend, and scroll idle each release it. expectSsrHydrationverifying zero warnings and deterministic SSR HTML.
- Controlled (
- Playwright E2E + axe (
tests/e2e/scroll-spy.spec.ts+tests/e2e/docs-landing.spec.ts):- Active tracking (
aria-current="location") while scrolling in both directions, including short final section. - Click and keyboard (
Enter) activation scrolls target into view and asserts real focus (toBeFocused()) on the target section and subsequentTabinside the section. prefers-reduced-motion: reducescrolls immediately without smooth motion.- Works without JS enabled (real
#targetlinks navigate natively). - Axe scan on headless and themed examples in light/dark modes.
- Visual baseline for themed example (
pnpm test:visual:docker). - Full
tests/e2e/docs-landing.spec.tsregression pass after migratingLandingSectionRail.vueandlanding-motion.ts.
- Active tracking (
- Compile-time type tests (
packages/vue/type-tests/):- Positive and negative fixtures for
GhostScrollSpy*props, scoped slots, exposedscrollTo, anduseGhostScrollSpy.
- Positive and negative fixtures for
Documentation plan
After spec approval and implementation:
docs/components/scroll-spy.mdwith<GhostExample />demos underexamples/scroll-spy/:basic— headless landmark navigation with--ghost-scroll-spy-section-progressthemed— themed@ghostvue/themesvertical rail/TOCcomposable—useGhostScrollSpycustom layout
packages/vue/manifests/ghost-scroll-spy*.manifest.jsonandpackages/themes/manifests/ghost-scroll-spy.manifest.jsonviapnpm manifests:write.- Generated API tables via
pnpm docs:api:write. - Playground section under
apps/playground/,docs/roadmap.mdrow update, and migration ofapps/docs/.vitepress/theme/LandingSectionRail.vue+landing-motion.ts.
Compatibility and release impact
- Purely additive minor release via Changesets for
@ghostvue/vueand@ghostvue/themes. - Migrating
LandingSectionRail.vueontoGhostScrollSpyis internal toapps/docsand preserves all existing test IDs, styles, and E2E behavior.
Open architectural questions
Decisions below require Zac's sign-off before writing production markup or exports:
Tab-per-link vs roving focus (
useRovingFocus).- Option A (Recommended): Standard Tab-per-link inside
<nav><ol><li><a>. Matches WAI-ARIA landmark navigation expectations, works identically with and without JS, and preserves the existing keyboard contract verified intests/e2e/docs-landing.spec.ts(Tab/Shift+Tabbetween links). - Option B: Roving
tabindex(useRovingFocus) with a single Tab stop andArrowUp/ArrowDownnavigation. - Option C: Tab-per-link by default with an opt-in
rovingFocus?: booleanprop.
- Option A (Recommended): Standard Tab-per-link inside
RTL behavior.
- Option A (Recommended): Use CSS logical properties (
inset-inline-*,padding-inline-*) in the themed recipe so rails flip sides cleanly indir="rtl", and keep v1 scroll tracking vertical (scrollTop/top), while honoringdirif horizontal arrow navigation is ever enabled. - Option B: Also support
orientation="horizontal"horizontal scroll containers (scrollLeft) with cross-browser RTLscrollLeftsign normalization in v1.
- Option A (Recommended): Use CSS logical properties (
Nested scroll containers vs viewport (
window) only.- Option A (Recommended): Support an optional
containerprop/option (MaybeRefOrGetter<HTMLElement | Window | null | undefined>, defaulting towindow). Whencontaineris anHTMLElement, measure bounds relative tocontainer.getBoundingClientRect().topand scroll the container directly viacontainer.scrollTo(...)rather thanelement.scrollIntoView(...)so outer page scroll does not jump unexpectedly. - Option B: Viewport (
window) only in v1; defer nested containers.
- Option A (Recommended): Support an optional
SSR output before client measurement.
- Option A (Recommended): Render
aria-current="location"onmodelValueif controlled, elsedefaultValueif provided, else the first registered enabled item once registered (matchingLandingSectionRail.vueSSR output), and reconcile to actual scroll position inonMountedafter hydration. Note: for compound children withoutdefaultValue,GhostScrollSpyLinksetup order must not mutate parent state after the first link renders; eitherGhostScrollSpyLinkreads a deterministic registration index synchronously in setup (firstTargetId) ordefaultValueis encouraged for SSR rails. - Option B: Render no
aria-currentduring SSR unlessmodelValueordefaultValueis explicitly passed, and applyaria-current="location"afteronMountedmeasurement.
- Option A (Recommended): Render
Target focusability on activation.
- Option A (Recommended): If the resolved target element is not naturally focusable and has no
tabindexattribute (target.tabIndex < 0 && !target.hasAttribute('tabindex')), settabindex="-1"right beforetarget.focus({ preventScroll: true })(matching standard skip-link handling so consumers who forgettabindex="-1"still get working keyboard flow). - Option B: Never write
tabindexonto consumer section elements; require consumers to puttabindex="-1"on target sections (asGhostLanding.vuealready does) and warn in dev whentarget.focus()leavesdocument.activeElementunchanged.
- Option A (Recommended): If the resolved target element is not naturally focusable and has no