fumadocs-core
Version:
The React.js library for building a documentation website
234 lines (233 loc) • 6.97 kB
JavaScript
"use client";
import { t as isEqualShallow } from "./is-equal-BuZW92e4.js";
import { createContext, use, useEffect, useEffectEvent, useMemo, useRef, useSyncExternalStore } from "react";
import { jsx } from "react/jsx-runtime";
import scrollIntoView from "scroll-into-view-if-needed";
// src/utils/merge-refs.ts
function mergeRefs(...refs) {
return (value) => {
refs.forEach((ref) => {
if (typeof ref === "function") ref(value);
else if (ref != null) ref.current = value;
});
};
}
// src/toc.tsx
const ObserverContext = createContext(null);
const ScrollContext = createContext(null);
/** Optional: add auto-scroll to TOC items. */
function ScrollProvider({ containerRef, children }) {
return /* @__PURE__ */ jsx(ScrollContext, {
value: containerRef,
children
});
}
function AnchorProvider({ toc, single = false, children }) {
const observer = useMemo(() => new Observer(toc, single), [toc, single]);
useEffect(() => {
observer.watch();
return () => observer.unwatch();
}, [observer]);
return /* @__PURE__ */ jsx(ObserverContext, {
value: observer,
children
});
}
function TOCItem({ ref, onActiveChange, onClick, autoScroll = true, ...props }) {
const id = props.href ? getItemId(props.href) : null;
const containerRef = use(ScrollContext);
const anchorRef = useRef(null);
const isMountedRef = useRef(false);
const observer = useObserver();
const active = useObserverValue((observer) => id !== null && observer.activeAnchors.includes(id));
const prevActiveRef = useRef(active);
if (prevActiveRef.current !== active) {
prevActiveRef.current = active;
onActiveChange?.(active);
}
useEffect(() => {
if (id === null) return;
const callback = () => {
const anchor = anchorRef.current;
const container = containerRef?.current;
if (autoScroll && observer.activeAnchor === id && anchor && container) scrollIntoView(anchor, {
behavior: isMountedRef.current ? "smooth" : "instant",
block: "center",
inline: "center",
scrollMode: "always",
boundary: container
});
};
callback();
isMountedRef.current = true;
return observer.subscribe(callback);
}, [
autoScroll,
id,
observer,
containerRef
]);
return /* @__PURE__ */ jsx("a", {
ref: mergeRefs(anchorRef, ref),
"data-active": String(active),
onClick: (e) => {
onClick?.(e);
if (id !== null && !e.defaultPrevented) observer.select(id);
},
...props
});
}
function useObserver() {
const observer = use(ObserverContext);
if (!observer) throw new Error(`Component must be used under the <AnchorProvider /> component.`);
return observer;
}
/** subscribe to a value of the observer, it must be stable between updates */
function useObserverValue(get) {
const observer = useObserver();
const getSnapshot = () => get(observer);
return useSyncExternalStore(observer.subscribe, getSnapshot, getSnapshot);
}
/** @returns static info object, useful for custom rendering logic */
function useTOC() {
const observer = useObserver();
return useMemo(() => ({
get() {
return observer.items;
},
listen: observer.listen.bind(observer),
unlisten: observer.unlisten.bind(observer)
}), [observer]);
}
function useTOCListener(listener) {
const observer = useObserver();
const callback = useEffectEvent(listener);
useEffect(() => observer.subscribe(callback), [observer]);
}
function useTOCSelector(select, isEqual = isEqualShallow) {
const cache = useRef(null);
return useObserverValue(({ items }) => {
const prev = cache.current;
if (prev && prev.items === items && prev.select === select) return prev.value;
const next = select(items);
const value = prev && isEqual(prev.value, next) ? prev.value : next;
cache.current = {
items,
select,
value
};
return value;
});
}
/**
* The current heading ID
*/
function useActiveAnchor() {
return useObserverValue((observer) => observer.activeAnchor);
}
/**
* The id of visible anchors
*/
function useActiveAnchors() {
return useObserverValue((observer) => observer.activeAnchors);
}
function useItems() {
return useObserverValue((observer) => observer.items);
}
function getItemId(url) {
if (url.startsWith("#")) return url.slice(1);
return null;
}
/** a heading is in view when this ratio of it is visible */
const VISIBLE_RATIO = .9;
var Observer = class {
constructor(toc, single) {
this.single = single;
this.activeAnchors = [];
this.observer = null;
this.visible = /* @__PURE__ */ new Set();
this.listeners = /* @__PURE__ */ new Set();
this.subscribe = (listener) => {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
};
this.items = [];
for (const item of toc) {
const id = getItemId(item.url);
if (id) this.items.push({
id,
active: false,
fallback: false,
t: 0,
original: item
});
}
}
listen(listener) {
this.listeners.add(listener);
}
unlisten(listener) {
this.listeners.delete(listener);
}
select(id) {
this.activeAnchor = id;
this.update();
}
watch() {
if (this.observer) return;
this.observer = new IntersectionObserver(this.callback.bind(this), { threshold: VISIBLE_RATIO });
for (const item of this.items) {
const element = document.getElementById(item.id);
if (!element) continue;
this.observer.observe(element);
}
}
unwatch() {
this.observer?.disconnect();
this.observer = null;
this.visible.clear();
}
callback(entries) {
for (const entry of entries) if (entry.intersectionRatio >= VISIBLE_RATIO) this.visible.add(entry.target.id);
else this.visible.delete(entry.target.id);
if (this.activeAnchor === void 0 || !this.visible.has(this.activeAnchor)) this.activeAnchor = this.items.find((item) => this.visible.has(item.id))?.id ?? this.findAbove(entries[0].rootBounds);
this.update();
}
/**
* Measure the last heading above the view, when no heading is in view.
*
* Headings can pass the view without intersecting it, so this cannot be tracked from entries.
*/
findAbove(root) {
if (!root) return;
const center = (root.top + root.bottom) / 2;
let id;
for (const item of this.items) {
const rect = document.getElementById(item.id)?.getBoundingClientRect();
if (!rect || rect.height === 0) continue;
if (rect.top >= center) break;
id = item.id;
}
return id;
}
update() {
const activeAnchors = [];
const t = Date.now();
this.items = this.items.map((item) => {
const active = this.single || this.visible.size === 0 ? item.id === this.activeAnchor : this.visible.has(item.id);
const fallback = active && !this.visible.has(item.id);
if (active) activeAnchors.push(item.id);
return item.active === active && item.fallback === fallback ? item : {
...item,
active,
fallback,
t
};
});
this.activeAnchors = activeAnchors;
for (const listener of this.listeners) listener(this.items);
}
};
export { AnchorProvider, ScrollProvider, TOCItem, useActiveAnchor, useActiveAnchors, useItems, useTOC, useTOCListener, useTOCSelector };