@lobehub/ui 6.14.0 → 6.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -41,7 +41,7 @@ declare const styleArrays: {
41
41
  }> | Readonly<{
42
42
  readonly backgroundColor: stylex.StyleXClassNameFor<"backgroundColor", "transparent">;
43
43
  readonly cursor: stylex.StyleXClassNameFor<"cursor", "default">;
44
- readonly display: stylex.StyleXClassNameFor<"display", "flex" | "none">;
44
+ readonly display: stylex.StyleXClassNameFor<"display", "none" | "flex">;
45
45
  }>)[];
46
46
  item: Readonly<{
47
47
  readonly borderRadius: stylex.StyleXClassNameFor<"borderRadius", string>;
@@ -0,0 +1,7 @@
1
+ import { TocProps } from "./type.mjs";
2
+ declare const Toc: {
3
+ ({ activeKey, className, getContainer, items, offset, onChange, onClick, style, ...rest }: TocProps): import("react").JSX.Element | null;
4
+ displayName: string;
5
+ };
6
+ export { Toc as default };
7
+ //# sourceMappingURL=Toc.d.mts.map
package/es/Toc/Toc.mjs ADDED
@@ -0,0 +1,201 @@
1
+ "use client";
2
+ import toc_default from "../i18n/resources/en/toc.mjs";
3
+ import { useTranslation } from "../i18n/useTranslation.mjs";
4
+ import { styleProps } from "../styles/stylex/props.mjs";
5
+ import { tocClasses } from "./stable.mjs";
6
+ import { styles } from "./style.mjs";
7
+ import { buildTocPath } from "./tocPath.mjs";
8
+ import { toFlatTocItems } from "./toFlatTocItems.mjs";
9
+ import clsx$1 from "clsx";
10
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
11
+ import { jsx, jsxs } from "react/jsx-runtime";
12
+ // src/Toc/Toc.tsx
13
+ const EMPTY_PATH = {
14
+ d: "",
15
+ length: 0,
16
+ ranges: []
17
+ };
18
+ const DEFAULT_OFFSET = 96;
19
+ const SCROLL_LOCK_FALLBACK_MS = 1e3;
20
+ const isWindow = (container) => container === window;
21
+ const getRelativeTop = (element, container) => element.getBoundingClientRect().top - (isWindow(container) ? 0 : container.getBoundingClientRect().top);
22
+ const getScrollTop = (container) => isWindow(container) ? window.scrollY : container.scrollTop;
23
+ const hrefToId = (href) => {
24
+ const hash = href.includes("#") ? href.split("#").at(-1) : href.replace(/^#/, "");
25
+ if (!hash) return "";
26
+ try {
27
+ return decodeURIComponent(hash);
28
+ } catch {
29
+ return hash;
30
+ }
31
+ };
32
+ const getTarget = (href) => {
33
+ const id = hrefToId(href);
34
+ if (!id) return null;
35
+ return document.getElementById(id);
36
+ };
37
+ const findParentId = (items, activeId) => {
38
+ const index = items.findIndex((item) => item.id === activeId);
39
+ if (index < 0 || items[index].level !== 3) return void 0;
40
+ for (let cursor = index - 1; cursor >= 0; cursor -= 1) if (items[cursor].level === 2) return items[cursor].id;
41
+ };
42
+ const getActiveId = (items, container, offset) => {
43
+ let activeId;
44
+ let activeTop = -Infinity;
45
+ for (const item of items) {
46
+ const target = getTarget(item.href);
47
+ if (!target) continue;
48
+ const top = getRelativeTop(target, container);
49
+ if (top <= offset + 1 && top >= activeTop) {
50
+ activeId = item.id;
51
+ activeTop = top;
52
+ }
53
+ }
54
+ return activeId ?? items[0]?.id;
55
+ };
56
+ const Toc = ({ activeKey, className, getContainer, items = [], offset = DEFAULT_OFFSET, onChange, onClick, style, ...rest }) => {
57
+ const { t } = useTranslation(toc_default);
58
+ const flatItems = useMemo(() => toFlatTocItems(items), [items]);
59
+ const listRef = useRef(null);
60
+ const scrollLockRef = useRef(false);
61
+ const lockTimerRef = useRef(void 0);
62
+ const [path, setPath] = useState(EMPTY_PATH);
63
+ const [spyActiveId, setSpyActiveId] = useState(void 0);
64
+ const resolveContainer = useCallback(() => {
65
+ const container = getContainer?.();
66
+ if (!container || container === window || container === document.body || container === document.documentElement) return window;
67
+ return container;
68
+ }, [getContainer]);
69
+ const activeId = (activeKey != null && activeKey !== "" ? hrefToId(String(activeKey)) || flatItems.find((item) => item.key === activeKey)?.id : void 0) ?? (spyActiveId && flatItems.some((item) => item.id === spyActiveId) ? spyActiveId : flatItems[0]?.id);
70
+ useEffect(() => {
71
+ const list = listRef.current;
72
+ if (!list) return;
73
+ const measure = () => {
74
+ const rows = Array.from(list.children, (child, index) => {
75
+ const row = child;
76
+ return {
77
+ bottom: row.offsetTop + row.offsetHeight,
78
+ level: flatItems[index]?.level ?? 2,
79
+ top: row.offsetTop
80
+ };
81
+ });
82
+ setPath(buildTocPath(rows));
83
+ };
84
+ measure();
85
+ if (typeof ResizeObserver === "undefined") return;
86
+ const observer = new ResizeObserver(measure);
87
+ observer.observe(list);
88
+ return () => observer.disconnect();
89
+ }, [flatItems]);
90
+ useEffect(() => {
91
+ if (flatItems.length === 0) return;
92
+ const container = resolveContainer();
93
+ let frame = 0;
94
+ const spy = () => {
95
+ if (scrollLockRef.current) return;
96
+ const next = getActiveId(flatItems, container, offset);
97
+ setSpyActiveId((prev) => {
98
+ if (prev === next) return prev;
99
+ onChange?.(next ?? null);
100
+ return next;
101
+ });
102
+ };
103
+ const handleScroll = () => {
104
+ cancelAnimationFrame(frame);
105
+ frame = requestAnimationFrame(spy);
106
+ };
107
+ spy();
108
+ container.addEventListener("scroll", handleScroll, { passive: true });
109
+ return () => {
110
+ cancelAnimationFrame(frame);
111
+ container.removeEventListener("scroll", handleScroll);
112
+ };
113
+ }, [
114
+ flatItems,
115
+ offset,
116
+ onChange,
117
+ resolveContainer
118
+ ]);
119
+ useEffect(() => () => clearTimeout(lockTimerRef.current), []);
120
+ const parentId = findParentId(flatItems, activeId);
121
+ const activeIndex = flatItems.findIndex((item) => item.id === activeId);
122
+ const range = path.ranges[activeIndex];
123
+ const handleNavigate = (item, event) => {
124
+ onClick?.(event, {
125
+ href: item.href,
126
+ key: item.key,
127
+ title: item.title
128
+ });
129
+ if (event.defaultPrevented || event.button !== 0) return;
130
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
131
+ const target = getTarget(item.href);
132
+ if (!target) return;
133
+ event.preventDefault();
134
+ const container = resolveContainer();
135
+ const top = getRelativeTop(target, container) + getScrollTop(container) - offset;
136
+ const reduceMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
137
+ const release = () => {
138
+ scrollLockRef.current = false;
139
+ };
140
+ scrollLockRef.current = true;
141
+ setSpyActiveId(item.id);
142
+ onChange?.(item.id);
143
+ clearTimeout(lockTimerRef.current);
144
+ lockTimerRef.current = setTimeout(release, SCROLL_LOCK_FALLBACK_MS);
145
+ container.addEventListener("scrollend", release, { once: true });
146
+ container.scrollTo({
147
+ behavior: reduceMotion ? "auto" : "smooth",
148
+ top
149
+ });
150
+ };
151
+ if (flatItems.length === 0) return null;
152
+ return /* @__PURE__ */ jsx("nav", {
153
+ "aria-label": t("toc.onThisPage"),
154
+ "data-docs-toc": "",
155
+ ...rest,
156
+ ...styleProps(styles.root, clsx$1(tocClasses(), className), style),
157
+ children: /* @__PURE__ */ jsxs("div", {
158
+ ...styleProps(styles.pathList),
159
+ children: [/* @__PURE__ */ jsxs("svg", {
160
+ "aria-hidden": true,
161
+ focusable: "false",
162
+ ...styleProps(styles.pathSvg),
163
+ children: [/* @__PURE__ */ jsx("path", {
164
+ "data-toc-track": "",
165
+ ...styleProps(styles.track, tocClasses("track")),
166
+ d: path.d
167
+ }), range ? /* @__PURE__ */ jsx("path", {
168
+ ...styleProps(styles.highlight, tocClasses("highlight")),
169
+ d: path.d,
170
+ style: {
171
+ strokeDasharray: `${range[1] - range[0]} ${path.length}`,
172
+ strokeDashoffset: -range[0]
173
+ }
174
+ }) : null]
175
+ }), /* @__PURE__ */ jsx("ol", {
176
+ ref: listRef,
177
+ ...styleProps(styles.list, tocClasses("list")),
178
+ children: flatItems.map((item) => {
179
+ const active = item.id === activeId;
180
+ const parent = item.id === parentId;
181
+ return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx("a", {
182
+ "aria-current": active ? "location" : void 0,
183
+ "data-toc-parent": parent ? "" : void 0,
184
+ href: item.href,
185
+ ...styleProps([
186
+ styles.link,
187
+ item.level === 3 && styles.linkNested,
188
+ (active || parent) && styles.linkActive
189
+ ], tocClasses("link")),
190
+ onClick: (event) => handleNavigate(item, event),
191
+ children: item.title
192
+ }) }, item.key);
193
+ })
194
+ })]
195
+ })
196
+ });
197
+ };
198
+ Toc.displayName = "Toc";
199
+ export { Toc as default };
200
+
201
+ //# sourceMappingURL=Toc.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Toc.mjs","names":["tocMessages","clsx"],"sources":["../../src/Toc/Toc.tsx"],"sourcesContent":["'use client';\n\nimport clsx from 'clsx';\nimport type { MouseEvent as ReactMouseEvent } from 'react';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport tocMessages from '@/i18n/resources/en/toc';\nimport { useTranslation } from '@/i18n/useTranslation';\nimport { styleProps } from '@/styles/stylex/props';\n\nimport { tocClasses } from './stable';\nimport { styles } from './style';\nimport { buildTocPath, type TocPath } from './tocPath';\nimport { type FlatTocItem, toFlatTocItems } from './toFlatTocItems';\nimport type { TocProps } from './type';\n\nconst EMPTY_PATH: TocPath = { d: '', length: 0, ranges: [] };\nconst DEFAULT_OFFSET = 96;\nconst SCROLL_LOCK_FALLBACK_MS = 1000;\n\ntype ScrollContainer = HTMLElement | Window;\n\nconst isWindow = (container: ScrollContainer): container is Window => container === window;\n\nconst getRelativeTop = (element: HTMLElement, container: ScrollContainer) =>\n element.getBoundingClientRect().top -\n (isWindow(container) ? 0 : container.getBoundingClientRect().top);\n\nconst getScrollTop = (container: ScrollContainer) =>\n isWindow(container) ? window.scrollY : container.scrollTop;\n\nconst hrefToId = (href: string) => {\n const hash = href.includes('#') ? href.split('#').at(-1) : href.replace(/^#/, '');\n if (!hash) return '';\n try {\n return decodeURIComponent(hash);\n } catch {\n return hash;\n }\n};\n\nconst getTarget = (href: string) => {\n const id = hrefToId(href);\n if (!id) return null;\n return document.getElementById(id);\n};\n\nconst findParentId = (items: FlatTocItem[], activeId: string | undefined) => {\n const index = items.findIndex((item) => item.id === activeId);\n if (index < 0 || items[index].level !== 3) return undefined;\n for (let cursor = index - 1; cursor >= 0; cursor -= 1) {\n if (items[cursor].level === 2) return items[cursor].id;\n }\n return undefined;\n};\n\nconst getActiveId = (\n items: FlatTocItem[],\n container: ScrollContainer,\n offset: number,\n): string | undefined => {\n let activeId: string | undefined;\n let activeTop = -Infinity;\n for (const item of items) {\n const target = getTarget(item.href);\n if (!target) continue;\n const top = getRelativeTop(target, container);\n if (top <= offset + 1 && top >= activeTop) {\n activeId = item.id;\n activeTop = top;\n }\n }\n return activeId ?? items[0]?.id;\n};\n\nconst Toc = ({\n activeKey,\n className,\n getContainer,\n items = [],\n offset = DEFAULT_OFFSET,\n onChange,\n onClick,\n style,\n ...rest\n}: TocProps) => {\n const { t } = useTranslation(tocMessages);\n const flatItems = useMemo(() => toFlatTocItems(items), [items]);\n const listRef = useRef<HTMLOListElement>(null);\n const scrollLockRef = useRef(false);\n const lockTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n const [path, setPath] = useState<TocPath>(EMPTY_PATH);\n const [spyActiveId, setSpyActiveId] = useState<string | undefined>(undefined);\n\n const resolveContainer = useCallback((): ScrollContainer => {\n const container = getContainer?.();\n if (\n !container ||\n container === window ||\n container === document.body ||\n container === document.documentElement\n ) {\n return window;\n }\n return container;\n }, [getContainer]);\n\n const controlledId =\n activeKey != null && activeKey !== ''\n ? hrefToId(String(activeKey)) || flatItems.find((item) => item.key === activeKey)?.id\n : undefined;\n\n const activeId =\n controlledId ??\n (spyActiveId && flatItems.some((item) => item.id === spyActiveId)\n ? spyActiveId\n : flatItems[0]?.id);\n\n useEffect(() => {\n const list = listRef.current;\n if (!list) return;\n\n const measure = () => {\n const rows = Array.from(list.children, (child, index) => {\n const row = child as HTMLElement;\n return {\n bottom: row.offsetTop + row.offsetHeight,\n level: flatItems[index]?.level ?? 2,\n top: row.offsetTop,\n };\n });\n setPath(buildTocPath(rows));\n };\n\n measure();\n if (typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(measure);\n observer.observe(list);\n return () => observer.disconnect();\n }, [flatItems]);\n\n useEffect(() => {\n if (flatItems.length === 0) return;\n const container = resolveContainer();\n let frame = 0;\n const spy = () => {\n if (scrollLockRef.current) return;\n const next = getActiveId(flatItems, container, offset);\n setSpyActiveId((prev) => {\n if (prev === next) return prev;\n onChange?.(next ?? null);\n return next;\n });\n };\n const handleScroll = () => {\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(spy);\n };\n spy();\n container.addEventListener('scroll', handleScroll, { passive: true });\n return () => {\n cancelAnimationFrame(frame);\n container.removeEventListener('scroll', handleScroll);\n };\n }, [flatItems, offset, onChange, resolveContainer]);\n\n useEffect(() => () => clearTimeout(lockTimerRef.current), []);\n\n const parentId = findParentId(flatItems, activeId);\n const activeIndex = flatItems.findIndex((item) => item.id === activeId);\n const range = path.ranges[activeIndex];\n\n const handleNavigate = (item: FlatTocItem, event: ReactMouseEvent<HTMLAnchorElement>) => {\n onClick?.(event, { href: item.href, key: item.key, title: item.title });\n if (event.defaultPrevented || event.button !== 0) return;\n if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;\n\n const target = getTarget(item.href);\n if (!target) return;\n event.preventDefault();\n\n const container = resolveContainer();\n const top = getRelativeTop(target, container) + getScrollTop(container) - offset;\n const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;\n\n const release = () => {\n scrollLockRef.current = false;\n };\n scrollLockRef.current = true;\n setSpyActiveId(item.id);\n onChange?.(item.id);\n clearTimeout(lockTimerRef.current);\n lockTimerRef.current = setTimeout(release, SCROLL_LOCK_FALLBACK_MS);\n container.addEventListener('scrollend', release, { once: true });\n\n container.scrollTo({\n behavior: reduceMotion ? 'auto' : 'smooth',\n top,\n });\n };\n\n if (flatItems.length === 0) return null;\n\n return (\n <nav\n aria-label={t('toc.onThisPage')}\n data-docs-toc=\"\"\n {...rest}\n {...styleProps(styles.root, clsx(tocClasses(), className), style)}\n >\n <div {...styleProps(styles.pathList)}>\n <svg aria-hidden focusable=\"false\" {...styleProps(styles.pathSvg)}>\n <path data-toc-track=\"\" {...styleProps(styles.track, tocClasses('track'))} d={path.d} />\n {range ? (\n <path\n {...styleProps(styles.highlight, tocClasses('highlight'))}\n d={path.d}\n style={{\n strokeDasharray: `${range[1] - range[0]} ${path.length}`,\n strokeDashoffset: -range[0],\n }}\n />\n ) : null}\n </svg>\n <ol ref={listRef} {...styleProps(styles.list, tocClasses('list'))}>\n {flatItems.map((item) => {\n const active = item.id === activeId;\n const parent = item.id === parentId;\n return (\n <li key={item.key}>\n <a\n aria-current={active ? 'location' : undefined}\n data-toc-parent={parent ? '' : undefined}\n href={item.href}\n {...styleProps(\n [\n styles.link,\n item.level === 3 && styles.linkNested,\n (active || parent) && styles.linkActive,\n ],\n tocClasses('link'),\n )}\n onClick={(event) => handleNavigate(item, event)}\n >\n {item.title}\n </a>\n </li>\n );\n })}\n </ol>\n </div>\n </nav>\n );\n};\n\nToc.displayName = 'Toc';\n\nexport default Toc;\n"],"mappings":";;;;;;;;;;;;AAgBA,MAAM,aAAsB;CAAE,GAAG;CAAI,QAAQ;CAAG,QAAQ,CAAC;AAAE;AAC3D,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;AAIhC,MAAM,YAAY,cAAoD,cAAc;AAEpF,MAAM,kBAAkB,SAAsB,cAC5C,QAAQ,sBAAsB,CAAC,CAAC,OAC/B,SAAS,SAAS,IAAI,IAAI,UAAU,sBAAsB,CAAC,CAAC;AAE/D,MAAM,gBAAgB,cACpB,SAAS,SAAS,IAAI,OAAO,UAAU,UAAU;AAEnD,MAAM,YAAY,SAAiB;CACjC,MAAM,OAAO,KAAK,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,KAAK,QAAQ,MAAM,EAAE;CAChF,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI;EACF,OAAO,mBAAmB,IAAI;CAChC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,aAAa,SAAiB;CAClC,MAAM,KA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AI,WAAW,OAAO,OAAO;IAAhE,UAAA,CACE,oBAAC,QAAD;KAAM,kBAAe;KAAG,GAAI,WAAW,OAAO,OAAO,WAAW,OAAO,CAAC;KAAG,GAAG,KAAK;IAAI,CAAA,GACtF,QACC,oBAAC,QAAD;KACE,GAAI,WAAW,OAAO,WAAW,WAAW,WAAW,CAAC;KACxD,GAAG,KAAK;KACR,OAAO;MACL,iBAAiB,GAAG,MAAM,KAAK,MAAM,GAAG,GAAG,KAAK;MAChD,kBAAkB,CAAC,MAAM;KAC3B;IACD,CAAA,IACC,IACD;GACL,CAAA,GAAA,oBAAC,MAAD;IAAI,KAAK;IAAS,GAAI,WAAW,OAAO,MAAM,WAAW,MAAM,CAAC;IAC7D,UAAA,UAAU,KAAK,SAAS;KACvB,MAAM,SAAS,KAAK,OAAO;KAC3B,MAAM,SAAS,KAAK,OAAO;KAC3B,OACE,oBAAC,MAAD,EAAA,UACE,oBAAC,KAAD;MACE,gBAAc,SAAS,aAAa,KAAA;MACpC,mBAAiB,SAAS,KAAK,KAAA;MAC/B,MAAM,KAAK;MACX,GAAI,WACF;OACE,OAAO;OACP,KAAK,UAAU,KAAK,OAAO;QAC1B,UAAU,WAAW,OAAO;MAC/B,GACA,WAAW,MAAM,CACnB;MACA,UAAU,UAAU,eAAe,MAAM,KAAK;MAE7C,UAAA,KAAK;KACL,CAAA,EACD,GAjBK,KAAK,GAiBV;IAER,CAAC;GACC,CAAA,CACD;;CACF,CAAA;AAET;AAEA,IAAI,cAAc"}
@@ -0,0 +1,5 @@
1
+ import Toc from "./Toc.mjs";
2
+ import { TocPath, TocPathRow, buildTocPath } from "./tocPath.mjs";
3
+ import { FlatTocItem, toFlatTocItems } from "./toFlatTocItems.mjs";
4
+ import { TocItem, TocProps } from "./type.mjs";
5
+ export { type FlatTocItem, type TocItem, type TocPath, type TocPathRow, type TocProps, buildTocPath, Toc as default, toFlatTocItems };
@@ -0,0 +1 @@
1
+ export * from './index.d.mts';
@@ -0,0 +1 @@
1
+ export * from './index.mjs';
@@ -0,0 +1,4 @@
1
+ import Toc from "./Toc.mjs";
2
+ import { buildTocPath } from "./tocPath.mjs";
3
+ import { toFlatTocItems } from "./toFlatTocItems.mjs";
4
+ export { buildTocPath, Toc as default, toFlatTocItems };
@@ -0,0 +1,14 @@
1
+ import { stableClasses } from "../utils/bem.mjs";
2
+ // src/Toc/stable.ts
3
+ const tocClasses = stableClasses({
4
+ block: "toc",
5
+ elements: [
6
+ "list",
7
+ "link",
8
+ "track",
9
+ "highlight"
10
+ ]
11
+ });
12
+ export { tocClasses };
13
+
14
+ //# sourceMappingURL=stable.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stable.mjs","names":[],"sources":["../../src/Toc/stable.ts"],"sourcesContent":["import { stableClasses } from '@/utils/bem';\n\nexport const tocClasses = stableClasses({\n block: 'toc',\n elements: ['list', 'link', 'track', 'highlight'],\n});\n"],"mappings":";;AAEA,MAAa,aAAa,cAAc;CACtC,OAAO;CACP,UAAU;EAAC;EAAQ;EAAQ;EAAS;CAAW;AACjD,CAAC"}
@@ -0,0 +1,76 @@
1
+ // src/Toc/style.ts
2
+ const styles = {
3
+ highlight: {
4
+ kDwRjp: "lbbh8q5q",
5
+ kjVXCG: "lblq7gtg",
6
+ k5rJSQ: null,
7
+ kDRTOe: null,
8
+ kU5bRw: "lb1owpc8m",
9
+ kfJifR: "lbhr4kjn",
10
+ kmkexE: "lb82stzn",
11
+ kIyJzY: "lbsagj69",
12
+ $$css: true
13
+ },
14
+ link: {
15
+ kaIpWk: "lbn61e16",
16
+ k8WAf4: "lb1qrv0by",
17
+ kybGjl: "lb1hl2dhg",
18
+ kmkexE: "lb1w3xhyk",
19
+ kMwMTN: "lbc77et8 lb1bxu9lh",
20
+ k1xSpc: "lb1lliihq",
21
+ kGuDYH: "lb4z9k3i",
22
+ k63SB2: "lb1cd1r4b",
23
+ kLWn49: "lb8r4c90",
24
+ kjBf7l: "lb1ay5pp7",
25
+ kInvED: "lb7s97pk",
26
+ k3XXqK: "lb9v5kkp",
27
+ kMeerF: "lb784prv",
28
+ kwRFfy: "lb1do52mm",
29
+ kZCmMZ: "lb1v1g0nc",
30
+ kIyJzY: "lbsagj69",
31
+ $$css: true
32
+ },
33
+ linkActive: {
34
+ kMwMTN: "lb66ogz0",
35
+ k63SB2: "lbfbjfs5",
36
+ $$css: true
37
+ },
38
+ linkNested: {
39
+ kZCmMZ: "lb1ljuerk",
40
+ $$css: true
41
+ },
42
+ list: {
43
+ kogj98: "lb1ghz6dp",
44
+ kmVPX3: "lb1717udv",
45
+ kB88ic: "lbe8uvvx",
46
+ $$css: true
47
+ },
48
+ pathList: {
49
+ kVAEAm: "lb1n2onr6",
50
+ $$css: true
51
+ },
52
+ pathSvg: {
53
+ kVQacm: "lb1rea2x4",
54
+ k87sOh: "lb13vifvy",
55
+ kLqNvP: "lb1o0tod",
56
+ kfzvcC: "lb47corl",
57
+ kVAEAm: "lb10l6tqk",
58
+ kZKoxP: "lb5yr21d",
59
+ kzqmXN: "lbcdlrvm",
60
+ $$css: true
61
+ },
62
+ root: {
63
+ kzqmXN: "lbh8yej3",
64
+ $$css: true
65
+ },
66
+ track: {
67
+ kDwRjp: "lbbh8q5q",
68
+ kjVXCG: "lbjw6t2z",
69
+ kU5bRw: "lb1owpc8m",
70
+ kfJifR: "lbnpr05h",
71
+ $$css: true
72
+ }
73
+ };
74
+ export { styles };
75
+
76
+ //# sourceMappingURL=style.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"style.mjs","names":[],"sources":["../../src/Toc/style.ts"],"sourcesContent":["import * as stylex from '@stylexjs/stylex';\n\nimport { cssVar } from '@/styles/stylex/cssVar.stylex';\n\nconst reducedMotion = '@media (prefers-reduced-motion: reduce)';\n\nexport const styles = stylex.create({\n highlight: {\n fill: 'none',\n stroke: cssVar.colorText,\n strokeDasharray: null,\n strokeDashoffset: null,\n strokeLinecap: 'round',\n strokeWidth: 1.5,\n transition:\n 'stroke-dasharray 460ms cubic-bezier(0.2, 0.8, 0.2, 1), stroke-dashoffset 460ms cubic-bezier(0.2, 0.8, 0.2, 1)',\n transitionDuration: { default: null, [reducedMotion]: '0.01ms' },\n },\n link: {\n borderRadius: { 'default': null, ':focus-visible': 4 },\n paddingBlock: '0.3125rem',\n textDecoration: 'none',\n transition: 'color 160ms ease',\n color: {\n 'default': cssVar.colorTextSecondary,\n ':hover': cssVar.colorText,\n },\n display: 'block',\n fontSize: 13,\n fontWeight: { 'default': null, \":is([aria-current='location'])\": 540 },\n lineHeight: '1.25rem',\n outlineColor: { 'default': null, ':focus-visible': cssVar.colorText },\n outlineOffset: { 'default': null, ':focus-visible': 2 },\n outlineStyle: { 'default': null, ':focus-visible': 'solid' },\n outlineWidth: { 'default': null, ':focus-visible': 2 },\n paddingInlineEnd: '0.25rem',\n paddingInlineStart: '1.375rem',\n transitionDuration: { default: null, [reducedMotion]: '0.01ms' },\n },\n linkActive: {\n color: cssVar.colorText,\n fontWeight: 540,\n },\n linkNested: {\n paddingInlineStart: '2.125rem',\n },\n list: {\n margin: 0,\n padding: 0,\n listStyle: 'none',\n },\n pathList: {\n position: 'relative',\n },\n pathSvg: {\n overflow: 'visible',\n insetBlockStart: 0,\n insetInlineStart: 0,\n pointerEvents: 'none',\n position: 'absolute',\n height: '100%',\n width: '1rem',\n },\n root: {\n width: '100%',\n },\n track: {\n fill: 'none',\n stroke: cssVar.colorBorder,\n strokeLinecap: 'round',\n strokeWidth: 1,\n },\n});\n"],"mappings":";AAIA,MAAa,SAAS;CACpB,WAAW;EACT,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,OAAO;CACT;CACA,MAAM;EACJ,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,OAAO;CACT;CACA,YAAY;EACV,QAAQ;EACR,QAAQ;EACR,OAAO;CACT;CACA,YAAY;EACV,QAAQ;EACR,OAAO;CACT;CACA,MAAM;EACJ,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,OAAO;CACT;CACA,UAAU;EACR,QAAQ;EACR,OAAO;CACT;CACA,SAAS;EACP,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,OAAO;CACT;CACA,MAAM;EACJ,QAAQ;EACR,OAAO;CACT;CACA,OAAO;EACL,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,OAAO;CACT;AACF"}
@@ -0,0 +1,16 @@
1
+ import { AnchorItem } from "../Anchor/type.mjs";
2
+ import "../Anchor/index.mjs";
3
+ import { TocItem } from "./type.mjs";
4
+ import { ReactNode } from "react";
5
+ export interface FlatTocItem {
6
+ href: string;
7
+ id: string;
8
+ key: string;
9
+ level: 2 | 3;
10
+ title: ReactNode;
11
+ }
12
+ /**
13
+ * Normalize Anchor tree or flat TocItem[] into a flat outline.
14
+ */
15
+ export declare const toFlatTocItems: (items?: AnchorItem[] | TocItem[]) => FlatTocItem[];
16
+ //# sourceMappingURL=toFlatTocItems.d.mts.map
@@ -0,0 +1,52 @@
1
+ // src/Toc/toFlatTocItems.ts
2
+ const hrefToId = (href) => {
3
+ const hash = href.includes("#") ? href.split("#").at(-1) : href.replace(/^#/, "");
4
+ if (!hash) return "";
5
+ try {
6
+ return decodeURIComponent(hash);
7
+ } catch {
8
+ return hash;
9
+ }
10
+ };
11
+ /**
12
+ * Normalize Anchor tree or flat TocItem[] into a flat outline.
13
+ */
14
+ const toFlatTocItems = (items = []) => {
15
+ if (!items.length) return [];
16
+ if (typeof items[0].level === "number") return items.flatMap((item, index) => {
17
+ const id = hrefToId(item.href);
18
+ if (!id || item.title == null || item.title === false || item.title === "") return [];
19
+ return [{
20
+ href: item.href.startsWith("#") ? item.href : `#${id}`,
21
+ id,
22
+ key: String(index + 1),
23
+ level: item.level === 3 ? 3 : 2,
24
+ title: item.title
25
+ }];
26
+ });
27
+ return items.flatMap((item, index) => {
28
+ const id = hrefToId(item.href);
29
+ const top = id ? [{
30
+ href: item.href.startsWith("#") ? item.href : `#${id}`,
31
+ id,
32
+ key: item.key ?? String(index + 1),
33
+ level: 2,
34
+ title: item.title ?? ""
35
+ }] : [];
36
+ const children = (item.children ?? []).flatMap((child, childIndex) => {
37
+ const childId = hrefToId(child.href);
38
+ if (!childId) return [];
39
+ return [{
40
+ href: child.href.startsWith("#") ? child.href : `#${childId}`,
41
+ id: childId,
42
+ key: child.key ?? `${item.key ?? index}-${childIndex}`,
43
+ level: 3,
44
+ title: child.title ?? ""
45
+ }];
46
+ });
47
+ return [...top, ...children];
48
+ });
49
+ };
50
+ export { toFlatTocItems };
51
+
52
+ //# sourceMappingURL=toFlatTocItems.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toFlatTocItems.mjs","names":[],"sources":["../../src/Toc/toFlatTocItems.ts"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport type { AnchorItem } from '../Anchor';\nimport type { TocItem } from './type';\n\nexport interface FlatTocItem {\n href: string;\n id: string;\n key: string;\n level: 2 | 3;\n title: ReactNode;\n}\n\nconst hrefToId = (href: string) => {\n const hash = href.includes('#') ? href.split('#').at(-1) : href.replace(/^#/, '');\n if (!hash) return '';\n try {\n return decodeURIComponent(hash);\n } catch {\n return hash;\n }\n};\n\n/**\n * Normalize Anchor tree or flat TocItem[] into a flat outline.\n */\nexport const toFlatTocItems = (items: AnchorItem[] | TocItem[] = []): FlatTocItem[] => {\n if (!items.length) return [];\n\n const first = items[0] as TocItem & { level?: number };\n if (typeof first.level === 'number') {\n return (items as TocItem[]).flatMap((item, index) => {\n const id = hrefToId(item.href);\n if (!id || item.title == null || item.title === false || item.title === '') return [];\n return [\n {\n href: item.href.startsWith('#') ? item.href : `#${id}`,\n id,\n key: String(index + 1),\n level: item.level === 3 ? 3 : 2,\n title: item.title,\n } satisfies FlatTocItem,\n ];\n });\n }\n\n return (items as AnchorItem[]).flatMap((item, index) => {\n const id = hrefToId(item.href);\n const top: FlatTocItem[] = id\n ? [\n {\n href: item.href.startsWith('#') ? item.href : `#${id}`,\n id,\n key: item.key ?? String(index + 1),\n level: 2,\n title: item.title ?? '',\n },\n ]\n : [];\n const children = (item.children ?? []).flatMap((child, childIndex) => {\n const childId = hrefToId(child.href);\n if (!childId) return [];\n return [\n {\n href: child.href.startsWith('#') ? child.href : `#${childId}`,\n id: childId,\n key: child.key ?? `${item.key ?? index}-${childIndex}`,\n level: 3 as const,\n title: child.title ?? '',\n },\n ];\n });\n return [...top, ...children];\n });\n};\n"],"mappings":";AAaA,MAAM,YAAY,SAAiB;CACjC,MAAM,OAAO,KAAK,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,KAAK,QAAQ,MAAM,EAAE;CAChF,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI;EACF,OAAO,mBAAmB,IAAI;CAChC,QAAQ;EACN,OAAO;CACT;AACF;;;;AAKA,MAAa,kBAAkB,QAAkC,CAAC,MAAqB;CACrF,IAAI,CAAC,MAAM,QAAQ,OAAO,CAAC;CAG3B,IAAI,OADU,MAAM,EACJ,CAAC,UAAU,UACzB,OAAQ,MAAoB,SAAS,MAAM,UAAU;EACnD,MAAM,KAAK,SAAS,KAAK,IAAI;EAC7B,IAAI,CAAC,MAAM,KAAK,SAAS,QAAQ,KAAK,UAAU,SAAS,KAAK,UAAU,IAAI,OAAO,CAAC;EACpF,OAAO,CACL;GACE,MAAM,KAAK,KAAK,WAAW,GAAG,IAAI,KAAK,OAAO,IAAI;GAClD;GACA,KAAK,OAAO,QAAQ,CAAC;GACrB,OAAO,KAAK,UAAU,IAAI,IAAI;GAC9B,OAAO,KAAK;EACd,CACF;CACF,CAAC;CAGH,OAAQ,MAAuB,SAAS,MAAM,UAAU;EACtD,MAAM,KAAK,SAAS,KAAK,IAAI;EAC7B,MAAM,MAAqB,KACvB,CACE;GACE,MAAM,KAAK,KAAK,WAAW,GAAG,IAAI,KAAK,OAAO,IAAI;GAClD;GACA,KAAK,KAAK,OAAO,OAAO,QAAQ,CAAC;GACjC,OAAO;GACP,OAAO,KAAK,SAAS;EACvB,CACF,IACA,CAAC;EACL,MAAM,YAAY,KAAK,YAAY,CAAC,EAAA,CAAG,SAAS,OAAO,eAAe;GACpE,MAAM,UAAU,SAAS,MAAM,IAAI;GACnC,IAAI,CAAC,SAAS,OAAO,CAAC;GACtB,OAAO,CACL;IACE,MAAM,MAAM,KAAK,WAAW,GAAG,IAAI,MAAM,OAAO,IAAI;IACpD,IAAI;IACJ,KAAK,MAAM,OAAO,GAAG,KAAK,OAAO,MAAM,GAAG;IAC1C,OAAO;IACP,OAAO,MAAM,SAAS;GACxB,CACF;EACF,CAAC;EACD,OAAO,CAAC,GAAG,KAAK,GAAG,QAAQ;CAC7B,CAAC;AACH"}
@@ -0,0 +1,12 @@
1
+ export interface TocPathRow {
2
+ bottom: number;
3
+ level: 2 | 3;
4
+ top: number;
5
+ }
6
+ export interface TocPath {
7
+ d: string;
8
+ length: number;
9
+ ranges: Array<[start: number, end: number]>;
10
+ }
11
+ export declare const buildTocPath: (rows: TocPathRow[]) => TocPath;
12
+ //# sourceMappingURL=tocPath.d.mts.map
@@ -0,0 +1,82 @@
1
+ const ROW_INSET = 6;
2
+ const BEND_RADIUS = 5;
3
+ const CURVE_SAMPLES = 16;
4
+ const round = (value) => Math.round(value * 100) / 100;
5
+ const quadraticLength = (from, control, to) => {
6
+ let total = 0;
7
+ let previous = from;
8
+ for (let step = 1; step <= CURVE_SAMPLES; step += 1) {
9
+ const t = step / CURVE_SAMPLES;
10
+ const u = 1 - t;
11
+ const next = {
12
+ x: u * u * from.x + 2 * u * t * control.x + t * t * to.x,
13
+ y: u * u * from.y + 2 * u * t * control.y + t * t * to.y
14
+ };
15
+ total += Math.hypot(next.x - previous.x, next.y - previous.y);
16
+ previous = next;
17
+ }
18
+ return total;
19
+ };
20
+ const buildTocPath = (rows) => {
21
+ if (rows.length === 0) return {
22
+ d: "",
23
+ length: 0,
24
+ ranges: []
25
+ };
26
+ const points = rows.flatMap((row) => {
27
+ const x = row.level === 3 ? 13 : 1;
28
+ return [{
29
+ x,
30
+ y: row.top + ROW_INSET
31
+ }, {
32
+ x,
33
+ y: row.bottom - ROW_INSET
34
+ }];
35
+ });
36
+ let d = `M${points[0].x} ${points[0].y}`;
37
+ let length = 0;
38
+ let cursor = points[0];
39
+ const offsets = [0];
40
+ for (let index = 1; index < points.length; index += 1) {
41
+ const point = points[index];
42
+ const previous = points[index - 1];
43
+ const next = points[index + 1];
44
+ const inX = point.x - previous.x;
45
+ const inY = point.y - previous.y;
46
+ if (!(next !== void 0 && (next.x - point.x) * inY - (next.y - point.y) * inX !== 0)) {
47
+ length += Math.hypot(point.x - cursor.x, point.y - cursor.y);
48
+ d += ` L${point.x} ${point.y}`;
49
+ offsets.push(length);
50
+ cursor = point;
51
+ continue;
52
+ }
53
+ const inLength = Math.hypot(inX, inY);
54
+ const outX = next.x - point.x;
55
+ const outY = next.y - point.y;
56
+ const outLength = Math.hypot(outX, outY);
57
+ const radius = Math.min(BEND_RADIUS, inLength / 2, outLength / 2);
58
+ const entry = {
59
+ x: point.x - inX / inLength * radius,
60
+ y: point.y - inY / inLength * radius
61
+ };
62
+ const exit = {
63
+ x: point.x + outX / outLength * radius,
64
+ y: point.y + outY / outLength * radius
65
+ };
66
+ const curve = quadraticLength(entry, point, exit);
67
+ length += Math.hypot(entry.x - cursor.x, entry.y - cursor.y);
68
+ d += ` L${round(entry.x)} ${round(entry.y)} Q${point.x} ${point.y} ${round(exit.x)} ${round(exit.y)}`;
69
+ offsets.push(length + curve / 2);
70
+ length += curve;
71
+ cursor = exit;
72
+ }
73
+ const ranges = rows.map((_, index) => [round(offsets[index * 2]), round(offsets[index * 2 + 1])]);
74
+ return {
75
+ d,
76
+ length: round(length),
77
+ ranges
78
+ };
79
+ };
80
+ export { buildTocPath };
81
+
82
+ //# sourceMappingURL=tocPath.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tocPath.mjs","names":[],"sources":["../../src/Toc/tocPath.ts"],"sourcesContent":["export interface TocPathRow {\n bottom: number;\n level: 2 | 3;\n top: number;\n}\n\nexport interface TocPath {\n d: string;\n length: number;\n ranges: Array<[start: number, end: number]>;\n}\n\ninterface Point {\n x: number;\n y: number;\n}\n\nexport const TOC_TRACK_X = 1;\nexport const TOC_NESTED_TRACK_X = 13;\nconst ROW_INSET = 6;\nconst BEND_RADIUS = 5;\nconst CURVE_SAMPLES = 16;\n\nconst round = (value: number) => Math.round(value * 100) / 100;\n\nconst quadraticLength = (from: Point, control: Point, to: Point) => {\n let total = 0;\n let previous = from;\n for (let step = 1; step <= CURVE_SAMPLES; step += 1) {\n const t = step / CURVE_SAMPLES;\n const u = 1 - t;\n const next = {\n x: u * u * from.x + 2 * u * t * control.x + t * t * to.x,\n y: u * u * from.y + 2 * u * t * control.y + t * t * to.y,\n };\n total += Math.hypot(next.x - previous.x, next.y - previous.y);\n previous = next;\n }\n return total;\n};\n\nexport const buildTocPath = (rows: TocPathRow[]): TocPath => {\n if (rows.length === 0) return { d: '', length: 0, ranges: [] };\n\n const points = rows.flatMap((row) => {\n const x = row.level === 3 ? TOC_NESTED_TRACK_X : TOC_TRACK_X;\n return [\n { x, y: row.top + ROW_INSET },\n { x, y: row.bottom - ROW_INSET },\n ];\n });\n\n let d = `M${points[0].x} ${points[0].y}`;\n let length = 0;\n let cursor = points[0];\n const offsets = [0];\n\n for (let index = 1; index < points.length; index += 1) {\n const point = points[index];\n const previous = points[index - 1];\n const next = points[index + 1];\n const inX = point.x - previous.x;\n const inY = point.y - previous.y;\n const bends = next !== undefined && (next.x - point.x) * inY - (next.y - point.y) * inX !== 0;\n\n if (!bends) {\n length += Math.hypot(point.x - cursor.x, point.y - cursor.y);\n d += ` L${point.x} ${point.y}`;\n offsets.push(length);\n cursor = point;\n continue;\n }\n\n const inLength = Math.hypot(inX, inY);\n const outX = next.x - point.x;\n const outY = next.y - point.y;\n const outLength = Math.hypot(outX, outY);\n const radius = Math.min(BEND_RADIUS, inLength / 2, outLength / 2);\n const entry = {\n x: point.x - (inX / inLength) * radius,\n y: point.y - (inY / inLength) * radius,\n };\n const exit = {\n x: point.x + (outX / outLength) * radius,\n y: point.y + (outY / outLength) * radius,\n };\n const curve = quadraticLength(entry, point, exit);\n\n length += Math.hypot(entry.x - cursor.x, entry.y - cursor.y);\n d += ` L${round(entry.x)} ${round(entry.y)} Q${point.x} ${point.y} ${round(exit.x)} ${round(exit.y)}`;\n offsets.push(length + curve / 2);\n length += curve;\n cursor = exit;\n }\n\n const ranges = rows.map(\n (_, index) =>\n [round(offsets[index * 2]), round(offsets[index * 2 + 1])] as [start: number, end: number],\n );\n\n return { d, length: round(length), ranges };\n};\n"],"mappings":"AAmBA,MAAM,YAAY;AAClB,MAAM,cAAc;AACpB,MAAM,gBAAgB;AAEtB,MAAM,SAAS,UAAkB,KAAK,MAAM,QAAQ,GAAG,IAAI;AAE3D,MAAM,mBAAmB,MAAa,SAAgB,OAAc;CAClE,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,KAAK,IAAI,OAAO,GAAG,QAAQ,eAAe,QAAQ,GAAG;EACnD,MAAM,IAAI,OAAO;EACjB,MAAM,IAAI,IAAI;EACd,MAAM,OAAO;GACX,GAAG,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,IAAI,QAAQ,IAAI,IAAI,IAAI,GAAG;GACvD,GAAG,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,IAAI,QAAQ,IAAI,IAAI,IAAI,GAAG;EACzD;EACA,SAAS,KAAK,MAAM,KAAK,IAAI,SAAS,GAAG,KAAK,IAAI,SAAS,CAAC;EAC5D,WAAW;CACb;CACA,OAAO;AACT;AAEA,M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AAK,MAAM,WAAY;EAClC;EACA,MAAM,OAAO;GACX,GAAG,MAAM,IAAK,OAAO,YAAa;GAClC,GAAG,MAAM,IAAK,OAAO,YAAa;EACpC;EACA,MAAM,QAAQ,gBAAgB,OAAO,OAAO,IAAI;EAEhD,UAAU,KAAK,MAAM,MAAM,IAAI,OAAO,GAAG,MAAM,IAAI,OAAO,CAAC;EAC3D,KAAK,KAAK,MAAM,MAAM,CAAC,EAAE,GAAG,MAAM,MAAM,CAAC,EAAE,IAAI,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,KAAK,CAAC,EAAE,GAAG,MAAM,KAAK,CAAC;EAClG,QAAQ,KAAK,SAAS,QAAQ,CAAC;EAC/B,UAAU;EACV,SAAS;CACX;CAEA,MAAM,SAAS,KAAK,KACjB,GAAG,UACF,CAAC,MAAM,QAAQ,QAAQ,EAAE,GAAG,MAAM,QAAQ,QAAQ,IAAI,EAAE,CAAC,CAC7D;CAEA,OAAO;EAAE;EAAG,QAAQ,MAAM,MAAM;EAAG;CAAO;AAC5C"}
@@ -0,0 +1,43 @@
1
+ import { AnchorItem } from "../Anchor/type.mjs";
2
+ import "../Anchor/index.mjs";
3
+ import { ComponentProps, ReactNode } from "react";
4
+ export interface TocItem {
5
+ href: string;
6
+ level: 2 | 3;
7
+ title: ReactNode;
8
+ }
9
+ /**
10
+ * @title Toc
11
+ */
12
+ export interface TocProps extends Omit<ComponentProps<'nav'>, 'children' | 'onChange' | 'onClick'> {
13
+ /**
14
+ * Controlled active key (the href or id of the active item)
15
+ */
16
+ activeKey?: string | null;
17
+ /**
18
+ * Returns the scroll container (default `window`; `document.body` / `document.documentElement` are normalized to `window`)
19
+ */
20
+ getContainer?: () => HTMLElement | Window | null | undefined;
21
+ /**
22
+ * Table of contents items (supports both Anchor tree format and flat TocItem array)
23
+ */
24
+ items?: AnchorItem[] | TocItem[];
25
+ /**
26
+ * Pixels from the container top to mark a heading as active
27
+ * @default 96
28
+ */
29
+ offset?: number;
30
+ /**
31
+ * Fires when the active item changes (passes the id, not the href)
32
+ */
33
+ onChange?: (activeId: string | null) => void;
34
+ /**
35
+ * Fires when a link is clicked (before the built-in scroll)
36
+ */
37
+ onClick?: (event: React.MouseEvent<HTMLAnchorElement>, item: {
38
+ href: string;
39
+ key: string;
40
+ title: ReactNode;
41
+ }) => void;
42
+ }
43
+ //# sourceMappingURL=type.d.mts.map