methanol 0.0.0 → 0.0.2

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 (48) hide show
  1. package/LICENSE +203 -0
  2. package/README.md +58 -0
  3. package/banner.txt +6 -0
  4. package/bin/methanol.js +24 -0
  5. package/index.js +22 -0
  6. package/package.json +51 -9
  7. package/src/assets.js +30 -0
  8. package/src/build-system.js +200 -0
  9. package/src/components.js +145 -0
  10. package/src/config.js +396 -0
  11. package/src/dev-server.js +632 -0
  12. package/src/main.js +133 -0
  13. package/src/mdx.js +406 -0
  14. package/src/node-loader.js +88 -0
  15. package/src/pagefind.js +107 -0
  16. package/src/pages.js +771 -0
  17. package/src/preview-server.js +58 -0
  18. package/src/public-assets.js +73 -0
  19. package/src/register-loader.js +29 -0
  20. package/src/rehype-plugins/link-resolve.js +116 -0
  21. package/src/rehype-plugins/methanol-ctx.js +89 -0
  22. package/src/renderer.js +25 -0
  23. package/src/rewind.js +117 -0
  24. package/src/stage-logger.js +59 -0
  25. package/src/state.js +179 -0
  26. package/src/virtual-module/inject.js +30 -0
  27. package/src/virtual-module/loader.js +116 -0
  28. package/src/virtual-module/pagefind.js +108 -0
  29. package/src/vite-plugins.js +173 -0
  30. package/themes/default/components/ThemeAccentSwitch.client.jsx +95 -0
  31. package/themes/default/components/ThemeAccentSwitch.static.jsx +23 -0
  32. package/themes/default/components/ThemeColorSwitch.client.jsx +95 -0
  33. package/themes/default/components/ThemeColorSwitch.static.jsx +23 -0
  34. package/themes/default/components/ThemeSearchBox.client.jsx +324 -0
  35. package/themes/default/components/ThemeSearchBox.static.jsx +40 -0
  36. package/themes/default/components/ThemeToCContainer.client.jsx +154 -0
  37. package/themes/default/components/ThemeToCContainer.static.jsx +61 -0
  38. package/themes/default/components/pre.client.jsx +84 -0
  39. package/themes/default/components/pre.static.jsx +27 -0
  40. package/themes/default/heading.jsx +35 -0
  41. package/themes/default/index.js +41 -0
  42. package/themes/default/page.jsx +303 -0
  43. package/themes/default/pages/404.mdx +8 -0
  44. package/themes/default/pages/index.mdx +31 -0
  45. package/themes/default/public/favicon.png +0 -0
  46. package/themes/default/public/logo.png +0 -0
  47. package/themes/default/sources/prefetch.js +49 -0
  48. package/themes/default/sources/style.css +1660 -0
