van-mdx 0.7.0 → 0.8.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "van-mdx",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Markdown preprocessor for Vanjs",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -38,6 +38,6 @@
38
38
  "mdzjs": "^0.17.0",
39
39
  "vanjs-core": "^1.6.0",
40
40
  "zextra": "^0.15.1",
41
- "ziko": "^0.65.0"
41
+ "ziko": "^0.66.0"
42
42
  }
43
43
  }
@@ -1,7 +1,59 @@
1
- import {TableOfContents as _TableOfContents} from 'zextra/nav'
1
+ import van from 'vanjs-core'
2
2
 
3
- export const TableOfContents = ({
4
- depth = 6,
5
- content = document.body,
6
- labelFn
7
- } = {}) => _TableOfContents({depth}).element
3
+ export const TableOfContents = ({ depth = 6, content = document.body, labelFn } = {}) => {
4
+ const { ul, li, a } = van.tags;
5
+ const container = ul();
6
+
7
+ const buildTOC = () => {
8
+ if (!content) return;
9
+
10
+ const selectors = getSelectorFromDepth(depth);
11
+ const headings = [...content.querySelectorAll(selectors)];
12
+ if (headings.length === 0) return; // nothing found yet
13
+
14
+ const levels = Array.isArray(depth)
15
+ ? [...depth].sort((a, b) => a - b)
16
+ : Array.from({ length: depth }, (_, i) => i + 1);
17
+
18
+ const items = headings.map((heading, i) => {
19
+ if (!heading.id) heading.id = `heading-${i + 1}`;
20
+ const level = parseInt(heading.tagName[1]);
21
+ const relativeIndex = levels.indexOf(level);
22
+ const label = labelFn ? labelFn(heading, level) : heading.textContent;
23
+ return li({ style: `margin-left:${relativeIndex * 15}px` },
24
+ a({ href: `#${heading.id}` }, label)
25
+ );
26
+ });
27
+
28
+ container.replaceChildren(...items);
29
+ };
30
+
31
+ // Try immediately (works if DOM is already ready)
32
+ buildTOC();
33
+
34
+ // If nothing was found, observe the DOM until headings appear
35
+ if (container.children.length === 0) {
36
+ const observer = new MutationObserver(() => {
37
+ buildTOC();
38
+ if (container.children.length > 0) observer.disconnect();
39
+ });
40
+
41
+ const observeTarget = () => {
42
+ if (content) observer.observe(content, { childList: true, subtree: true });
43
+ else {
44
+ document.addEventListener('DOMContentLoaded', () => {
45
+ observer.observe(content ?? document.body, { childList: true, subtree: true });
46
+ });
47
+ }
48
+ };
49
+ observeTarget();
50
+ }
51
+ return container;
52
+ };
53
+
54
+ function getSelectorFromDepth(depth = 6) {
55
+ if (Array.isArray(depth))
56
+ return depth.map(d => `h${d}`).join(', ');
57
+ const max = Math.min(Math.max(depth, 1), 6);
58
+ return Array.from({ length: max }, (_, i) => `h${i + 1}`).join(', ');
59
+ }