@noy4/docserve 0.3.2 → 0.3.4

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.
Files changed (76) hide show
  1. package/bin.mjs +2 -2
  2. package/dist/widget/index.js +11803 -0
  3. package/package.json +24 -3
  4. package/src/node/adapter.mjs +67 -0
  5. package/src/node/assets.mjs +36 -0
  6. package/src/node/dates.mjs +73 -0
  7. package/src/node/docs-info.mjs +39 -0
  8. package/src/node/files.mjs +43 -0
  9. package/src/node/gallery.mjs +33 -0
  10. package/src/node/inject.mjs +43 -0
  11. package/src/node/meta.mjs +137 -0
  12. package/src/node/routes.mjs +105 -0
  13. package/src/node/scan.mjs +87 -0
  14. package/src/node/serve-static.mjs +158 -0
  15. package/src/node/server.mjs +69 -0
  16. package/src/node/watch.mjs +119 -0
  17. package/src/plugins/collapse/client.js +45 -0
  18. package/src/plugins/collapse/collapse.css +74 -0
  19. package/src/plugins/collapse/commands.ts +81 -0
  20. package/src/plugins/collapse/model.ts +123 -0
  21. package/src/plugins/collapse/sections.ts +105 -0
  22. package/src/plugins/collapse/view.ts +84 -0
  23. package/src/plugins/copy/client.js +72 -0
  24. package/src/plugins/copy/copy.css +21 -0
  25. package/src/plugins/home/client.js +24 -0
  26. package/src/plugins/sidebar/client.js +106 -0
  27. package/src/plugins/sidebar/grouping.js +108 -0
  28. package/src/plugins/sidebar/icons.js +25 -0
  29. package/src/plugins/sidebar/model.ts +91 -0
  30. package/src/plugins/sidebar/resize-model.ts +47 -0
  31. package/src/plugins/sidebar/sidebar.css +663 -0
  32. package/src/plugins/sidebar/tree-model.ts +23 -0
  33. package/src/plugins/sidebar/tree.ts +69 -0
  34. package/src/plugins/sidebar/ui/PageList.tsx +153 -0
  35. package/src/plugins/sidebar/ui/RadioMenu.tsx +201 -0
  36. package/src/plugins/sidebar/ui/Sidebar.tsx +95 -0
  37. package/src/plugins/sidebar/ui/SidebarHeader.tsx +87 -0
  38. package/src/plugins/sidebar/ui/TreeList.tsx +121 -0
  39. package/src/plugins/sidebar/ui/preview-model.ts +134 -0
  40. package/src/plugins/sidebar/ui/useModel.ts +25 -0
  41. package/src/plugins/toc/client.js +55 -0
  42. package/src/plugins/toc/commands.ts +49 -0
  43. package/src/plugins/toc/heading-html.ts +40 -0
  44. package/src/plugins/toc/model.ts +178 -0
  45. package/src/plugins/toc/outline.js +94 -0
  46. package/src/plugins/toc/scroll-spy.ts +35 -0
  47. package/src/plugins/toc/toc.css +214 -0
  48. package/src/plugins/toc/ui/TocPanel.tsx +87 -0
  49. package/src/shared/types.d.ts +193 -0
  50. package/src/widget/commands.js +214 -0
  51. package/src/widget/docks.js +127 -0
  52. package/src/widget/host.js +187 -0
  53. package/src/widget/index.js +22 -0
  54. package/src/widget/lib/disposables.js +44 -0
  55. package/src/widget/lib/dom.js +106 -0
  56. package/src/widget/lib/events.js +65 -0
  57. package/src/widget/lib/headings.js +132 -0
  58. package/src/widget/lib/persisted-signal.js +40 -0
  59. package/src/widget/lib/storage.js +70 -0
  60. package/src/widget/live.js +86 -0
  61. package/src/widget/pages.js +65 -0
  62. package/src/widget/palette.css +162 -0
  63. package/src/widget/palette.js +259 -0
  64. package/src/widget/placement.js +204 -0
  65. package/src/widget/plugins.js +39 -0
  66. package/src/widget/rpc.js +32 -0
  67. package/src/widget/styles.js +31 -0
  68. package/src/widget/ui.js +50 -0
  69. package/src/widget/widget.css +206 -0
  70. package/server/files.mjs +0 -261
  71. package/server/index.mjs +0 -198
  72. package/server/inject.html +0 -88
  73. package/server/inject.mjs +0 -28
  74. package/server/watch.mjs +0 -104
  75. /package/{server → src/node}/state.mjs +0 -0
  76. /package/{server → src/node}/websocket.mjs +0 -0