@@ -0,0 +1,23 @@
1
+ /* Copyright Yukino Song, SudoMaker Ltd.
2
+ *
3
+ * Licensed to the Apache Software Foundation (ASF) under one
4
+ * or more contributor license agreements. See the NOTICE file
5
+ * distributed with this work for additional information
6
+ * regarding copyright ownership. The ASF licenses this file
7
+ * to you under the Apache License, Version 2.0 (the
8
+ * "License"); you may not use this file except in compliance
9
+ * with the License. You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing,
14
+ * software distributed under the License is distributed on an
15
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ * KIND, either express or implied. See the License for the
17
+ * specific language governing permissions and limitations
18
+ * under the License.
19
+ */
20
+
21
+ export default function () {
22
+ // render nothing on server side
23
+ }
@@ -0,0 +1,95 @@
1
+ /* Copyright Yukino Song, SudoMaker Ltd.
2
+ *
3
+ * Licensed to the Apache Software Foundation (ASF) under one
4
+ * or more contributor license agreements. See the NOTICE file
5
+ * distributed with this work for additional information
6
+ * regarding copyright ownership. The ASF licenses this file
7
+ * to you under the Apache License, Version 2.0 (the
8
+ * "License"); you may not use this file except in compliance
9
+ * with the License. You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing,
14
+ * software distributed under the License is distributed on an
15
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ * KIND, either express or implied. See the License for the
17
+ * specific language governing permissions and limitations
18
+ * under the License.
19
+ */
20
+
21
+ import { signal, $ } from 'refui'
22
+
23
+ const LightIcon = () => (
24
+ <svg
25
+ attr:width="18"
26
+ attr:height="18"
27
+ attr:viewBox="0 0 24 24"
28
+ attr:fill="none"
29
+ attr:stroke="currentColor"
30
+ attr:stroke-width="2"
31
+ attr:stroke-linecap="round"
32
+ attr:stroke-linejoin="round"
33
+ >
34
+ <circle attr:cx="12" attr:cy="12" attr:r="5"></circle>
35
+ <line attr:x1="12" attr:y1="1" attr:x2="12" attr:y2="3"></line>
36
+ <line attr:x1="12" attr:y1="21" attr:x2="12" attr:y2="23"></line>
37
+ <line attr:x1="4.22" attr:y1="4.22" attr:x2="5.64" attr:y2="5.64"></line>
38
+ <line attr:x1="18.36" attr:y1="18.36" attr:x2="19.78" attr:y2="19.78"></line>
39
+ <line attr:x1="1" attr:y1="12" attr:x2="3" attr:y2="12"></line>
40
+ <line attr:x1="21" attr:y1="12" attr:x2="23" attr:y2="12"></line>
41
+ <line attr:x1="4.22" attr:y1="19.78" attr:x2="5.64" attr:y2="18.36"></line>
42
+ <line attr:x1="18.36" attr:y1="5.64" attr:x2="19.78" attr:y2="4.22"></line>
43
+ </svg>
44
+ )
45
+
46
+ const DarkIcon = () => (
47
+ <svg
48
+ attr:width="18"
49
+ attr:height="18"
50
+ attr:viewBox="0 0 24 24"
51
+ attr:fill="none"
52
+ attr:stroke="currentColor"
53
+ attr:stroke-width="2"
54
+ attr:stroke-linecap="round"
55
+ attr:stroke-linejoin="round"
56
+ >
57
+ <path attr:d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
58
+ </svg>
59
+ )
60
+
61
+ export default function () {
62
+ const theme = signal('dark')
63
+
64
+ // Initialize theme from localStorage or system preference
65
+ if (typeof window !== 'undefined') {
66
+ const savedTheme = localStorage.getItem('methanol-theme')
67
+ const systemTheme = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'
68
+ theme.value = savedTheme || systemTheme
69
+ document.documentElement.classList.toggle('light', theme.value === 'light')
70
+ document.documentElement.classList.toggle('dark', theme.value === 'dark')
71
+ }
72
+
73
+ const toggle = () => {
74
+ theme.value = theme.value === 'light' ? 'dark' : 'light'
75
+ localStorage.setItem('methanol-theme', theme.value)
76
+ document.documentElement.classList.toggle('light', theme.value === 'light')
77
+ document.documentElement.classList.toggle('dark', theme.value === 'dark')
78
+ }
79
+
80
+ const CurrentIcon = $(() => {
81
+ if (theme.value === 'light') {
82
+ return LightIcon
83
+ } else {
84
+ return DarkIcon
85
+ }
86
+ })
87
+
88
+ return (
89
+ <div class="theme-switch-container">
90
+ <button class="theme-switch-btn" on:click={toggle} attr:aria-label="Toggle theme">
91
+ <CurrentIcon />
92
+ </button>
93
+ </div>
94
+ )
95
+ }
@@ -0,0 +1,23 @@
1
+ /* Copyright Yukino Song, SudoMaker Ltd.
2
+ *
3
+ * Licensed to the Apache Software Foundation (ASF) under one
4
+ * or more contributor license agreements. See the NOTICE file
5
+ * distributed with this work for additional information
6
+ * regarding copyright ownership. The ASF licenses this file
7
+ * to you under the Apache License, Version 2.0 (the
8
+ * "License"); you may not use this file except in compliance
9
+ * with the License. You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing,
14
+ * software distributed under the License is distributed on an
15
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ * KIND, either express or implied. See the License for the
17
+ * specific language governing permissions and limitations
18
+ * under the License.
19
+ */
20
+
21
+ export default function () {
22
+ // render nothing on server side
23
+ }
@@ -0,0 +1,324 @@
1
+ /* Copyright Yukino Song, SudoMaker Ltd.
2
+ *
3
+ * Licensed to the Apache Software Foundation (ASF) under one
4
+ * or more contributor license agreements. See the NOTICE file
5
+ * distributed with this work for additional information
6
+ * regarding copyright ownership. The ASF licenses this file
7
+ * to you under the Apache License, Version 2.0 (the
8
+ * "License"); you may not use this file except in compliance
9
+ * with the License. You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing,
14
+ * software distributed under the License is distributed on an
15
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ * KIND, either express or implied. See the License for the
17
+ * specific language governing permissions and limitations
18
+ * under the License.
19
+ */
20
+
21
+ import { signal, $, t, If, For, onCondition } from 'refui'
22
+ import { createPortal } from 'refui/extras'
23
+ import { loadPagefind } from '/.methanol_virtual_module/pagefind.js'
24
+
25
+ let keybindReady = false
26
+ let cachedPagefind = null
27
+
28
+ const resolveShortcutLabel = () => {
29
+ if (typeof navigator === 'undefined') return 'Ctrl+K'
30
+ const platform = navigator.platform || ''
31
+ const agent = navigator.userAgent || ''
32
+ const isMac = /Mac|iPhone|iPad|iPod/.test(platform) || /Mac OS X/.test(agent)
33
+ return isMac ? '⌘K' : 'Ctrl+K'
34
+ }
35
+
36
+ const ensurePagefind = async (options) => {
37
+ if (cachedPagefind) return cachedPagefind
38
+ const pagefind = await loadPagefind()
39
+ if (!pagefind) return null
40
+ if (pagefind.options) {
41
+ const nextOptions = { excerptLength: 30, ...(options || {}) }
42
+ await pagefind.options(nextOptions)
43
+ }
44
+ if (pagefind.init) {
45
+ await pagefind.init()
46
+ }
47
+ cachedPagefind = pagefind
48
+ return pagefind
49
+ }
50
+
51
+ export default function ({ options } = {}) {
52
+ const isOpen = signal(false)
53
+ const query = signal('')
54
+ const results = signal([])
55
+ const isLoading = signal(false)
56
+ const activeIndex = signal(-1)
57
+
58
+ const buttonRef = signal()
59
+ const inputRef = signal()
60
+ const resultIdPrefix = `search-result-${Math.random().toString(36).slice(2)}`
61
+ const activeMatch = onCondition(activeIndex)
62
+
63
+ let debounceTimer = null
64
+ const shortcutLabel = resolveShortcutLabel()
65
+ const [Inlet, Outlet] = createPortal()
66
+
67
+ const search = async (q) => {
68
+ isLoading.value = true
69
+ results.value = []
70
+ activeIndex.value = -1
71
+
72
+ const pagefind = await ensurePagefind(options)
73
+ if (!pagefind) {
74
+ isLoading.value = false
75
+ return
76
+ }
77
+
78
+ try {
79
+ const searchResult = await pagefind.search(q)
80
+ if (searchResult?.results?.length) {
81
+ const data = await Promise.all(searchResult.results.slice(0, 10).map((r) => r.data()))
82
+ results.value = data.map((value) => ({ value, el: signal() }))
83
+ }
84
+ } catch (err) {
85
+ console.error('Search error:', err)
86
+ } finally {
87
+ isLoading.value = false
88
+ }
89
+ }
90
+
91
+ const onInput = (event) => {
92
+ const value = event.target.value
93
+ query.value = value
94
+ if (debounceTimer) clearTimeout(debounceTimer)
95
+
96
+ if (!value.trim()) {
97
+ results.value = []
98
+ activeIndex.value = -1
99
+ return
100
+ }
101
+
102
+ debounceTimer = setTimeout(() => {
103
+ search(value)
104
+ }, 300)
105
+ }
106
+
107
+ const focusInput = () => {
108
+ if (inputRef.value) inputRef.value.focus()
109
+ }
110
+
111
+ const open = async () => {
112
+ isOpen.value = true
113
+ setTimeout(focusInput, 50)
114
+ await ensurePagefind(options)
115
+ }
116
+
117
+ const close = () => {
118
+ isOpen.value = false
119
+ query.value = ''
120
+ results.value = []
121
+ activeIndex.value = -1
122
+ if (debounceTimer) clearTimeout(debounceTimer)
123
+ if (inputRef.value) inputRef.value.blur()
124
+ if (buttonRef.value) buttonRef.value.focus()
125
+ }
126
+
127
+ const scrollActiveIntoView = () => {
128
+ setTimeout(() => {
129
+ const activeEl = results.value[activeIndex.value]?.el.value
130
+ if (activeEl) {
131
+ activeEl.scrollIntoView({ block: 'nearest' })
132
+ }
133
+ }, 0)
134
+ }
135
+
136
+ const onKeyDown = (event) => {
137
+ if (event.key === 'Escape') {
138
+ event.preventDefault()
139
+ close()
140
+ return
141
+ }
142
+
143
+ if (event.key === 'ArrowDown') {
144
+ event.preventDefault()
145
+ if (results.value.length > 0) {
146
+ const nextIndex = activeIndex.value >= 0 ? (activeIndex.value + 1) % results.value.length : 0
147
+ activeIndex.value = nextIndex
148
+ scrollActiveIntoView()
149
+ }
150
+ } else if (event.key === 'ArrowUp') {
151
+ event.preventDefault()
152
+ if (results.value.length > 0) {
153
+ const nextIndex = activeIndex.value > 0 ? activeIndex.value - 1 : results.value.length - 1
154
+ activeIndex.value = nextIndex
155
+ scrollActiveIntoView()
156
+ }
157
+ } else if (event.key === 'Enter') {
158
+ event.preventDefault()
159
+ const selected = results.value[activeIndex.value]?.value
160
+ const fallback = results.value[0]?.value
161
+ const target = selected || fallback
162
+ if (target?.url) {
163
+ window.location.href = target.url
164
+ close()
165
+ }
166
+ }
167
+ }
168
+
169
+ const onResultKeyDown = (event, indexValue) => {
170
+ if (event.key === 'Escape') {
171
+ event.preventDefault()
172
+ close()
173
+ return
174
+ }
175
+ if (event.key === 'ArrowDown') {
176
+ event.preventDefault()
177
+ const nextIndex = (indexValue + 1) % results.value.length
178
+ activeIndex.value = nextIndex
179
+ scrollActiveIntoView()
180
+ } else if (event.key === 'ArrowUp') {
181
+ event.preventDefault()
182
+ if (indexValue === 0) {
183
+ activeIndex.value = -1
184
+ focusInput()
185
+ return
186
+ }
187
+ const nextIndex = indexValue - 1
188
+ activeIndex.value = nextIndex
189
+ scrollActiveIntoView()
190
+ }
191
+ }
192
+
193
+ const showEmpty = $(() => !query.value)
194
+ const showNoResults = $(() => {
195
+ const _query = query.value
196
+ const _isLoading = isLoading.value
197
+ const _length = results.value.length
198
+ return _query && !_isLoading && _length === 0
199
+ })
200
+
201
+ if (typeof window !== 'undefined') {
202
+ window.__methanolSearchOpen = open
203
+ window.__methanolSearchClose = close
204
+ }
205
+
206
+ if (typeof window !== 'undefined' && !keybindReady) {
207
+ keybindReady = true
208
+ window.addEventListener('keydown', (event) => {
209
+ const key = event.key?.toLowerCase?.()
210
+ if ((event.metaKey || event.ctrlKey) && key === 'k') {
211
+ event.preventDefault()
212
+ if (isOpen.value) {
213
+ close()
214
+ } else {
215
+ open()
216
+ }
217
+ } else if (key === 'escape' && isOpen.value) {
218
+ close()
219
+ }
220
+ })
221
+ }
222
+
223
+ return (R) => {
224
+ R.render(document.body, Outlet)
225
+ return (
226
+ <button class="search-box" type="button" on:click={open} attr:aria-label="Open search" $ref={buttonRef}>
227
+ <svg
228
+ attr:width="16"
229
+ attr:height="16"
230
+ attr:viewBox="0 0 24 24"
231
+ attr:fill="none"
232
+ attr:stroke="currentColor"
233
+ attr:stroke-width="2"
234
+ attr:stroke-linecap="round"
235
+ attr:stroke-linejoin="round"
236
+ >
237
+ <circle attr:cx="11" attr:cy="11" attr:r="8"></circle>
238
+ <path attr:d="m21 21-4.3-4.3"></path>
239
+ </svg>
240
+ <span>Search</span>
241
+ <kbd>{shortcutLabel}</kbd>
242
+ <Inlet>
243
+ <div class="search-modal" class:open={isOpen} attr:inert={$(() => (isOpen.value ? null : ''))}>
244
+ <div class="search-modal__scrim" on:click={close}></div>
245
+ <div class="search-modal__panel">
246
+ <div class="search-input-wrapper">
247
+ <svg
248
+ attr:width="20"
249
+ attr:height="20"
250
+ attr:viewBox="0 0 24 24"
251
+ attr:fill="none"
252
+ attr:stroke="currentColor"
253
+ attr:stroke-width="2"
254
+ attr:stroke-linecap="round"
255
+ attr:stroke-linejoin="round"
256
+ >
257
+ <circle attr:cx="11" attr:cy="11" attr:r="8"></circle>
258
+ <path attr:d="m21 21-4.3-4.3"></path>
259
+ </svg>
260
+ <input
261
+ class="search-input"
262
+ type="text"
263
+ placeholder="Search documentation..."
264
+ value={query}
265
+ on:input={onInput}
266
+ on:keydown={onKeyDown}
267
+ attr:aria-activedescendant={$(() =>
268
+ activeIndex.value >= 0 ? `${resultIdPrefix}-${activeIndex.value}` : null
269
+ )}
270
+ attr:autocomplete="off"
271
+ attr:autocorrect="off"
272
+ attr:spellcheck="false"
273
+ $ref={inputRef}
274
+ />
275
+ </div>
276
+ <div class="search-results">
277
+ <If condition={showEmpty}>{() => <div class="search-status">Type to start searching...</div>}</If>
278
+ <If condition={showNoResults}>
279
+ {() => <div class="search-status">No results found for "{query}"</div>}
280
+ </If>
281
+ <If condition={isLoading}>{() => <div class="search-status">Searching...</div>}</If>
282
+ <For entries={results} indexed>
283
+ {({ item: { value, el }, index }) => (
284
+ <a
285
+ class="search-result-item"
286
+ class:active={activeMatch(index)}
287
+ href={value.url}
288
+ on:click={close}
289
+ on:keydown={(event) => onResultKeyDown(event, index.value)}
290
+ on:focus={() => {
291
+ activeIndex.value = index.value
292
+ }}
293
+ attr:aria-selected={$(() => (activeIndex.value === index.value ? 'true' : 'false'))}
294
+ attr:id={t`${resultIdPrefix}-${index.value}`}
295
+ $ref={el}
296
+ >
297
+ <div class="search-result-title">
298
+ <svg
299
+ attr:width="14"
300
+ attr:height="14"
301
+ attr:viewBox="0 0 24 24"
302
+ attr:fill="none"
303
+ attr:stroke="currentColor"
304
+ attr:stroke-width="2"
305
+ attr:stroke-linecap="round"
306
+ attr:stroke-linejoin="round"
307
+ >
308
+ <path attr:d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
309
+ <polyline attr:points="14 2 14 8 20 8"></polyline>
310
+ </svg>
311
+ {value?.meta?.title || value?.title || value?.url}
312
+ </div>
313
+ <div class="search-result-excerpt" innerHTML={value.excerpt || ''}></div>
314
+ </a>
315
+ )}
316
+ </For>
317
+ </div>
318
+ </div>
319
+ </div>
320
+ </Inlet>
321
+ </button>
322
+ )
323
+ }
324
+ }
@@ -0,0 +1,40 @@
1
+ /* Copyright Yukino Song, SudoMaker Ltd.
2
+ *
3
+ * Licensed to the Apache Software Foundation (ASF) under one
4
+ * or more contributor license agreements. See the NOTICE file
5
+ * distributed with this work for additional information
6
+ * regarding copyright ownership. The ASF licenses this file
7
+ * to you under the Apache License, Version 2.0 (the
8
+ * "License"); you may not use this file except in compliance
9
+ * with the License. You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing,
14
+ * software distributed under the License is distributed on an
15
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ * KIND, either express or implied. See the License for the
17
+ * specific language governing permissions and limitations
18
+ * under the License.
19
+ */
20
+
21
+ export default function () {
22
+ return (
23
+ <button class="search-box" type="button" aria-label="Open search">
24
+ <svg
25
+ width="16"
26
+ height="16"
27
+ viewBox="0 0 24 24"
28
+ fill="none"
29
+ stroke="currentColor"
30
+ stroke-width="2"
31
+ stroke-linecap="round"
32
+ stroke-linejoin="round"
33
+ >
34
+ <circle cx="11" cy="11" r="8"></circle>
35
+ <path d="m21 21-4.3-4.3"></path>
36
+ </svg>
37
+ <span>Search</span>
38
+ </button>
39
+ )
40
+ }
@@ -0,0 +1,154 @@
1
+ /* Copyright Yukino Song, SudoMaker Ltd.
2
+ *
3
+ * Licensed to the Apache Software Foundation (ASF) under one
4
+ * or more contributor license agreements. See the NOTICE file
5
+ * distributed with this work for additional information
6
+ * regarding copyright ownership. The ASF licenses this file
7
+ * to you under the Apache License, Version 2.0 (the
8
+ * "License"); you may not use this file except in compliance
9
+ * with the License. You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing,
14
+ * software distributed under the License is distributed on an
15
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ * KIND, either express or implied. See the License for the
17
+ * specific language governing permissions and limitations
18
+ * under the License.
19
+ */
20
+
21
+ import { signal, t, useEffect } from 'refui'
22
+
23
+ export default function (props, ...children) {
24
+ if (!children.length) {
25
+ return
26
+ }
27
+
28
+ const el = signal()
29
+ const top = signal(0)
30
+ const height = signal(0)
31
+ const opacity = signal(0)
32
+
33
+ const updateActive = () => {
34
+ if (!el.value) return
35
+
36
+ const links = Array.from(el.value.querySelectorAll('a'))
37
+ if (!links.length) return
38
+
39
+ // Map links to their corresponding content anchors
40
+ const anchors = links.map(link => {
41
+ const href = link.getAttribute('href')
42
+ if (!href || !href.startsWith('#')) return null
43
+ return document.getElementById(href.slice(1))
44
+ }).filter(Boolean)
45
+
46
+ if (!anchors.length) return
47
+
48
+ const scrollY = window.scrollY
49
+ const offset = 100 // Header offset
50
+
51
+ // Find all sections that are visible in the viewport
52
+ const visibleAnchors = new Set()
53
+ const windowHeight = window.innerHeight
54
+ const threshold = 100 // Header offset/buffer
55
+
56
+ for (let i = 0; i < anchors.length; i++) {
57
+ const anchor = anchors[i]
58
+ const nextAnchor = anchors[i + 1]
59
+
60
+ const sectionStart = anchor.offsetTop - threshold
61
+ const sectionEnd = nextAnchor ? nextAnchor.offsetTop - threshold : document.body.offsetHeight
62
+
63
+ // A section is visible if its range overlaps with the viewport [scrollY, scrollY + windowHeight]
64
+ const isVisible = sectionStart < (scrollY + windowHeight - threshold) && sectionEnd > scrollY
65
+
66
+ if (isVisible) {
67
+ visibleAnchors.add(anchor)
68
+ }
69
+ }
70
+
71
+ // Fallback: if somehow nothing is found, at least highlight the first one
72
+ if (visibleAnchors.size === 0 && anchors.length > 0) {
73
+ visibleAnchors.add(anchors[0])
74
+ }
75
+
76
+ // Update active class on links and find active range
77
+ let firstActiveLink = null
78
+ let lastActiveLink = null
79
+
80
+ links.forEach(l => {
81
+ const href = l.getAttribute('href')
82
+ const anchorId = href ? href.slice(1) : null
83
+ const anchor = anchors.find(a => a.id === anchorId)
84
+ if (visibleAnchors.has(anchor)) {
85
+ l.classList.add('active')
86
+ if (!firstActiveLink) firstActiveLink = l
87
+ lastActiveLink = l
88
+ } else {
89
+ l.classList.remove('active')
90
+ }
91
+ })
92
+
93
+ // Update indicator position
94
+ if (firstActiveLink && lastActiveLink) {
95
+ const containerRect = el.value.getBoundingClientRect()
96
+ const firstRect = firstActiveLink.getBoundingClientRect()
97
+ const lastRect = lastActiveLink.getBoundingClientRect()
98
+
99
+ const currentTop = firstRect.top - containerRect.top + el.value.scrollTop
100
+ const currentHeight = lastRect.bottom - firstRect.top
101
+
102
+ top.value = currentTop
103
+ height.value = currentHeight
104
+ opacity.value = 1
105
+
106
+ // Scroll into view logic
107
+ const indicatorTop = currentTop
108
+ const indicatorBottom = currentTop + currentHeight
109
+ const scrollTop = el.value.scrollTop
110
+ const clientHeight = el.value.clientHeight
111
+
112
+ if (indicatorTop < scrollTop + 20) {
113
+ el.value.scrollTo({ top: indicatorTop - 20, behavior: 'smooth' })
114
+ } else if (indicatorBottom > scrollTop + clientHeight - 20) {
115
+ el.value.scrollTo({ top: indicatorBottom - clientHeight + 20, behavior: 'smooth' })
116
+ }
117
+ } else {
118
+ opacity.value = 0
119
+ }
120
+ }
121
+
122
+ // Attach listeners
123
+ let ticking = false
124
+ const onScroll = () => {
125
+ if (!ticking) {
126
+ window.requestAnimationFrame(() => {
127
+ updateActive()
128
+ ticking = false
129
+ })
130
+ ticking = true
131
+ }
132
+ }
133
+
134
+ // Wait for mount/layout
135
+ useEffect(() => {
136
+ updateActive()
137
+ window.addEventListener('scroll', onScroll, { passive: true })
138
+ window.addEventListener('resize', onScroll, { passive: true })
139
+ return () => {
140
+ window.removeEventListener('scroll', onScroll)
141
+ window.removeEventListener('resize', onScroll)
142
+ }
143
+ })
144
+
145
+ return (
146
+ <aside class="toc-panel" $ref={el}>
147
+ <div class="toc-indicator" style:top={t`${top}px`} style:height={t`${height}px`} style:opacity={t`${opacity}`}></div>
148
+ <div class="toc">
149
+ <h4>On this page</h4>
150
+ <ul>{...children}</ul>
151
+ </div>
152
+ </aside>
153
+ )
154
+ }