import * as stylex from "@stylexjs/stylex";
import {
createContext,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import type { CSSProperties } from "react";
import { mergeProps, renderElement, type PartProps } from "@ui-sdk/react/primitive";
import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";
import {
defineSlotRecipe,
variantDataAttrs,
type WithStyleOverrides,
} from "#lib/recipe-props.ts";
import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'
import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'
import { easings } from '@stylexblocks/ui/tokens/easings.stylex.ts'
import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'
import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'
import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'
import { radii } from '@stylexblocks/ui/tokens/radii.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'
// Table of contents: a scroll-spy link list in the docs-sidebar idiom. The
// root carries `--top` / `--left` / `--width` / `--height` (the active items'
// box, relative to the list) which the indicator reads to glide between
// entries. Items carry `--depth` (the heading level, 2 for h2) and links
// indent by `--depth - 2` steps, so h2 sits flush.
const tocRoot = stylex.create({
base: {
display: 'flex',
flexDirection: 'column',
gap: spacing._2,
minWidth: 0,
},
})
const tocTitle = stylex.create({
base: {
margin: 0,
color: semanticColors.fg,
fontSize: fontSizes.sm,
lineHeight: lineHeights.sm,
fontWeight: fontWeights.semibold,
},
})
const tocList = stylex.create({
base: {
position: 'relative',
isolation: 'isolate',
display: 'flex',
flexDirection: 'column',
listStyleType: 'none',
margin: 0,
padding: 0,
},
})
const tocListVariants = stylex.create({
line: {
borderInlineStartWidth: '1px',
borderInlineStartStyle: 'solid',
borderInlineStartColor: semanticColors.border,
},
subtle: {},
})
const tocItem = stylex.create({
base: {
position: 'relative',
minWidth: 0,
},
})
const tocLink = stylex.create({
base: {
position: 'relative',
zIndex: 1,
display: 'block',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
textDecorationLine: 'none',
fontWeight: fontWeights.medium,
'--toc-indent': 'calc(max(var(--depth, 2) - 2, 0) * var(--toc-indent-size))',
paddingInlineStart: 'calc(var(--toc-padding-inline) + var(--toc-indent))',
paddingInlineEnd: 'var(--toc-padding-inline)',
paddingBlock: 'var(--toc-padding-block)',
color: {
default: semanticColors.fgMuted,
':hover': semanticColors.fg,
':is([data-active], [aria-current="location"])': colorPalette.fg,
},
transitionProperty: 'color, background-color',
transitionDuration: durations.fast,
outlineWidth: {
default: null,
':focus-visible': '2px',
},
outlineOffset: {
default: null,
':focus-visible': '-2px',
},
outlineStyle: {
default: null,
':focus-visible': 'solid',
},
outlineColor: {
default: null,
':focus-visible': colorPalette.focusRing,
},
},
})
const tocLinkVariants = stylex.create({
line: {
borderRadius: 0,
},
subtle: {
borderRadius: radii.md,
backgroundColor: {
default: 'transparent',
':hover': semanticColors.interactionHover,
':is([data-active], [aria-current="location"])': 'transparent',
},
},
})
const tocLinkSizes = stylex.create({
sm: {
fontSize: fontSizes.xs,
lineHeight: lineHeights.xs,
'--toc-padding-inline': spacing._2_5,
'--toc-padding-block': spacing._1,
'--toc-indent-size': spacing._3,
},
md: {
fontSize: '0.8125rem',
lineHeight: lineHeights.sm,
'--toc-padding-inline': spacing._3,
'--toc-padding-block': spacing._1_5,
'--toc-indent-size': spacing._3,
},
})
const tocIndicator = stylex.create({
base: {
position: 'absolute',
zIndex: 0,
pointerEvents: 'none',
top: 'var(--top)',
height: 'var(--height)',
transitionProperty: 'top, height, left, width',
transitionDuration: durations.moderate,
transitionTimingFunction: easings.standard,
},
})
const tocIndicatorVariants = stylex.create({
// A bar riding the list's inline-start rail (over its 1px border).
line: {
insetInlineStart: '-1px',
width: '2px',
borderRadius: radii.full,
backgroundColor: colorPalette.solid,
},
// A pill behind the active link(s).
subtle: {
left: 'var(--left)',
width: 'var(--width)',
borderRadius: radii.md,
backgroundColor: colorPalette.muted,
},
})
export type TocVariant = keyof typeof tocIndicatorVariants
export type TocSize = keyof typeof tocLinkSizes
const tocRecipe = defineSlotRecipe({
slots: {
root: { styles: tocRoot },
title: { styles: tocTitle },
list: { styles: tocList, variants: tocListVariants },
item: { styles: tocItem },
link: { styles: tocLink, variants: tocLinkVariants, sizes: tocLinkSizes },
indicator: { styles: tocIndicator, variants: tocIndicatorVariants },
},
defaultVariants: { variant: "line", size: "md" },
});
const tocStatic = stylex.create({
nav: { display: "flex", flexDirection: "column", gap: "inherit", minWidth: 0 },
});
const { withProvider, withContext, VariantContext } =
createSlotRecipeContext(tocRecipe);
export interface TocItemData {
/** The id of the heading element in the document. */
value: string;
/** The heading level (2 for h2, 3 for h3); drives indentation. */
depth: number;
}
interface IndicatorRect {
x: number;
y: number;
width: number;
height: number;
}
// UI SDK has no table-of-contents primitive; the Root runs the scroll spy
// (an IntersectionObserver over the headings, scoped to `scrollEl`), owns the
// active ids, and measures the active items into CSS variables the
// indicator reads. Parts read it through context.
interface TocState {
ids: { nav: string; title: string };
activeIds: string[];
scrollTo: (value: string) => void;
registerItem: (value: string, el: HTMLElement | null) => void;
listRef: React.RefObject<HTMLElement | null>;
hasIndicator: boolean;
setHasIndicator: (value: boolean) => void;
rect: IndicatorRect | null;
}
const TocContext = createContext<TocState | null>(null);
function useToc() {
const ctx = useContext(TocContext);
if (!ctx) throw new Error("Toc parts must be rendered inside <Toc.Root>");
return ctx;
}
const ItemContext = createContext<TocItemData | null>(null);
const px = (n: number | undefined) => (n == null ? undefined : `${n}px`);
export type TocRootProps = WithStyleOverrides<PartProps<"div">> & {
variant?: "line" | "subtle";
size?: "sm" | "md";
/** The entries, in document order. */
items: TocItemData[];
/** Returns the scroll container the headings live in. Defaults to the viewport. */
scrollEl?: () => HTMLElement | null;
/** IntersectionObserver root margin: the band that counts as "visible". */
rootMargin?: string;
/** IntersectionObserver threshold. */
threshold?: number | number[];
/** Every visible heading is active (`true`), or only the topmost (`false`). */
multiple?: boolean;
/** Scroll behavior when a link is clicked. */
scrollBehavior?: ScrollBehavior;
/** Controlled active heading ids. */
activeIds?: string[];
/** Initial active heading ids when uncontrolled. */
defaultActiveIds?: string[];
onActiveChange?: (details: { activeIds: string[]; activeItems: TocItemData[] }) => void;
};
const sameIds = (a: string[], b: string[]) =>
a.length === b.length && a.every((id, i) => id === b[i]);
function RootNode({
render,
style,
items,
scrollEl,
rootMargin = "-20px 0px -40% 0px",
threshold = 0,
multiple = true,
scrollBehavior = "smooth",
activeIds: activeIdsProp,
defaultActiveIds,
onActiveChange,
...rest
}: Omit<TocRootProps, "variant" | "size" | "palette" | "style"> & {
style?: CSSProperties;
}) {
const v = useContext(VariantContext);
const id = useId();
const [innerActive, setInnerActive] = useState<string[]>(defaultActiveIds ?? []);
const activeIds = activeIdsProp ?? innerActive;
const [rect, setRect] = useState<IndicatorRect | null>(null);
const [hasIndicator, setHasIndicator] = useState(false);
const itemEls = useRef(new Map<string, HTMLElement>());
const listRef = useRef<HTMLElement | null>(null);
// While a link click scrolls, the clicked entry stays active instead of
// flickering through every heading the scroll passes.
const navigating = useRef(false);
const releaseTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const syncRef = useRef<() => void>(() => {});
// (Re)arms the lock release; scroll events keep pushing it back until the
// scroll settles.
const releaseSoon = useCallback(() => {
clearTimeout(releaseTimer.current);
releaseTimer.current = setTimeout(() => {
navigating.current = false;
syncRef.current();
}, 150);
}, []);
const latest = useRef({ activeIds, items, onActiveChange, scrollEl, multiple });
latest.current = { activeIds, items, onActiveChange, scrollEl, multiple };
const setActive = useCallback((next: string[]) => {
const { activeIds: prev, items: all, onActiveChange: notify } = latest.current;
if (sameIds(prev, next)) return;
setInnerActive(next);
notify?.({
activeIds: next,
activeItems: all.filter((item) => next.includes(item.value)),
});
}, []);
// Scroll spy: observe every heading, keep a visibility map, derive the
// active ids. With nothing in the band, the last heading above it wins
// (the section being read).
const itemsKey = items.map((item) => item.value).join("\n");
useEffect(() => {
const doc = document;
const headings = latest.current.items
.map((item) => ({ value: item.value, el: doc.getElementById(item.value) }))
.filter((h): h is { value: string; el: HTMLElement } => h.el !== null);
if (headings.length === 0) return;
const root = latest.current.scrollEl?.() ?? null;
const visible = new Map<string, boolean>();
let bandTop = 0;
const sync = () => {
if (navigating.current) return;
const ids = headings.filter((h) => visible.get(h.value)).map((h) => h.value);
let next = latest.current.multiple ? ids : ids.slice(0, 1);
if (next.length === 0) {
const passed = headings.filter((h) => h.el.getBoundingClientRect().top <= bandTop);
const current = passed[passed.length - 1] ?? headings[0];
next = current ? [current.value] : [];
}
setActive(next);
};
syncRef.current = sync;
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) visible.set(entry.target.id, entry.isIntersecting);
bandTop =
entries[0]?.rootBounds?.top ?? (root ? root.getBoundingClientRect().top : 0);
sync();
},
{ root, rootMargin, threshold },
);
for (const heading of headings) observer.observe(heading.el);
// Release the click lock once the scroll settles.
const target: HTMLElement | Window = root ?? window;
const onScroll = () => {
if (navigating.current) releaseSoon();
};
target.addEventListener("scroll", onScroll, { passive: true });
return () => {
observer.disconnect();
target.removeEventListener("scroll", onScroll);
clearTimeout(releaseTimer.current);
syncRef.current = () => {};
};
}, [itemsKey, rootMargin, threshold, multiple, setActive, releaseSoon]);
// Measure the active items' box relative to the list for the indicator.
const activeKey = activeIds.join("\n");
useLayoutEffect(() => {
if (!hasIndicator) return;
const list = listRef.current;
const measure = () => {
const ids = latest.current.activeIds;
const first = itemEls.current.get(ids[0] ?? "");
const last = itemEls.current.get(ids[ids.length - 1] ?? "") ?? first;
if (!first || !last || !list) {
setRect(null);
return;
}
const listBox = list.getBoundingClientRect();
const originX = listBox.left - list.scrollLeft;
const originY = listBox.top - list.scrollTop;
const a = first.getBoundingClientRect();
const b = last.getBoundingClientRect();
const next = { x: a.left - originX, y: a.top - originY, width: a.width, height: b.bottom - a.top };
setRect((prev) =>
prev &&
prev.x === next.x &&
prev.y === next.y &&
prev.width === next.width &&
prev.height === next.height
? prev
: next,
);
};
measure();
const observer = new ResizeObserver(measure);
for (const id of latest.current.activeIds) {
const el = itemEls.current.get(id);
if (el) observer.observe(el);
}
return () => observer.disconnect();
}, [activeKey, hasIndicator]);
const scrollTo = useCallback(
(value: string) => {
const heading = document.getElementById(value);
if (!heading) return;
navigating.current = true;
setActive([value]);
const container = latest.current.scrollEl?.();
if (container) {
const top =
heading.getBoundingClientRect().top -
container.getBoundingClientRect().top +
container.scrollTop;
container.scrollTo({ top, behavior: scrollBehavior });
} else {
heading.scrollIntoView({ behavior: scrollBehavior, block: "start" });
}
// Armed now too, in case no scroll happens (already in place).
releaseSoon();
},
[scrollBehavior, setActive, releaseSoon],
);
const registerItem = useCallback((value: string, el: HTMLElement | null) => {
if (el) itemEls.current.set(value, el);
else itemEls.current.delete(value);
}, []);
const state = useMemo<TocState>(
() => ({
ids: { nav: `${id}-nav`, title: `${id}-title` },
activeIds,
scrollTo,
registerItem,
listRef,
hasIndicator,
setHasIndicator,
rect,
}),
[id, activeIds, scrollTo, registerItem, hasIndicator, rect],
);
const element = renderElement(
"div",
mergeProps(
{
...variantDataAttrs(v),
style: {
...style,
"--top": px(rect?.y),
"--left": px(rect?.x),
"--width": px(rect?.width),
"--height": px(rect?.height),
} as CSSProperties,
},
rest,
),
render,
v,
);
return <TocContext.Provider value={state}>{element}</TocContext.Provider>;
}
function NavNode(allProps: PartProps<"nav">) {
const { render, ...rest } = allProps;
const toc = useToc();
return renderElement(
"nav",
mergeProps({ id: toc.ids.nav, "aria-labelledby": toc.ids.title }, rest),
render,
);
}
function TitleNode(allProps: PartProps<"h2">) {
const { render, ...rest } = allProps;
const toc = useToc();
return renderElement("h2", mergeProps({ id: toc.ids.title }, rest), render);
}
function ListNode(allProps: PartProps<"ul">) {
const { render, ...rest } = allProps;
const toc = useToc();
return renderElement(
"ul",
mergeProps({ ref: toc.listRef as React.Ref<HTMLUListElement> }, rest),
render,
);
}
export type TocItemProps = WithStyleOverrides<PartProps<"li">> & {
item: TocItemData;
};
function ItemNode({
render,
item,
style,
...rest
}: Omit<TocItemProps, "palette" | "style"> & { style?: CSSProperties }) {
const toc = useToc();
const active = toc.activeIds.includes(item.value);
const { registerItem } = toc;
const ref = useCallback(
(el: HTMLLIElement | null) => registerItem(item.value, el),
[registerItem, item.value],
);
const element = renderElement(
"li",
mergeProps(
{
ref,
"data-value": item.value,
"data-depth": String(item.depth),
"data-active": active ? "" : undefined,
"data-first": active && toc.activeIds[0] === item.value ? "" : undefined,
"data-last":
active && toc.activeIds[toc.activeIds.length - 1] === item.value
? ""
: undefined,
style: { ...style, "--depth": item.depth } as CSSProperties,
},
rest,
),
render,
);
return <ItemContext.Provider value={item}>{element}</ItemContext.Provider>;
}
function LinkNode(allProps: PartProps<"a">) {
const { render, ...rest } = allProps;
const toc = useToc();
const item = useContext(ItemContext);
const active = item ? toc.activeIds.includes(item.value) : false;
return renderElement(
"a",
mergeProps(
{
href: item ? `#${item.value}` : undefined,
"data-value": item?.value,
"data-active": active ? "" : undefined,
"aria-current": active ? ("location" as const) : undefined,
onClick: (event: React.MouseEvent<HTMLAnchorElement>) => {
if (!item || event.defaultPrevented) return;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
if (event.button !== 0) return;
if (!document.getElementById(item.value)) return;
event.preventDefault();
toc.scrollTo(item.value);
history.pushState(null, "", `#${item.value}`);
},
},
rest,
),
render,
);
}
function IndicatorNode(allProps: PartProps<"div">) {
const { render, ...rest } = allProps;
const toc = useToc();
const { setHasIndicator } = toc;
useEffect(() => {
setHasIndicator(true);
return () => setHasIndicator(false);
}, [setHasIndicator]);
return renderElement(
"div",
mergeProps(
{
"aria-hidden": true,
hidden: !toc.rect || (toc.rect.width === 0 && toc.rect.height === 0),
},
rest,
),
render,
);
}
/**
* Toc — the `toc` recipe composed through UI SDK's `renderElement` /
* `mergeProps` primitives with a hand-built scroll spy (UI SDK has no
* table-of-contents primitive). `<Toc.Root items
* scrollEl variant size>` resolves the recipe once and every part inherits it
* through context. The Root observes the headings whose ids match
* `items[].value` with an IntersectionObserver (inside `scrollEl`, or the
* viewport), marks visible ones active (`data-active`,
* `aria-current="location"` on the link), and measures their box into
* `--top` / `--left` / `--width` / `--height`, which `Toc.Indicator` (placed
* inside `Toc.List`) reads to glide between entries. `multiple={false}` keeps
* one active entry. Composition per part via `render`.
*/
export const Toc = {
Root: withProvider(RootNode, "root", "TocRoot"),
Nav: withContext(NavNode, () => [tocStatic.nav], "TocNav"),
Title: withContext(TitleNode, "title", "TocTitle"),
List: withContext(ListNode, "list", "TocList"),
Item: withContext(ItemNode, "item", "TocItem"),
Link: withContext(LinkNode, "link", "TocLink"),
Indicator: withContext(IndicatorNode, "indicator", "TocIndicator"),
Content: withContext("article", () => [], "TocContent"),
};