@@ -0,0 +1,121 @@
1
+ import { decoded, pageUrl } from "../../../widget/lib/dom.js"
2
+ import type { CSSProperties } from "react"
3
+ import { ICON_CHEVRON, ICON_FILE } from "../icons.js"
4
+ import type { TreeModel } from "../tree-model.js"
5
+ import type { TreeNode } from "../tree.js"
6
+ import { Favicon } from "./PageList.js"
7
+
8
+ export interface TreeListProps {
9
+ model: TreeModel
10
+ currentPage: string
11
+ }
12
+
13
+ export function TreeList({ model, currentPage }: TreeListProps) {
14
+ const nodes = model.nodes.value
15
+ const collapsed = new Set(model.collapsed.value)
16
+ const target = pageUrl(currentPage)
17
+
18
+ if (!nodes.length)
19
+ return <p className="docserve-sidebar__empty">No pages</p>
20
+
21
+ return (
22
+ <div className="docserve-sidebar__tree" role="tree" aria-label="Pages">
23
+ {nodes.map((node) => (
24
+ <TreeRow
25
+ key={node.path}
26
+ node={node}
27
+ depth={0}
28
+ collapsed={collapsed}
29
+ model={model}
30
+ target={target}
31
+ currentPage={currentPage}
32
+ />
33
+ ))}
34
+ </div>
35
+ )
36
+ }
37
+
38
+ interface TreeRowProps {
39
+ node: TreeNode<DocPage>
40
+ depth: number
41
+ collapsed: Set<string>
42
+ model: TreeModel
43
+ target: string
44
+ currentPage: string
45
+ }
46
+
47
+ function TreeRow({ node, depth, collapsed, model, target, currentPage }: TreeRowProps) {
48
+ // One 16px slot per row: a chevron for folders, an icon for pages. Both
49
+ // start at the same offset, so every label lines up column for column.
50
+ const style = { paddingLeft: `${8 + depth * 14}px` }
51
+
52
+ if (node.isFolder) {
53
+ const open = !collapsed.has(node.path)
54
+
55
+ return (
56
+ <div className="docserve-sidebar__tree-branch" role="none">
57
+ <button
58
+ type="button"
59
+ className="docserve-sidebar__tree-row docserve-sidebar__tree-row--folder"
60
+ role="treeitem"
61
+ aria-expanded={open}
62
+ aria-level={depth + 1}
63
+ style={style}
64
+ onClick={() => model.toggleFolder(node.path)}
65
+ >
66
+ <span
67
+ className="docserve-sidebar__tree-slot docserve-sidebar__tree-caret"
68
+ data-open={open ? "" : undefined}
69
+ dangerouslySetInnerHTML={{ __html: ICON_CHEVRON }}
70
+ />
71
+ <span className="docserve-sidebar__tree-label">{node.name}</span>
72
+ </button>
73
+ {open && (
74
+ <div
75
+ className="docserve-sidebar__tree-group"
76
+ role="group"
77
+ style={{ "--docserve-tree-guide": `${16 + depth * 14}px` } as CSSProperties}
78
+ >
79
+ {node.children.map((child) => (
80
+ <TreeRow
81
+ key={child.path}
82
+ node={child}
83
+ depth={depth + 1}
84
+ collapsed={collapsed}
85
+ model={model}
86
+ target={target}
87
+ currentPage={currentPage}
88
+ />
89
+ ))}
90
+ </div>
91
+ )}
92
+ </div>
93
+ )
94
+ }
95
+
96
+ const page = node.data
97
+ if (!page) return null
98
+
99
+ const active = isActive(page, target, currentPage)
100
+
101
+ return (
102
+ <a
103
+ className="docserve-sidebar__tree-row docserve-sidebar__tree-row--page"
104
+ role="treeitem"
105
+ aria-level={depth + 1}
106
+ aria-current={active ? "page" : undefined}
107
+ href={page.url}
108
+ title={page.title}
109
+ style={style}
110
+ >
111
+ <span className="docserve-sidebar__tree-slot docserve-sidebar__tree-icon">
112
+ {page.favicon ? <Favicon src={page.favicon} /> : <span dangerouslySetInnerHTML={{ __html: ICON_FILE }} />}
113
+ </span>
114
+ <span className="docserve-sidebar__tree-label">{node.name}</span>
115
+ </a>
116
+ )
117
+ }
118
+
119
+ function isActive(page: DocPage, target: string, currentPage: string): boolean {
120
+ return page.url === target || decoded(page.url) === `/${currentPage}`
121
+ }
@@ -0,0 +1,134 @@
1
+ import { effect, signal } from "@preact/signals-react"
2
+
3
+ export const THUMB_W = 960
4
+ const MAX_PREVIEWS = 2
5
+
6
+ interface QueueItem {
7
+ iframe: HTMLIFrameElement
8
+ src: string
9
+ }
10
+
11
+ export class PreviewModel {
12
+ #root = signal<HTMLElement | null>(null)
13
+
14
+ readonly setRoot = (element: HTMLElement | null): void => {
15
+ this.#root.value = element
16
+ }
17
+
18
+ get element(): HTMLElement | null {
19
+ return this.#root.value
20
+ }
21
+
22
+ #thumbs = new Set<HTMLElement>()
23
+ #observer: IntersectionObserver | null = null
24
+ #resize: ResizeObserver | null = null
25
+ #queue: QueueItem[] = []
26
+ #loads = new Map<HTMLIFrameElement, () => void>()
27
+ #active = 0
28
+
29
+ subscribe(): () => void {
30
+ const stop = effect(() => {
31
+ const root = this.#root.value
32
+ if (!root) return
33
+
34
+ const observer = new IntersectionObserver((entries) => {
35
+ for (const entry of entries) {
36
+ if (!entry.isIntersecting) continue
37
+ observer.unobserve(entry.target)
38
+ const iframe = entry.target.querySelector("iframe")
39
+ const src = iframe?.getAttribute("data-src")
40
+ if (!iframe || !src || iframe.hasAttribute("src")) continue
41
+ this.#queue.push({ iframe, src })
42
+ this.#pump()
43
+ }
44
+ }, { root, rootMargin: "150px" })
45
+
46
+ const resize = new ResizeObserver((entries) => {
47
+ for (const entry of entries) {
48
+ if (entry.target instanceof HTMLElement) this.#fit(entry.target)
49
+ }
50
+ })
51
+
52
+ this.#observer = observer
53
+ this.#resize = resize
54
+ for (const thumb of this.#thumbs) {
55
+ observer.observe(thumb)
56
+ resize.observe(thumb)
57
+ }
58
+
59
+ return () => {
60
+ observer.disconnect()
61
+ resize.disconnect()
62
+ this.#observer = null
63
+ this.#resize = null
64
+ this.#reset()
65
+ }
66
+ })
67
+
68
+ return () => {
69
+ stop()
70
+ this.#thumbs.clear()
71
+ }
72
+ }
73
+
74
+ watch(thumb: HTMLElement | null): void | (() => void) {
75
+ if (!thumb) return
76
+
77
+ this.#thumbs.add(thumb)
78
+ this.#observer?.observe(thumb)
79
+ this.#resize?.observe(thumb)
80
+ this.#fit(thumb)
81
+
82
+ return () => {
83
+ this.#thumbs.delete(thumb)
84
+ this.#observer?.unobserve(thumb)
85
+ this.#resize?.unobserve(thumb)
86
+
87
+ const iframe = thumb.querySelector("iframe")
88
+ if (!iframe) return
89
+ this.#queue = this.#queue.filter((item) => item.iframe !== iframe)
90
+ const load = this.#loads.get(iframe)
91
+ if (!load) return
92
+ iframe.removeEventListener("load", load)
93
+ this.#loads.delete(iframe)
94
+ this.#active = Math.max(0, this.#active - 1)
95
+ this.#pump()
96
+ }
97
+ }
98
+
99
+ #pump(): void {
100
+ while (this.#active < MAX_PREVIEWS && this.#queue.length) {
101
+ const item = this.#queue.shift()
102
+ if (!item || !item.iframe.isConnected) continue
103
+ this.#active++
104
+
105
+ const load = () => {
106
+ this.#loads.delete(item.iframe)
107
+ this.#active = Math.max(0, this.#active - 1)
108
+ this.#pump()
109
+ }
110
+
111
+ this.#loads.set(item.iframe, load)
112
+ item.iframe.addEventListener("load", load, { once: true })
113
+ item.iframe.src = item.src
114
+ }
115
+ }
116
+
117
+ #fit(thumb: HTMLElement): void {
118
+ const iframe = thumb.querySelector("iframe")
119
+ if (!iframe || !thumb.clientWidth) return
120
+
121
+ const scale = thumb.clientWidth / THUMB_W
122
+ iframe.style.width = `${THUMB_W}px`
123
+ iframe.style.height = `${Math.round(thumb.clientHeight / scale)}px`
124
+ iframe.style.transform = `scale(${scale})`
125
+ }
126
+
127
+ #reset(): void {
128
+ this.#queue.length = 0
129
+ this.#active = 0
130
+ for (const [iframe, load] of this.#loads)
131
+ iframe.removeEventListener("load", load)
132
+ this.#loads.clear()
133
+ }
134
+ }
@@ -0,0 +1,25 @@
1
+ import { useEffect, useLayoutEffect, useState } from "react"
2
+
3
+ export interface Subscribable {
4
+ subscribe(): (() => void) | void
5
+ }
6
+
7
+ /** Create a model once and run its `subscribe()`. */
8
+ export function useModel<T extends object>(create: () => T): T {
9
+ const [model] = useState(create)
10
+ useEffect(() => subscribe(model), [model])
11
+ return model
12
+ }
13
+
14
+ /** Create a model once and run its `subscribe()` before paint. */
15
+ export function useLayoutModel<T extends object>(create: () => T): T {
16
+ const [model] = useState(create)
17
+ useLayoutEffect(() => subscribe(model), [model])
18
+ return model
19
+ }
20
+
21
+ function subscribe(model: object): (() => void) | void {
22
+ const subscribable = model as Partial<Subscribable>
23
+ if (typeof subscribable.subscribe !== "function") return
24
+ return subscribable.subscribe()
25
+ }
@@ -0,0 +1,55 @@
1
+ import { createElement } from "react"
2
+ import { createRoot } from "react-dom/client"
3
+ import { createDisposables } from "../../widget/lib/disposables.js"
4
+ import { registerTocCommands, registerTocDock } from "./commands.js"
5
+ import { TocModel } from "./model.js"
6
+ import { startScrollSpy } from "./scroll-spy.js"
7
+ import { TocPanel } from "./ui/TocPanel.js"
8
+
9
+ /**
10
+ * @returns {DocservePlugin}
11
+ */
12
+ export function tocPlugin() {
13
+ return {
14
+ id: "toc",
15
+ setup(ctx) {
16
+ // state
17
+ const html = document.documentElement
18
+ const model = TocModel.create(ctx.rpc)
19
+ const cleanup = createDisposables()
20
+
21
+ // styles
22
+ ctx.ui.style("/__docserve/plugins/toc/toc.css")
23
+
24
+ // panel
25
+ const mount = ctx.ui.mountPoint()
26
+ const root = createRoot(mount)
27
+ root.render(createElement(TocPanel, { model }))
28
+ cleanup.add(() => {
29
+ root.unmount()
30
+ mount.remove()
31
+ })
32
+ cleanup.add(model.subscribe())
33
+
34
+ // open state
35
+ cleanup.add(model.open.subscribe(() => {
36
+ html.toggleAttribute("data-docserve-panel-right", model.open.value)
37
+ }))
38
+
39
+ // commands
40
+ cleanup.add(registerTocCommands(ctx, model))
41
+ cleanup.add(registerTocDock(ctx, model))
42
+
43
+ // scroll spy
44
+ cleanup.add(startScrollSpy(model))
45
+
46
+ // teardown
47
+ cleanup.add(() => html.removeAttribute("data-docserve-panel-right"))
48
+
49
+ // data
50
+ model.load()
51
+
52
+ return cleanup.dispose
53
+ },
54
+ }
55
+ }
@@ -0,0 +1,49 @@
1
+ import ICON_TOC_RAW from "~icons/lucide/list-tree?raw&width=18&height=18"
2
+ import { iconSvg } from "../../widget/lib/dom.js"
3
+ import type { TocModel } from "./model.js"
4
+
5
+ const ICON_TOC = iconSvg(ICON_TOC_RAW)
6
+
7
+ export function registerTocCommands(ctx: DocserveContext, model: TocModel): () => void {
8
+ const offToggle = ctx.commands.register({
9
+ id: "plugin:toc:toggle",
10
+ title: "Toggle table of contents",
11
+ category: "View",
12
+ icon: ICON_TOC,
13
+ keys: ["t"],
14
+ run: () => model.toggle(),
15
+ })
16
+
17
+ const offClose = ctx.commands.register({
18
+ id: "plugin:toc:close",
19
+ title: "Close table of contents",
20
+ keys: ["Escape"],
21
+ showInPalette: false,
22
+ when: () => model.open.value,
23
+ run: () => model.setOpen(false),
24
+ })
25
+
26
+ return () => {
27
+ offClose()
28
+ offToggle()
29
+ }
30
+ }
31
+
32
+ export function registerTocDock(ctx: DocserveContext, model: TocModel): () => void {
33
+ const dock = ctx.docks.register({
34
+ id: "toc",
35
+ title: "Toggle table of contents",
36
+ icon: ICON_TOC,
37
+ category: "main",
38
+ order: 1,
39
+ command: "plugin:toc:toggle",
40
+ isActive: () => model.open.value,
41
+ })
42
+
43
+ const offOpen = model.open.subscribe(() => dock.update())
44
+
45
+ return () => {
46
+ offOpen()
47
+ dock.dispose()
48
+ }
49
+ }
@@ -0,0 +1,40 @@
1
+ const BLOCKED = [
2
+ "script",
3
+ "style",
4
+ "link",
5
+ "iframe",
6
+ "object",
7
+ "embed",
8
+ "button",
9
+ "input",
10
+ "select",
11
+ "textarea",
12
+ "template",
13
+ ]
14
+
15
+ export function headingHtml(element: HTMLHeadingElement): string {
16
+ const clone = element.cloneNode(true) as HTMLElement
17
+
18
+ for (const node of [clone, ...clone.querySelectorAll("*")]) {
19
+ node.removeAttribute("id")
20
+ node.removeAttribute("tabindex")
21
+ node.removeAttribute("contenteditable")
22
+ for (const attribute of [...node.attributes]) {
23
+ if (attribute.name.toLowerCase().startsWith("on"))
24
+ node.removeAttribute(attribute.name)
25
+ }
26
+ }
27
+
28
+ for (const anchor of [...clone.querySelectorAll("a")])
29
+ anchor.replaceWith(...anchor.childNodes)
30
+
31
+ for (const blocked of clone.querySelectorAll(BLOCKED.join(",")))
32
+ blocked.remove()
33
+
34
+ for (const icon of clone.querySelectorAll("iconify-icon, svg, img")) {
35
+ icon.removeAttribute("width")
36
+ icon.removeAttribute("height")
37
+ }
38
+
39
+ return clone.innerHTML
40
+ }
@@ -0,0 +1,178 @@
1
+ import { effect, signal } from "@preact/signals-react"
2
+ import type { MouseEvent } from "react"
3
+ import { persistedBool } from "../../widget/lib/persisted-signal.js"
4
+ import { headingHtml } from "./heading-html.js"
5
+ import { buildTree, collectOutline } from "./outline.js"
6
+
7
+ export const HEADING_OFFSET = 88
8
+
9
+ export interface TocEntry {
10
+ element: HTMLHeadingElement
11
+ id: string
12
+ level: number
13
+ html: string
14
+ children: TocEntry[]
15
+ }
16
+
17
+ type OutlineNode = ReturnType<typeof buildTree>[number]
18
+
19
+ export class TocModel {
20
+ readonly open: ReturnType<typeof persistedBool>
21
+ readonly headings = signal<HTMLHeadingElement[]>([])
22
+ readonly tree = signal<TocEntry[]>([])
23
+ readonly activeId = signal<string | null>(null)
24
+ readonly marker = signal<HTMLElement | null>(null)
25
+ readonly scroll = signal<HTMLElement | null>(null)
26
+
27
+ #links = new Map<string, HTMLAnchorElement>()
28
+ #linkRefs = new Map<string, (element: HTMLAnchorElement | null) => void>()
29
+ #rpc?: RpcContext
30
+
31
+ constructor(defaultOpen = false, rpc?: RpcContext) {
32
+ this.open = persistedBool("docserve:toc:open", defaultOpen)
33
+ this.#rpc = rpc
34
+ }
35
+
36
+ static create(rpc?: RpcContext): TocModel {
37
+ const source = document.body ?? document.documentElement
38
+ return new TocModel(source?.hasAttribute("data-toc-open") ?? false, rpc)
39
+ }
40
+
41
+ load(): void {
42
+ this.#links.clear()
43
+ this.#linkRefs.clear()
44
+
45
+ const { headings } = collectOutline(document)
46
+ this.headings.value = headings
47
+ this.tree.value = buildEntries(buildTree(headings))
48
+ this.activeId.value = null
49
+ this.layout()
50
+ }
51
+
52
+ toggle(): void {
53
+ this.setOpen(!this.open.value)
54
+ }
55
+
56
+ setOpen(next: boolean): void {
57
+ this.open.value = next
58
+ if (!next) return
59
+
60
+ this.layout()
61
+ const link = this.activeId.value ? this.#links.get(this.activeId.value) : null
62
+ if (link) this.#reveal(link)
63
+ }
64
+
65
+ close(): void {
66
+ this.setOpen(false)
67
+ }
68
+
69
+ setActive(id: string | null): void {
70
+ if (id === this.activeId.value) return
71
+
72
+ this.activeId.value = id
73
+ this.layout()
74
+
75
+ const link = id ? this.#links.get(id) : null
76
+ if (link) this.#reveal(link)
77
+ }
78
+
79
+ navigate(event: MouseEvent<HTMLAnchorElement>, element: HTMLHeadingElement): void {
80
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return
81
+ event.preventDefault()
82
+ void this.#navigateTo(element)
83
+ }
84
+
85
+ async #navigateTo(element: HTMLHeadingElement): Promise<void> {
86
+ if (this.#rpc?.has("plugin:collapse:expand-ancestors")) {
87
+ try {
88
+ await this.#rpc.call("plugin:collapse:expand-ancestors", element.id)
89
+ } catch {}
90
+ }
91
+
92
+ const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches
93
+ const top = window.scrollY + element.getBoundingClientRect().top - HEADING_OFFSET
94
+
95
+ window.scrollTo({ top: Math.max(0, top), behavior: reduce ? "auto" : "smooth" })
96
+ history.replaceState(null, "", `#${element.id}`)
97
+ this.setActive(element.id)
98
+ }
99
+
100
+ layout(): void {
101
+ const marker = this.marker.value
102
+ if (!marker) return
103
+
104
+ const active = this.activeId.value ? this.#links.get(this.activeId.value) : null
105
+ if (!active) {
106
+ marker.style.opacity = "0"
107
+ return
108
+ }
109
+
110
+ const top = active.offsetTop + (active.offsetHeight - marker.offsetHeight) / 2
111
+ marker.style.transform = `translateY(${top}px)`
112
+ marker.style.opacity = "1"
113
+ }
114
+
115
+ linkRef(id: string): (element: HTMLAnchorElement | null) => void {
116
+ let ref = this.#linkRefs.get(id)
117
+ if (!ref) {
118
+ ref = (element) => {
119
+ if (element) {
120
+ this.#links.set(id, element)
121
+ if (id === this.activeId.value) this.#reveal(element)
122
+ } else {
123
+ this.#links.delete(id)
124
+ }
125
+ this.layout()
126
+ }
127
+ this.#linkRefs.set(id, ref)
128
+ }
129
+ return ref
130
+ }
131
+
132
+ readonly setMarker = (element: HTMLElement | null): void => {
133
+ this.marker.value = element
134
+ this.layout()
135
+ }
136
+
137
+ readonly setScroll = (element: HTMLElement | null): void => {
138
+ this.scroll.value = element
139
+ const link = this.activeId.value ? this.#links.get(this.activeId.value) : null
140
+ if (link) this.#reveal(link)
141
+ }
142
+
143
+ subscribe(): () => void {
144
+ if (typeof ResizeObserver !== "function") return () => {}
145
+
146
+ return effect(() => {
147
+ const marker = this.marker.value
148
+ const target = marker?.parentElement
149
+ if (!target) return
150
+
151
+ const observer = new ResizeObserver(() => this.layout())
152
+ observer.observe(target)
153
+ return () => observer.disconnect()
154
+ })
155
+ }
156
+
157
+ #reveal(link: HTMLAnchorElement): void {
158
+ const scroll = this.scroll.value
159
+ if (!scroll || !this.open.value) return
160
+
161
+ const top = link.offsetTop
162
+ const bottom = top + link.offsetHeight
163
+ if (top < scroll.scrollTop + 4)
164
+ scroll.scrollTop = Math.max(0, top - 8)
165
+ else if (bottom > scroll.scrollTop + scroll.clientHeight - 4)
166
+ scroll.scrollTop = bottom - scroll.clientHeight + 8
167
+ }
168
+ }
169
+
170
+ function buildEntries(nodes: OutlineNode[]): TocEntry[] {
171
+ return nodes.map((node) => ({
172
+ element: node.element,
173
+ id: node.element.id,
174
+ level: node.level,
175
+ html: headingHtml(node.element),
176
+ children: buildEntries(node.children),
177
+ }))
178
+ }
@@ -0,0 +1,94 @@
1
+ import {
2
+ buildTree,
3
+ collectHeadings as collect,
4
+ ensureIds,
5
+ findRoot as find,
6
+ slugify,
7
+ } from "../../widget/lib/headings.js"
8
+
9
+ export { buildTree, ensureIds, slugify }
10
+
11
+ const DEFAULT_RANGE = [2, 3]
12
+ const EXCLUDED = "nav, aside, header, footer, [data-toc-ignore]"
13
+ const ROOT_ATTRIBUTE = "data-toc-root"
14
+
15
+ /**
16
+ * @typedef {{ root: HTMLElement | null, range: [number, number] | null, headings: HTMLHeadingElement[] }} TocOutline
17
+ */
18
+
19
+ /**
20
+ * Resolve the page root, its outline range and its headings.
21
+ * @param {Document} [doc]
22
+ * @returns {TocOutline}
23
+ */
24
+ export function collectOutline(doc = document) {
25
+ const root = findRoot(doc)
26
+ const source = doc.body ?? doc.documentElement
27
+ if (!root || !source) return { root: null, range: null, headings: [] }
28
+
29
+ const raw = root.getAttribute("data-toc-outline") ?? source.getAttribute("data-toc-outline")
30
+ const range = resolveRange(parseOutline(raw))
31
+ if (!range) return { root, range: null, headings: [] }
32
+
33
+ const headings = collectHeadings(root, range)
34
+ ensureIds(headings, doc)
35
+
36
+ return { root, range, headings }
37
+ }
38
+
39
+ /**
40
+ * Content root for the TOC.
41
+ * @param {Document} [doc]
42
+ * @returns {HTMLElement | null}
43
+ */
44
+ export function findRoot(doc = document) {
45
+ return find(doc, ROOT_ATTRIBUTE)
46
+ }
47
+
48
+ /**
49
+ * `data-toc-outline` → `[min, max] | "deep" | false`.
50
+ * @param {string | null | undefined} value
51
+ * @returns {number | number[] | "deep" | false}
52
+ */
53
+ export function parseOutline(value) {
54
+ if (value == null || value.trim() === "") return [...DEFAULT_RANGE]
55
+ if (value === "deep") return "deep"
56
+ if (value === "false") return false
57
+
58
+ const levels = value.split(",").map((part) => Number(part.trim())).filter(Number.isFinite)
59
+ if (!levels.length) return [...DEFAULT_RANGE]
60
+ return levels.length > 1 ? levels : levels[0]
61
+ }
62
+
63
+ /**
64
+ * Normalize an outline setting to an inclusive heading-level range.
65
+ * @param {number | number[] | "deep" | false | { level?: number | number[] | "deep" } | null | undefined} outline
66
+ * @returns {[number, number] | null}
67
+ */
68
+ export function resolveRange(outline) {
69
+ if (outline === false) return null
70
+
71
+ const value = (outline && typeof outline === "object" && !Array.isArray(outline) ? outline.level : outline) ?? DEFAULT_RANGE
72
+
73
+ if (Array.isArray(value)) {
74
+ const min = Number(value[0])
75
+ const max = Number(value[1])
76
+ if (!Number.isFinite(min) || !Number.isFinite(max)) return [2, 3]
77
+ return min <= max ? [min, max] : [max, min]
78
+ }
79
+
80
+ if (value === "deep") return [2, 6]
81
+
82
+ const level = Number(value)
83
+ return Number.isFinite(level) ? [level, level] : [2, 3]
84
+ }
85
+
86
+ /**
87
+ * Headings inside `root` whose level falls in `range`, in document order.
88
+ * @param {HTMLElement | null} root
89
+ * @param {[number, number] | null} range
90
+ * @returns {HTMLHeadingElement[]}
91
+ */
92
+ export function collectHeadings(root, range) {
93
+ return collect(root, range, EXCLUDED)
94
+ }