@noy4/docserve 0.3.3 → 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.
@@ -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
+ }
@@ -0,0 +1,35 @@
1
+ import type { TocModel } from "./model.js"
2
+ import { HEADING_OFFSET } from "./model.js"
3
+
4
+ export function startScrollSpy(model: TocModel, offset = HEADING_OFFSET): () => void {
5
+ const controller = new AbortController()
6
+ let frame = 0
7
+
8
+ window.addEventListener("scroll", schedule, { passive: true, signal: controller.signal })
9
+ window.addEventListener("resize", schedule, { passive: true, signal: controller.signal })
10
+
11
+ schedule()
12
+
13
+ return () => {
14
+ controller.abort()
15
+ if (frame) cancelAnimationFrame(frame)
16
+ }
17
+
18
+ function schedule(): void {
19
+ if (frame) return
20
+ frame = requestAnimationFrame(() => {
21
+ frame = 0
22
+ update()
23
+ })
24
+ }
25
+
26
+ function update(): void {
27
+ const headings = model.headings.value
28
+ let current = headings[0] ?? null
29
+ for (const heading of headings) {
30
+ if (heading.getBoundingClientRect().top > offset) break
31
+ current = heading
32
+ }
33
+ model.setActive(current?.id ?? null)
34
+ }
35
+ }
@@ -0,0 +1,214 @@
1
+ .docserve-toc,
2
+ .docserve-toc * {
3
+ box-sizing: border-box;
4
+ }
5
+
6
+ .docserve-toc {
7
+ position: fixed;
8
+ top: 96px;
9
+ left: max(16px, calc(100% - var(--docserve-panel-right, 0px)));
10
+ z-index: 1;
11
+ display: flex;
12
+ flex-direction: column;
13
+ width: 200px;
14
+ max-height: calc(100vh - 128px);
15
+ color: var(--docserve-panel-text);
16
+ font-size: 12px;
17
+ line-height: 1.5;
18
+ opacity: 0;
19
+ visibility: hidden;
20
+ transform: translateX(12px);
21
+ transition:
22
+ opacity 0.18s ease,
23
+ transform 0.18s ease,
24
+ visibility 0.18s ease;
25
+ }
26
+
27
+ .docserve-toc[data-open] {
28
+ opacity: 1;
29
+ visibility: visible;
30
+ transform: translateX(0);
31
+ }
32
+
33
+ .docserve-toc__head {
34
+ display: flex;
35
+ flex-shrink: 0;
36
+ align-items: center;
37
+ justify-content: space-between;
38
+ gap: 8px;
39
+ padding: 0 0 8px;
40
+ }
41
+
42
+ .docserve-toc__title {
43
+ min-width: 0;
44
+ overflow: hidden;
45
+ color: var(--docserve-panel-text);
46
+ font-size: 14px;
47
+ font-weight: 600;
48
+ text-overflow: ellipsis;
49
+ white-space: nowrap;
50
+ }
51
+
52
+ .docserve-toc__close {
53
+ display: grid;
54
+ flex-shrink: 0;
55
+ place-items: center;
56
+ width: 22px;
57
+ height: 22px;
58
+ padding: 0;
59
+ border: 0;
60
+ border-radius: 6px;
61
+ background: transparent;
62
+ color: var(--docserve-panel-muted);
63
+ font: inherit;
64
+ line-height: 0;
65
+ opacity: 0;
66
+ visibility: hidden;
67
+ appearance: none;
68
+ transition:
69
+ opacity 0.15s ease,
70
+ visibility 0.15s ease,
71
+ background-color 0.15s ease,
72
+ color 0.15s ease;
73
+ }
74
+
75
+ .docserve-toc:hover .docserve-toc__close,
76
+ .docserve-toc:focus-within .docserve-toc__close {
77
+ opacity: 1;
78
+ visibility: visible;
79
+ }
80
+
81
+ .docserve-toc__close svg {
82
+ width: 14px;
83
+ height: 14px;
84
+ }
85
+
86
+ .docserve-toc__close:hover {
87
+ background: color-mix(in srgb, var(--docserve-panel-text) 8%, transparent);
88
+ color: var(--docserve-panel-text);
89
+ }
90
+
91
+ .docserve-toc__close:focus-visible {
92
+ outline: 2px solid var(--docserve-dock-accent);
93
+ outline-offset: 2px;
94
+ }
95
+
96
+ .docserve-toc__scroll {
97
+ flex: 1;
98
+ min-height: 0;
99
+ padding: 0 4px 4px 0;
100
+ overflow-x: hidden;
101
+ overflow-y: auto;
102
+ overscroll-behavior: contain;
103
+ scrollbar-width: thin;
104
+ }
105
+
106
+ .docserve-toc__scroll::-webkit-scrollbar {
107
+ width: 8px;
108
+ }
109
+
110
+ .docserve-toc__scroll::-webkit-scrollbar-thumb {
111
+ border: 2px solid transparent;
112
+ border-radius: 999px;
113
+ background: color-mix(in srgb, var(--docserve-panel-muted) 40%, transparent);
114
+ background-clip: content-box;
115
+ }
116
+
117
+ .docserve-toc__content {
118
+ position: relative;
119
+ border-left: 1px solid var(--docserve-panel-border);
120
+ }
121
+
122
+ .docserve-toc__marker {
123
+ position: absolute;
124
+ top: 0;
125
+ left: -1px;
126
+ width: 2px;
127
+ height: 18px;
128
+ border-radius: 2px;
129
+ background: var(--docserve-dock-accent);
130
+ opacity: 0;
131
+ pointer-events: none;
132
+ transition:
133
+ transform 0.25s cubic-bezier(0, 1, 0.5, 1),
134
+ opacity 0.15s ease;
135
+ }
136
+
137
+ .docserve-toc__list {
138
+ margin: 0;
139
+ padding: 0;
140
+ list-style: none;
141
+ }
142
+
143
+ .docserve-toc__list .docserve-toc__list {
144
+ padding-left: 12px;
145
+ }
146
+
147
+ .docserve-toc__link {
148
+ display: block;
149
+ padding: 3px 8px 3px 11px;
150
+ overflow-wrap: anywhere;
151
+ border-radius: 0 5px 5px 0;
152
+ color: var(--docserve-panel-muted);
153
+ font-size: 12px;
154
+ line-height: 1.5;
155
+ text-decoration: none;
156
+ transition: background-color 0.15s ease, color 0.15s ease;
157
+ }
158
+
159
+ .docserve-toc__link[data-level="2"] {
160
+ font-size: 12.5px;
161
+ }
162
+
163
+ .docserve-toc__link[data-level="3"] {
164
+ font-size: 11.5px;
165
+ }
166
+
167
+ .docserve-toc__link[data-level="4"],
168
+ .docserve-toc__link[data-level="5"],
169
+ .docserve-toc__link[data-level="6"] {
170
+ font-size: 11px;
171
+ }
172
+
173
+ .docserve-toc__link iconify-icon,
174
+ .docserve-toc__link svg,
175
+ .docserve-toc__link img {
176
+ display: inline-block;
177
+ width: 13px;
178
+ height: 13px;
179
+ margin-right: 5px;
180
+ vertical-align: -2px;
181
+ color: inherit;
182
+ }
183
+
184
+ .docserve-toc__link:hover {
185
+ background: color-mix(in srgb, var(--docserve-panel-text) 6%, transparent);
186
+ color: var(--docserve-panel-text);
187
+ }
188
+
189
+ .docserve-toc__link.is-active {
190
+ background: color-mix(in srgb, var(--docserve-dock-accent) 10%, transparent);
191
+ color: var(--docserve-dock-accent);
192
+ }
193
+
194
+ .docserve-toc__link:focus-visible {
195
+ outline: 2px solid var(--docserve-dock-accent);
196
+ outline-offset: -1px;
197
+ }
198
+
199
+ .docserve-toc__empty {
200
+ margin: 0;
201
+ padding: 4px 0;
202
+ color: var(--docserve-panel-muted);
203
+ font-size: 12px;
204
+ line-height: 1.5;
205
+ }
206
+
207
+ @media (prefers-reduced-motion: reduce) {
208
+ .docserve-toc,
209
+ .docserve-toc__marker,
210
+ .docserve-toc__link,
211
+ .docserve-toc__close {
212
+ transition: none;
213
+ }
214
+ }
@@ -0,0 +1,87 @@
1
+ import ICON_CLOSE_RAW from "~icons/lucide/x?raw&width=16&height=16"
2
+ import { iconSvg } from "../../../widget/lib/dom.js"
3
+ import type { TocEntry, TocModel } from "../model.js"
4
+
5
+ const ICON_CLOSE = iconSvg(ICON_CLOSE_RAW)
6
+
7
+ export interface TocPanelProps {
8
+ model: TocModel
9
+ }
10
+
11
+ export function TocPanel({ model }: TocPanelProps) {
12
+ const open = model.open.value
13
+ const tree = model.tree.value
14
+ const active = model.activeId.value
15
+
16
+ return (
17
+ <aside className="docserve-toc" data-open={open ? "" : undefined} aria-label="Table of contents">
18
+ <header className="docserve-toc__head">
19
+ <span className="docserve-toc__title">On this page</span>
20
+ <button
21
+ type="button"
22
+ className="docserve-toc__close"
23
+ title="Close table of contents"
24
+ aria-label="Close table of contents"
25
+ onClick={() => model.close()}
26
+ dangerouslySetInnerHTML={{ __html: ICON_CLOSE }}
27
+ />
28
+ </header>
29
+ <nav className="docserve-toc__scroll" ref={model.setScroll} aria-label="On this page">
30
+ <div className="docserve-toc__content">
31
+ <div className="docserve-toc__marker" ref={model.setMarker} aria-hidden="true" />
32
+ {tree.length
33
+ ? <TocList model={model} nodes={tree} active={active} />
34
+ : <p className="docserve-toc__empty">No headings on this page</p>}
35
+ </div>
36
+ </nav>
37
+ </aside>
38
+ )
39
+ }
40
+
41
+ interface TocListProps {
42
+ model: TocModel
43
+ nodes: TocEntry[]
44
+ active: string | null
45
+ }
46
+
47
+ function TocList({ model, nodes, active }: TocListProps) {
48
+ return (
49
+ <ul className="docserve-toc__list">
50
+ {nodes.map((node, index) => (
51
+ <TocItem
52
+ key={`${node.id}:${index}`}
53
+ model={model}
54
+ entry={node}
55
+ active={active}
56
+ />
57
+ ))}
58
+ </ul>
59
+ )
60
+ }
61
+
62
+ interface TocItemProps {
63
+ model: TocModel
64
+ entry: TocEntry
65
+ active: string | null
66
+ }
67
+
68
+ function TocItem({ model, entry, active }: TocItemProps) {
69
+ const isActive = entry.id === active
70
+
71
+ return (
72
+ <li className="docserve-toc__item">
73
+ <a
74
+ ref={model.linkRef(entry.id)}
75
+ className={isActive ? "docserve-toc__link is-active" : "docserve-toc__link"}
76
+ href={`#${entry.id}`}
77
+ data-level={entry.level}
78
+ aria-current={isActive ? "location" : undefined}
79
+ onClick={(event) => model.navigate(event, entry.element)}
80
+ dangerouslySetInnerHTML={{ __html: entry.html }}
81
+ />
82
+ {entry.children.length
83
+ ? <TocList model={model} nodes={entry.children} active={active} />
84
+ : null}
85
+ </li>
86
+ )
87
+ }
@@ -1,10 +1,18 @@
1
1
  // Widget entry: register the built-in plugins, then start.
2
+ import { collapsePlugin } from "../plugins/collapse/client.js"
2
3
  import { copyPlugin } from "../plugins/copy/client.js"
3
4
  import { homePlugin } from "../plugins/home/client.js"
4
5
  import { sidebarPlugin } from "../plugins/sidebar/client.js"
6
+ import { tocPlugin } from "../plugins/toc/client.js"
5
7
  import { createHost } from "./host.js"
6
8
 
7
- const PLUGINS = [sidebarPlugin, homePlugin, copyPlugin]
9
+ const PLUGINS = [
10
+ homePlugin,
11
+ collapsePlugin,
12
+ copyPlugin,
13
+ sidebarPlugin,
14
+ tocPlugin,
15
+ ]
8
16
 
9
17
  // The server skips iframe previews; this guard covers pages served some other way.
10
18
  if (window.self === window.top && !document.getElementById("docserve-dock-host")) {