@cloudhal/astro-renderer 0.0.0-stage → 0.1.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.
Files changed (164) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +36 -2
  3. package/dist/src/ambient-client.d.ts +17 -0
  4. package/dist/src/ambient-client.js +55 -0
  5. package/dist/src/analytics-client.d.ts +17 -0
  6. package/dist/src/analytics-client.js +96 -0
  7. package/dist/src/analytics-middleware.d.ts +6 -0
  8. package/dist/src/analytics-middleware.js +43 -0
  9. package/dist/src/analytics-node.d.ts +46 -0
  10. package/dist/src/analytics-node.js +134 -0
  11. package/dist/src/analytics.d.ts +117 -0
  12. package/dist/src/analytics.js +372 -0
  13. package/dist/src/archive.d.ts +106 -0
  14. package/dist/src/archive.js +207 -0
  15. package/dist/src/astro-env.d.ts +21 -0
  16. package/dist/src/block-html.d.ts +14 -0
  17. package/dist/src/block-html.js +103 -0
  18. package/dist/src/blocks.d.ts +24 -0
  19. package/dist/src/blocks.js +66 -0
  20. package/dist/src/cache-tags.d.ts +25 -0
  21. package/dist/src/cache-tags.js +59 -0
  22. package/dist/src/carousel-client.d.ts +28 -0
  23. package/dist/src/carousel-client.js +67 -0
  24. package/dist/src/chart.d.ts +34 -0
  25. package/dist/src/chart.js +182 -0
  26. package/dist/src/chrome-client.d.ts +27 -0
  27. package/dist/src/chrome-client.js +64 -0
  28. package/dist/src/cloudflare-entry.d.ts +87 -0
  29. package/dist/src/cloudflare-entry.js +548 -0
  30. package/dist/src/comments-client.d.ts +11 -0
  31. package/dist/src/comments-client.js +58 -0
  32. package/dist/src/comments-html.d.ts +42 -0
  33. package/dist/src/comments-html.js +303 -0
  34. package/dist/src/comments-middleware.d.ts +6 -0
  35. package/dist/src/comments-middleware.js +38 -0
  36. package/dist/src/comments-node.d.ts +42 -0
  37. package/dist/src/comments-node.js +112 -0
  38. package/dist/src/comments-view.d.ts +68 -0
  39. package/dist/src/comments-view.js +174 -0
  40. package/dist/src/comments.d.ts +66 -0
  41. package/dist/src/comments.js +258 -0
  42. package/dist/src/components/Block.astro +39 -0
  43. package/dist/src/components/Body.astro +43 -0
  44. package/dist/src/components/Comments.astro +19 -0
  45. package/dist/src/components/ContentList.astro +31 -0
  46. package/dist/src/components/EntryArticle.astro +31 -0
  47. package/dist/src/components/Hero.astro +36 -0
  48. package/dist/src/components/Image.astro +36 -0
  49. package/dist/src/components/RichText.astro +19 -0
  50. package/dist/src/components/Sections.astro +66 -0
  51. package/dist/src/components/SeoHead.astro +22 -0
  52. package/dist/src/components/Surface.astro +36 -0
  53. package/dist/src/components/SurfaceNode.astro +82 -0
  54. package/dist/src/components/index.d.ts +12 -0
  55. package/dist/src/components/index.js +12 -0
  56. package/dist/src/csp.d.ts +20 -0
  57. package/dist/src/csp.js +28 -0
  58. package/dist/src/embed-client.d.ts +38 -0
  59. package/dist/src/embed-client.js +98 -0
  60. package/dist/src/embed-middleware.d.ts +9 -0
  61. package/dist/src/embed-middleware.js +49 -0
  62. package/dist/src/feeds.d.ts +72 -0
  63. package/dist/src/feeds.js +246 -0
  64. package/dist/src/gates.d.ts +25 -0
  65. package/dist/src/gates.js +63 -0
  66. package/dist/src/index.d.ts +17 -0
  67. package/dist/src/index.js +17 -0
  68. package/dist/src/integration.d.ts +55 -0
  69. package/dist/src/integration.js +244 -0
  70. package/dist/src/kit.d.ts +48 -0
  71. package/dist/src/kit.js +83 -0
  72. package/dist/src/locale-feeds.d.ts +29 -0
  73. package/dist/src/locale-feeds.js +152 -0
  74. package/dist/src/locale-middleware.d.ts +5 -0
  75. package/dist/src/locale-middleware.js +26 -0
  76. package/dist/src/locales.d.ts +87 -0
  77. package/dist/src/locales.js +336 -0
  78. package/dist/src/markdown.d.ts +83 -0
  79. package/dist/src/markdown.js +533 -0
  80. package/dist/src/media-middleware.d.ts +5 -0
  81. package/dist/src/media-middleware.js +18 -0
  82. package/dist/src/media-route.d.ts +47 -0
  83. package/dist/src/media-route.js +238 -0
  84. package/dist/src/media.d.ts +109 -0
  85. package/dist/src/media.js +298 -0
  86. package/dist/src/motion-client.d.ts +39 -0
  87. package/dist/src/motion-client.js +115 -0
  88. package/dist/src/navigation.d.ts +127 -0
  89. package/dist/src/navigation.js +382 -0
  90. package/dist/src/not-found.d.ts +16 -0
  91. package/dist/src/not-found.js +41 -0
  92. package/dist/src/overlay-client.d.ts +20 -0
  93. package/dist/src/overlay-client.js +49 -0
  94. package/dist/src/prefs-client.d.ts +14 -0
  95. package/dist/src/prefs-client.js +18 -0
  96. package/dist/src/preview.d.ts +70 -0
  97. package/dist/src/preview.js +551 -0
  98. package/dist/src/resolver.d.ts +71 -0
  99. package/dist/src/resolver.js +206 -0
  100. package/dist/src/routing.d.ts +108 -0
  101. package/dist/src/routing.js +285 -0
  102. package/dist/src/runtime-workerd.d.ts +87 -0
  103. package/dist/src/runtime-workerd.js +275 -0
  104. package/dist/src/runtime.d.ts +59 -0
  105. package/dist/src/runtime.js +153 -0
  106. package/dist/src/safe-urls.d.ts +13 -0
  107. package/dist/src/safe-urls.js +35 -0
  108. package/dist/src/sanitize.d.ts +7 -0
  109. package/dist/src/sanitize.js +217 -0
  110. package/dist/src/search-client.d.ts +29 -0
  111. package/dist/src/search-client.js +92 -0
  112. package/dist/src/search-limit.d.ts +36 -0
  113. package/dist/src/search-limit.js +66 -0
  114. package/dist/src/search.d.ts +64 -0
  115. package/dist/src/search.js +155 -0
  116. package/dist/src/seo.d.ts +85 -0
  117. package/dist/src/seo.js +468 -0
  118. package/dist/src/site-dispatch.d.ts +37 -0
  119. package/dist/src/site-dispatch.js +86 -0
  120. package/dist/src/site-hosts.d.ts +35 -0
  121. package/dist/src/site-hosts.js +110 -0
  122. package/dist/src/source.d.ts +227 -0
  123. package/dist/src/source.js +794 -0
  124. package/dist/src/static-gates.d.ts +3 -0
  125. package/dist/src/static-gates.js +28 -0
  126. package/dist/src/static-headers.d.ts +30 -0
  127. package/dist/src/static-headers.js +140 -0
  128. package/dist/src/static-media.d.ts +4 -0
  129. package/dist/src/static-media.js +65 -0
  130. package/dist/src/static-redirects.d.ts +4 -0
  131. package/dist/src/static-redirects.js +40 -0
  132. package/dist/src/surface-client.d.ts +34 -0
  133. package/dist/src/surface-client.js +146 -0
  134. package/dist/src/surfaces/html.d.ts +35 -0
  135. package/dist/src/surfaces/html.js +184 -0
  136. package/dist/src/surfaces/markup.d.ts +57 -0
  137. package/dist/src/surfaces/markup.js +135 -0
  138. package/dist/src/surfaces/motion.d.ts +33 -0
  139. package/dist/src/surfaces/motion.js +132 -0
  140. package/dist/src/surfaces/primitives/carousel.d.ts +2 -0
  141. package/dist/src/surfaces/primitives/carousel.js +95 -0
  142. package/dist/src/surfaces/primitives/content.d.ts +13 -0
  143. package/dist/src/surfaces/primitives/content.js +159 -0
  144. package/dist/src/surfaces/primitives/data.d.ts +5 -0
  145. package/dist/src/surfaces/primitives/data.js +80 -0
  146. package/dist/src/surfaces/primitives/index.d.ts +54 -0
  147. package/dist/src/surfaces/primitives/index.js +106 -0
  148. package/dist/src/surfaces/primitives/inputs.d.ts +8 -0
  149. package/dist/src/surfaces/primitives/inputs.js +68 -0
  150. package/dist/src/surfaces/primitives/layout.d.ts +14 -0
  151. package/dist/src/surfaces/primitives/layout.js +61 -0
  152. package/dist/src/surfaces/primitives/motion.d.ts +9 -0
  153. package/dist/src/surfaces/primitives/motion.js +45 -0
  154. package/dist/src/surfaces/primitives/overlays.d.ts +6 -0
  155. package/dist/src/surfaces/primitives/overlays.js +79 -0
  156. package/dist/src/surfaces/tree.d.ts +107 -0
  157. package/dist/src/surfaces/tree.js +321 -0
  158. package/dist/src/surfaces.d.ts +14 -0
  159. package/dist/src/surfaces.js +33 -0
  160. package/dist/src/taxonomy.d.ts +86 -0
  161. package/dist/src/taxonomy.js +268 -0
  162. package/dist/src/theme-settings.d.ts +24 -0
  163. package/dist/src/theme-settings.js +111 -0
  164. package/package.json +219 -3
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Cloudhal's motion module (RFC-0024 §7): what CSS cannot do alone, for pages whose surfaces use
3
+ * `motion`. A self-contained, versioned file under `/_cloudhal/` (CSP `script-src 'self'`), loaded
4
+ * only by pages that need it; it never evaluates code and only adds classes, `hidden`-free state
5
+ * and CSS custom properties (through the CSSOM).
6
+ *
7
+ * - **Reveals.** Content is complete without this module. Components already on screen play their
8
+ * entrance through `@starting-style` (pure CSS). Components below the first screen get the
9
+ * "before" state (`ch-pre`) only once the module runs, while still off screen, and lose it as
10
+ * they enter (IntersectionObserver), or at once if the reader scrolled past them before the module
11
+ * ran; `replay` puts it back when they leave downwards. Wipes
12
+ * and masks start fully clipped, which an observer never sees intersect, so their parent is
13
+ * watched instead.
14
+ * - **Scroll stories.** A `Scrolly`'s step crossing the middle of the screen becomes the active one;
15
+ * its number goes to the surface's data through a `ch:set` event the interaction runtime takes
16
+ * (at every motion level: it is content, not movement).
17
+ * - **Scroll effects without scroll-driven CSS** (Firefox today): `--ch-p` (0–1) on each element,
18
+ * written once a frame from passive scroll events, which the theme's fallback rules read.
19
+ * - **Kinetic type and loops** (24c): split lines numbered once the line breaks are known; a
20
+ * marquee's children copied once (hidden from screen readers, inert) so it loops seamlessly;
21
+ * rotating words take turns every 2.8 s; counters count up once as they come into view, ending
22
+ * on the number the page already shows. Loops stop while paused or in a hidden tab.
23
+ * - **Ambient particles** (24d): the ambient module, imported only for a page with a particle band,
24
+ * at `standard` or above, without Save-Data and with more than 2 GB of memory; otherwise the
25
+ * band keeps its still poster.
26
+ * - **Pointer effects.** `tilt`, `magnetic` and `spotlight` follow a fine pointer through
27
+ * `--ch-mx`/`--ch-my` (0–1), one write per frame.
28
+ * - **Pause control.** `[data-ch-motion-toggle]` buttons pause loops and ambient effects for every
29
+ * page (`data-ch-motion-paused` on `<html>`, remembered when storage allows); the renderer adds
30
+ * one per looping surface, and only the first on the page stays visible.
31
+ *
32
+ * Nothing moves when the page's level is `none` or the reader asks for reduced motion.
33
+ */
34
+ export declare const MOTION_SCRIPT: {
35
+ readonly path: "/_cloudhal/motion.4.js";
36
+ readonly code: string;
37
+ };
38
+ /** Earlier names of the module, served with the current code (each version only adds). */
39
+ export declare const MOTION_SCRIPT_ALIASES: readonly ["/_cloudhal/motion.1.js", "/_cloudhal/motion.2.js", "/_cloudhal/motion.3.js"];
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Cloudhal's motion module (RFC-0024 §7): what CSS cannot do alone, for pages whose surfaces use
3
+ * `motion`. A self-contained, versioned file under `/_cloudhal/` (CSP `script-src 'self'`), loaded
4
+ * only by pages that need it; it never evaluates code and only adds classes, `hidden`-free state
5
+ * and CSS custom properties (through the CSSOM).
6
+ *
7
+ * - **Reveals.** Content is complete without this module. Components already on screen play their
8
+ * entrance through `@starting-style` (pure CSS). Components below the first screen get the
9
+ * "before" state (`ch-pre`) only once the module runs, while still off screen, and lose it as
10
+ * they enter (IntersectionObserver), or at once if the reader scrolled past them before the module
11
+ * ran; `replay` puts it back when they leave downwards. Wipes
12
+ * and masks start fully clipped, which an observer never sees intersect, so their parent is
13
+ * watched instead.
14
+ * - **Scroll stories.** A `Scrolly`'s step crossing the middle of the screen becomes the active one;
15
+ * its number goes to the surface's data through a `ch:set` event the interaction runtime takes
16
+ * (at every motion level: it is content, not movement).
17
+ * - **Scroll effects without scroll-driven CSS** (Firefox today): `--ch-p` (0–1) on each element,
18
+ * written once a frame from passive scroll events, which the theme's fallback rules read.
19
+ * - **Kinetic type and loops** (24c): split lines numbered once the line breaks are known; a
20
+ * marquee's children copied once (hidden from screen readers, inert) so it loops seamlessly;
21
+ * rotating words take turns every 2.8 s; counters count up once as they come into view, ending
22
+ * on the number the page already shows. Loops stop while paused or in a hidden tab.
23
+ * - **Ambient particles** (24d): the ambient module, imported only for a page with a particle band,
24
+ * at `standard` or above, without Save-Data and with more than 2 GB of memory; otherwise the
25
+ * band keeps its still poster.
26
+ * - **Pointer effects.** `tilt`, `magnetic` and `spotlight` follow a fine pointer through
27
+ * `--ch-mx`/`--ch-my` (0–1), one write per frame.
28
+ * - **Pause control.** `[data-ch-motion-toggle]` buttons pause loops and ambient effects for every
29
+ * page (`data-ch-motion-paused` on `<html>`, remembered when storage allows); the renderer adds
30
+ * one per looping surface, and only the first on the page stays visible.
31
+ *
32
+ * Nothing moves when the page's level is `none` or the reader asks for reduced motion.
33
+ */
34
+
35
+ import { AMBIENT_SCRIPT } from "./ambient-client.js";
36
+
37
+ const code = String.raw`const d=document,h=d.documentElement;
38
+ const reduce=matchMedia("(prefers-reduced-motion: reduce)").matches;
39
+ const level=h.getAttribute("data-ch-motion")||"none";
40
+ const moving=!reduce&&level!=="none";
41
+ const KEY="ch-motion-paused";
42
+ let paused=false;try{paused=localStorage.getItem(KEY)==="1";}catch{}
43
+ const setPaused=(p)=>{paused=p;if(p)h.setAttribute("data-ch-motion-paused","");else h.removeAttribute("data-ch-motion-paused");
44
+ for(const b of d.querySelectorAll("[data-ch-motion-toggle]"))b.setAttribute("aria-pressed",String(p));
45
+ try{if(p)localStorage.setItem(KEY,"1");else localStorage.removeItem(KEY);}catch{}};
46
+ const toggles=[...d.querySelectorAll("[data-ch-motion-toggle]")];for(const t of toggles.slice(1))t.hidden=true;
47
+ setPaused(paused);
48
+ d.addEventListener("click",(e)=>{const b=e.target instanceof Element&&e.target.closest("[data-ch-motion-toggle]");if(b)setPaused(!paused);});
49
+ if(moving){
50
+ for(const sp of d.querySelectorAll('.ch-split[data-mode="lines"]')){let line=-1,top=null;
51
+ for(const w of sp.querySelectorAll(".ch-w")){const t=w.offsetTop;if(top===null||t>top+2){line++;top=t;}w.style.setProperty("--ch-i",String(line));}}
52
+ for(const m of d.querySelectorAll(".ch-marquee")){const tr=m.querySelector(".ch-marquee__track");if(!tr||m.hasAttribute("data-ch-ready")||level==="subtle")continue;
53
+ for(const c of [...tr.children]){const k=c.cloneNode(true);for(const x of [k,...k.querySelectorAll("[id]")])x.removeAttribute("id");k.setAttribute("aria-hidden","true");k.setAttribute("inert","");tr.appendChild(k);}m.setAttribute("data-ch-ready","");}
54
+ if(level!=="subtle"){const rot=[...d.querySelectorAll("[data-ch-rotate]")];
55
+ if(rot.length)setInterval(()=>{if(paused||d.hidden)return;for(const r of rot){const ws=[...r.children];const i=ws.findIndex((w)=>w.hasAttribute("data-active"));
56
+ ws.forEach((w,j)=>w.toggleAttribute("data-active",j===(i+1)%ws.length));}},2800);}
57
+ const counts=[...d.querySelectorAll("[data-ch-count]")];
58
+ if(counts.length&&"IntersectionObserver"in window){const lang=h.lang||"en";
59
+ const co=new IntersectionObserver((es)=>{for(const e of es){const el=e.target;if(!e.isIntersecting){if(e.boundingClientRect.bottom<=0)co.unobserve(el);continue;}co.unobserve(el);
60
+ const to=Number(el.getAttribute("data-ch-count")),from=Number(el.getAttribute("data-ch-from"))||0,dec=Number(el.getAttribute("data-ch-decimals"))||0;
61
+ const sp=el.getAttribute("data-ch-speed"),ms=sp==="fast"?900:sp==="slow"?2200:1500;const fmt=new Intl.NumberFormat(lang,{minimumFractionDigits:dec,maximumFractionDigits:dec});
62
+ const final=el.textContent;const t0=performance.now();const step=(t)=>{const k=Math.min(1,(t-t0)/ms),v=from+(to-from)*(1-Math.pow(1-k,3));
63
+ el.textContent=k<1?fmt.format(v):final;if(k<1)requestAnimationFrame(step);};el.textContent=fmt.format(from);requestAnimationFrame(step);}},{threshold:0.4});
64
+ for(const el of counts)co.observe(el);}}
65
+ if(moving&&"IntersectionObserver"in window){
66
+ const watch=new Map();
67
+ const io=new IntersectionObserver((es)=>{for(const e of es){for(const el of watch.get(e.target)||[]){
68
+ if(e.isIntersecting||e.boundingClientRect.bottom<=0){el.classList.remove("ch-pre");}
69
+ else if(el.hasAttribute("data-ch-replay")&&e.boundingClientRect.top>0)el.classList.add("ch-pre");}
70
+ if((e.isIntersecting||e.boundingClientRect.bottom<=0)&&!(watch.get(e.target)||[]).some((el)=>el.hasAttribute("data-ch-replay")))io.unobserve(e.target);}},{rootMargin:"0px 0px -6% 0px",threshold:0.1});
71
+ const fold=innerHeight;
72
+ for(const el of d.querySelectorAll("[data-ch-reveal]")){if(el.getBoundingClientRect().top<=fold)continue;
73
+ el.classList.add("ch-pre");
74
+ const clip=/^(wipe|mask)-/.test(el.getAttribute("data-ch-reveal")||"");
75
+ const at=clip&&el.parentElement?el.parentElement:el;
76
+ if(!watch.has(at))watch.set(at,[]);watch.get(at).push(el);io.observe(at);}}
77
+ for(const sc of d.querySelectorAll(".ch-scrolly[data-ch-step-path]")){
78
+ const steps=[...sc.children].filter((c)=>c.classList.contains("ch-step"));const path=sc.getAttribute("data-ch-step-path");
79
+ const root=sc.closest("[data-ch-surface]");if(!steps.length||!path||!root||!("IntersectionObserver"in window))continue;
80
+ sc.setAttribute("data-ch-live","");
81
+ const so=new IntersectionObserver((es)=>{for(const e of es){if(!e.isIntersecting)continue;const n=steps.indexOf(e.target)+1;
82
+ for(const s of steps)s.toggleAttribute("data-ch-active",s===e.target);sc.setAttribute("data-ch-current",String(n));
83
+ root.dispatchEvent(new CustomEvent("ch:set",{detail:{path,value:n}}));}},{rootMargin:"-45% 0px -45% 0px",threshold:0});
84
+ for(const s of steps)so.observe(s);}
85
+ if(moving&&!(window.CSS&&CSS.supports("animation-timeline: view()"))){
86
+ const els=[...d.querySelectorAll("[data-ch-scroll],.ch-progress")];
87
+ if(els.length){let raf=0;const tick=()=>{raf=0;const vh=innerHeight,sh=d.documentElement.scrollHeight;
88
+ for(const el of els){let p;
89
+ if(el.matches('.ch-progress[data-placement="page"]'))p=scrollY/Math.max(1,sh-vh);
90
+ else if(el.classList.contains("ch-progress")){const sec=el.closest(".ch-surface")||el.parentElement;const r=sec.getBoundingClientRect();p=-r.top/Math.max(1,r.height-vh);}
91
+ else{const r=el.getBoundingClientRect();if(r.bottom<-vh||r.top>2*vh)continue;p=(vh-r.top)/(vh+r.height);}
92
+ el.style.setProperty("--ch-p",Math.min(1,Math.max(0,p)).toFixed(4));}};
93
+ addEventListener("scroll",()=>{if(!raf)raf=requestAnimationFrame(tick);},{passive:true});addEventListener("resize",()=>{if(!raf)raf=requestAnimationFrame(tick);},{passive:true});tick();}}
94
+ const nav=navigator;
95
+ if(moving&&level!=="subtle"&&d.querySelector("canvas.ch-ambient")&&!(nav.connection&&nav.connection.saveData)&&!(nav.deviceMemory&&nav.deviceMemory<=2))import("${AMBIENT_SCRIPT.path}").catch(()=>{});
96
+ if(moving&&matchMedia("(hover: hover) and (pointer: fine)").matches){
97
+ let raf=0,pending=null;
98
+ const apply=()=>{raf=0;if(!pending)return;const[el,x,y]=pending;pending=null;
99
+ el.style.setProperty("--ch-mx",x.toFixed(3));el.style.setProperty("--ch-my",y.toFixed(3));};
100
+ d.addEventListener("pointermove",(e)=>{const el=e.target instanceof Element&&e.target.closest('[data-ch-hover="tilt"],[data-ch-hover="magnetic"],[data-ch-hover="spotlight"]');
101
+ if(!el)return;const r=el.getBoundingClientRect();if(!r.width||!r.height)return;
102
+ pending=[el,Math.min(1,Math.max(0,(e.clientX-r.left)/r.width)),Math.min(1,Math.max(0,(e.clientY-r.top)/r.height))];
103
+ if(!raf)raf=requestAnimationFrame(apply);},{passive:true});
104
+ d.addEventListener("pointerout",(e)=>{const el=e.target instanceof Element&&e.target.closest("[data-ch-hover]");
105
+ if(el&&!(e.relatedTarget instanceof Node&&el.contains(e.relatedTarget))){el.style.removeProperty("--ch-mx");el.style.removeProperty("--ch-my");}},{passive:true});}
106
+ `;
107
+
108
+ export const MOTION_SCRIPT = { path: "/_cloudhal/motion.4.js", code } ;
109
+
110
+ /** Earlier names of the module, served with the current code (each version only adds). */
111
+ export const MOTION_SCRIPT_ALIASES = [
112
+ "/_cloudhal/motion.1.js",
113
+ "/_cloudhal/motion.2.js",
114
+ "/_cloudhal/motion.3.js",
115
+ ] ;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Navigation (RFC-0003 §7): menus resolved for rendering, the active item, breadcrumbs and prev/next
3
+ * for docs sidebars, and the derived header for sites without a menu. Pure functions over graph
4
+ * nodes, so the starter, previews and MCP agree on one set of rules:
5
+ *
6
+ * - an item links only to what the site serves (`resolveMenu` in `@cloudhal/core-ts/menu`): a
7
+ * missing, unpublished or retired target, an empty archive or a collection without an index
8
+ * hides the item and its subtree;
9
+ * - the active item is the exact match, then the longest prefix, then the context (an entry's
10
+ * primary category, its ancestors, then its collection);
11
+ * - without a menu, `derivedNavigation` is today's header (`navLinks` + `categoryNavLinks`).
12
+ */
13
+ import type { ContentEntry, Menu, MenuItem, Page, Site, Taxonomy, Term } from "@cloudhal/core-contracts";
14
+ import { type MenuLookup, type ResolvedMenu } from "@cloudhal/core-ts/menu";
15
+ import { type ArchiveSummary } from "./archive.js";
16
+ /** A menu resolved for one locale: only shown items, with labels and hrefs. */
17
+ export interface Navigation {
18
+ readonly key: string;
19
+ /** Absent: the theme's derived default (no menu stored under `key`). */
20
+ readonly menuId?: string;
21
+ readonly locale: string;
22
+ readonly items: NavItem[];
23
+ }
24
+ export interface NavItem {
25
+ readonly id: string;
26
+ readonly kind: MenuItem["kind"];
27
+ readonly label: string;
28
+ /** Absent for groups. */
29
+ readonly href?: string;
30
+ readonly external: boolean;
31
+ readonly newTab: boolean;
32
+ readonly target?: {
33
+ readonly kind: "page" | "contentEntry" | "term";
34
+ readonly id: string;
35
+ } | {
36
+ readonly kind: "collection";
37
+ readonly collection: string;
38
+ };
39
+ /** RFC-0025 25d: a top-level item that opens its children as columns of one wide panel. */
40
+ readonly display?: "mega";
41
+ /** Shown children only. */
42
+ readonly children: NavItem[];
43
+ }
44
+ /**
45
+ * Where a theme serves a collection's index in a locale (`undefined`: it does not). Starters own
46
+ * routes (ADR-0009); the blog starter exports one from `theme.ts`.
47
+ */
48
+ export type CollectionIndexHook = (collection: string, locale: string) => string | undefined;
49
+ export interface NavigationOptions {
50
+ readonly collectionIndex?: CollectionIndexHook;
51
+ }
52
+ /** What a lookup is built from: every node of the site in any status, and which statuses are served. */
53
+ export interface LookupData {
54
+ readonly site: Site;
55
+ readonly pages: readonly Page[];
56
+ readonly entries: readonly ContentEntry[];
57
+ readonly taxonomies: readonly Taxonomy[];
58
+ readonly terms: readonly Term[];
59
+ /** Live dev source: drafts render (everything but archived is served). Default false. */
60
+ readonly includeDrafts?: boolean;
61
+ readonly collectionIndex?: CollectionIndexHook;
62
+ }
63
+ /**
64
+ * A `MenuLookup` over a site's nodes (§7.1 table). Term items follow `archiveState` (200 only when
65
+ * the archive lists entries the site serves in the locale); a collection index comes from the theme
66
+ * hook, else the first served page (in `Site.pageIds` order) of the locale with an unfiltered
67
+ * `contentList` of that collection (answer 5).
68
+ */
69
+ export declare function menuLookup(data: LookupData): MenuLookup;
70
+ /** The shown part of a resolved menu. */
71
+ export declare function toNavigation(resolved: ResolvedMenu): Navigation;
72
+ /** `resolveMenu` + `toNavigation` over a lookup built from `data`. */
73
+ export declare function navigationFor(menu: Menu, data: LookupData, locale: string): Navigation;
74
+ /**
75
+ * The header of a site without a `primary` menu, in the `Navigation` shape: the top-level pages of
76
+ * the default locale in `Site.pageIds` order (home excluded), then the given categories (themes
77
+ * pass the served top-level ones, or none). Exactly what `navLinks` + `categoryNavLinks` list.
78
+ */
79
+ export declare function derivedNavigation(site: Site, pages: readonly Page[], categories: readonly ArchiveSummary[], locale: string): Navigation;
80
+ export interface Active {
81
+ readonly itemId: string;
82
+ readonly match: "exact" | "prefix" | "context";
83
+ /** Root → item (the breadcrumb, and the path a sidebar expands). */
84
+ readonly trail: NavItem[];
85
+ }
86
+ export interface ActiveNavItem extends NavItem {
87
+ /** `page` on the exact match, `true` on a prefix or context match. */
88
+ readonly current?: "page" | "true";
89
+ /** The active item or one of its ancestors. */
90
+ readonly inTrail: boolean;
91
+ readonly children: ActiveNavItem[];
92
+ }
93
+ export interface ActiveRoute {
94
+ /** The request path (query, fragment and a trailing slash are ignored). */
95
+ readonly path: string;
96
+ /** The entry the page renders, for context matching. */
97
+ readonly entry?: Pick<ContentEntry, "collection" | "terms">;
98
+ /** The term whose archive the page renders. */
99
+ readonly archiveTermId?: string;
100
+ }
101
+ /**
102
+ * The active item (§7.2): the first item whose href equals the path; else the longest href the
103
+ * path continues with `/` (never `/` itself); else the context — for an entry, the item for its
104
+ * primary category, then that term's nearest ancestor in the menu, then the entry's collection; for
105
+ * an archive, the term's item or its nearest ancestor's. `ancestors(termId)` lists a term's
106
+ * ancestors root first. Ties go to the first item in depth-first order; external links never match.
107
+ */
108
+ export declare function activeItem(nav: Navigation, route: ActiveRoute, ancestors?: (termId: string) => readonly string[]): Active | undefined;
109
+ /** The tree with `current` on the active item and `inTrail` on it and its ancestors. */
110
+ export declare function markActive(nav: Navigation, active?: Active): ActiveNavItem[];
111
+ /**
112
+ * Today's header rule for the derived default (kept so a site without a menu renders byte-for-byte
113
+ * the same): every item whose href is the path or a prefix of it is `current="page"`.
114
+ */
115
+ export declare function markCurrent(nav: Navigation, path: string): ActiveNavItem[];
116
+ /** The breadcrumb of the active item (root → item); empty when nothing is active. */
117
+ export declare function breadcrumbs(active?: Active): NavItem[];
118
+ /** Previous and next linked items in depth-first order around the active one (docs sidebars). */
119
+ export declare function neighbours(nav: Navigation, active?: Active): {
120
+ prev?: NavItem;
121
+ next?: NavItem;
122
+ };
123
+ /**
124
+ * Edge-cache tags of a page that renders `nav` (RFC-0003 §7.3): the menu node and the terms of
125
+ * the term items it shows. Derived navigation has no node and adds nothing (the site tag covers it).
126
+ */
127
+ export declare function navigationCacheTags(nav: Navigation | undefined): string[];
@@ -0,0 +1,382 @@
1
+ /**
2
+ * Navigation (RFC-0003 §7): menus resolved for rendering, the active item, breadcrumbs and prev/next
3
+ * for docs sidebars, and the derived header for sites without a menu. Pure functions over graph
4
+ * nodes, so the starter, previews and MCP agree on one set of rules:
5
+ *
6
+ * - an item links only to what the site serves (`resolveMenu` in `@cloudhal/core-ts/menu`): a
7
+ * missing, unpublished or retired target, an empty archive or a collection without an index
8
+ * hides the item and its subtree;
9
+ * - the active item is the exact match, then the longest prefix, then the context (an entry's
10
+ * primary category, its ancestors, then its collection);
11
+ * - without a menu, `derivedNavigation` is today's header (`navLinks` + `categoryNavLinks`).
12
+ */
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+ import { normalisePath, termName } from "@cloudhal/core-ts";
23
+ import {
24
+
25
+
26
+
27
+
28
+ resolveMenu,
29
+ } from "@cloudhal/core-ts/menu";
30
+ import { archiveState } from "./archive.js";
31
+ import { nodeCacheTag, termCacheTag } from "./cache-tags.js";
32
+ import { archiveMembers, archivePath, taxonomyIndex } from "./taxonomy.js";
33
+
34
+ /** A menu resolved for one locale: only shown items, with labels and hrefs. */
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+ /**
61
+ * Where a theme serves a collection's index in a locale (`undefined`: it does not). Starters own
62
+ * routes (ADR-0009); the blog starter exports one from `theme.ts`.
63
+ */
64
+
65
+
66
+
67
+
68
+
69
+
70
+ /** What a lookup is built from: every node of the site in any status, and which statuses are served. */
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+ /** `/<collection>/<slug>`. */
83
+ const entryHref = (e ) => `/${e.collection}/${e.slug}`;
84
+
85
+ /**
86
+ * A `MenuLookup` over a site's nodes (§7.1 table). Term items follow `archiveState` (200 only when
87
+ * the archive lists entries the site serves in the locale); a collection index comes from the theme
88
+ * hook, else the first served page (in `Site.pageIds` order) of the locale with an unfiltered
89
+ * `contentList` of that collection (answer 5).
90
+ */
91
+ export function menuLookup(data ) {
92
+ const served = (status ) =>
93
+ data.includeDrafts ? status !== "archived" : status === "published";
94
+ const pages = new Map(data.pages.map((p) => [p.id, p]));
95
+ const entries = new Map(data.entries.map((e) => [e.id, e]));
96
+ const terms = new Map(data.terms.map((t) => [t.id, t]));
97
+ const taxonomies = new Map(data.taxonomies.map((t) => [t.id, t]));
98
+ const order = new Map(data.site.pageIds.map((id, i) => [id, i]));
99
+ const counts = new Map ();
100
+ const countsFor = (locale ) => {
101
+ let c = counts.get(locale);
102
+ if (!c) {
103
+ const index = taxonomyIndex(data.taxonomies, data.terms, locale);
104
+ const members = archiveMembers(
105
+ index,
106
+ data.entries.filter((e) => e.locale === locale && served(e.status)),
107
+ );
108
+ c = new Map([...members].map(([id, list]) => [id, list.length]));
109
+ counts.set(locale, c);
110
+ }
111
+ return c;
112
+ };
113
+ const node = (n , path ) => ({
114
+ path,
115
+ title: n.title,
116
+ locale: n.locale,
117
+ served: served(n.status),
118
+ });
119
+ return {
120
+ defaultLocale: data.site.defaultLocale,
121
+ page: (id) => {
122
+ const p = pages.get(id);
123
+ return p ? node(p, p.path) : undefined;
124
+ },
125
+ entry: (id) => {
126
+ const e = entries.get(id);
127
+ return e ? node(e, entryHref(e)) : undefined;
128
+ },
129
+ term: (id, locale) => {
130
+ const term = terms.get(id);
131
+ if (!term) return undefined;
132
+ const taxonomy = taxonomies.get(term.taxonomyId);
133
+ if (!taxonomy) return undefined;
134
+ const state = archiveState(taxonomy, term, countsFor(locale).get(term.id) ?? 0, locale);
135
+ return {
136
+ name: termName(term, locale),
137
+ state: state.status,
138
+ ...(taxonomy.archive.enabled ? { path: archivePath(taxonomy, term.slug) } : {}),
139
+ };
140
+ },
141
+ collectionIndex: (collection, locale) => {
142
+ const hooked = data.collectionIndex?.(collection, locale);
143
+ if (hooked !== undefined) return hooked;
144
+ return [...data.pages]
145
+ .filter((p) => p.locale === locale && served(p.status))
146
+ .sort((a, b) => (order.get(a.id) ?? 1e9) - (order.get(b.id) ?? 1e9))
147
+ .find((p) =>
148
+ p.sections.some(
149
+ (s) => s.kind === "contentList" && s.collection === collection && !s.filter,
150
+ ),
151
+ )?.path;
152
+ },
153
+ };
154
+ }
155
+
156
+ function shownItems(items ) {
157
+ return items
158
+ .filter((i) => i.state === "shown")
159
+ .map((i) => ({
160
+ id: i.id,
161
+ kind: i.kind,
162
+ label: i.label,
163
+ ...(i.href !== undefined ? { href: i.href } : {}),
164
+ external: i.external,
165
+ newTab: i.newTab,
166
+ ...(i.target ? { target: i.target } : {}),
167
+ ...(i.display ? { display: i.display } : {}),
168
+ children: shownItems(i.children),
169
+ }));
170
+ }
171
+
172
+ /** The shown part of a resolved menu. */
173
+ export function toNavigation(resolved ) {
174
+ return {
175
+ key: resolved.key,
176
+ menuId: resolved.menuId,
177
+ locale: resolved.locale,
178
+ items: shownItems(resolved.items),
179
+ };
180
+ }
181
+
182
+ /** `resolveMenu` + `toNavigation` over a lookup built from `data`. */
183
+ export function navigationFor(menu , data , locale ) {
184
+ return toNavigation(resolveMenu(menu, menuLookup(data), locale));
185
+ }
186
+
187
+ // ───────────────────────────── derived default ─────────────────────────────
188
+
189
+ /**
190
+ * The header of a site without a `primary` menu, in the `Navigation` shape: the top-level pages of
191
+ * the default locale in `Site.pageIds` order (home excluded), then the given categories (themes
192
+ * pass the served top-level ones, or none). Exactly what `navLinks` + `categoryNavLinks` list.
193
+ */
194
+ export function derivedNavigation(
195
+ site ,
196
+ pages ,
197
+ categories ,
198
+ locale ,
199
+ ) {
200
+ const link = (id , kind , label , href ) => ({
201
+ id,
202
+ kind,
203
+ label,
204
+ href,
205
+ external: false,
206
+ newTab: false,
207
+ target: { kind, id },
208
+ children: [],
209
+ });
210
+ return {
211
+ key: "primary",
212
+ locale,
213
+ items: [
214
+ ...pages
215
+ .filter(
216
+ (p) => p.locale === site.defaultLocale && p.path !== "/" && /^\/[^/]+$/.test(p.path),
217
+ )
218
+ .map((p) => link(p.id, "page", p.title, p.path)),
219
+ ...categories
220
+ .filter((a) => a.taxonomy.key === "category" && !a.term.parentId)
221
+ .map((a) => link(a.term.id, "term", termName(a.term, locale), a.path)),
222
+ ],
223
+ };
224
+ }
225
+
226
+ // ───────────────────────────── active item (§7.2) ─────────────────────────────
227
+
228
+
229
+
230
+
231
+  
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+
244
+
245
+
246
+
247
+
248
+
249
+
250
+
251
+
252
+ /** Items depth-first with their trail (root → item). */
253
+ function flatten(
254
+ items ,
255
+ trail = [],
256
+ ) {
257
+ return items.flatMap((item) => {
258
+ const t = [...trail, item];
259
+ return [{ item, trail: t }, ...flatten(item.children, t)];
260
+ });
261
+ }
262
+
263
+ const cleanPath = normalisePath;
264
+
265
+ /**
266
+ * The active item (§7.2): the first item whose href equals the path; else the longest href the
267
+ * path continues with `/` (never `/` itself); else the context — for an entry, the item for its
268
+ * primary category, then that term's nearest ancestor in the menu, then the entry's collection; for
269
+ * an archive, the term's item or its nearest ancestor's. `ancestors(termId)` lists a term's
270
+ * ancestors root first. Ties go to the first item in depth-first order; external links never match.
271
+ */
272
+ export function activeItem(
273
+ nav ,
274
+ route ,
275
+ ancestors = () => [],
276
+ ) {
277
+ const path = cleanPath(route.path);
278
+ const all = flatten(nav.items).filter((x) => !x.item.external);
279
+ const exact = all.find((x) => x.item.href !== undefined && cleanPath(x.item.href) === path);
280
+ if (exact) return { itemId: exact.item.id, match: "exact", trail: exact.trail };
281
+ let best ;
282
+ let bestLength = 0;
283
+ for (const x of all) {
284
+ if (x.item.href === undefined) continue;
285
+ const href = cleanPath(x.item.href);
286
+ if (href === "/" || !path.startsWith(`${href}/`)) continue;
287
+ if (href.length > bestLength) {
288
+ best = x;
289
+ bestLength = href.length;
290
+ }
291
+ }
292
+ if (best) return { itemId: best.item.id, match: "prefix", trail: best.trail };
293
+ const byTerm = (termId ) =>
294
+ all.find(
295
+ (x) => x.item.target?.kind === "term" && "id" in x.item.target && x.item.target.id === termId,
296
+ );
297
+ const nearest = (termId ) => {
298
+ for (const id of [termId, ...[...ancestors(termId)].reverse()]) {
299
+ const hit = byTerm(id);
300
+ if (hit) return hit;
301
+ }
302
+ return undefined;
303
+ };
304
+ let context ;
305
+ if (route.entry) {
306
+ const primary = route.entry.terms?.category?.primary;
307
+ context = primary ? nearest(primary) : undefined;
308
+ const collection = route.entry.collection;
309
+ context ??= all.find(
310
+ (x) =>
311
+ x.item.target?.kind === "collection" &&
312
+ "collection" in x.item.target &&
313
+ x.item.target.collection === collection,
314
+ );
315
+ } else if (route.archiveTermId) context = nearest(route.archiveTermId);
316
+ return context ? { itemId: context.item.id, match: "context", trail: context.trail } : undefined;
317
+ }
318
+
319
+ /** The tree with `current` on the active item and `inTrail` on it and its ancestors. */
320
+ export function markActive(nav , active ) {
321
+ const trail = new Set(active?.trail.map((i) => i.id) ?? []);
322
+ const mark = (items ) =>
323
+ items.map((item) => ({
324
+ ...item,
325
+ ...(active?.itemId === item.id
326
+ ? { current: active.match === "exact" ? ("page" ) : ("true" ) }
327
+ : {}),
328
+ inTrail: trail.has(item.id),
329
+ children: mark(item.children),
330
+ }));
331
+ return mark(nav.items);
332
+ }
333
+
334
+ /**
335
+ * Today's header rule for the derived default (kept so a site without a menu renders byte-for-byte
336
+ * the same): every item whose href is the path or a prefix of it is `current="page"`.
337
+ */
338
+ export function markCurrent(nav , path ) {
339
+ const mark = (items ) =>
340
+ items.map((item) => {
341
+ const current =
342
+ item.href !== undefined && (path === item.href || path.startsWith(`${item.href}/`));
343
+ return {
344
+ ...item,
345
+ ...(current ? { current: "page" } : {}),
346
+ inTrail: current,
347
+ children: mark(item.children),
348
+ };
349
+ });
350
+ return mark(nav.items);
351
+ }
352
+
353
+ /** The breadcrumb of the active item (root → item); empty when nothing is active. */
354
+ export function breadcrumbs(active ) {
355
+ return active ? [...active.trail] : [];
356
+ }
357
+
358
+ /** Previous and next linked items in depth-first order around the active one (docs sidebars). */
359
+ export function neighbours(nav , active ) {
360
+ if (!active) return {};
361
+ const linked = flatten(nav.items)
362
+ .map((x) => x.item)
363
+ .filter((i) => i.href !== undefined && !i.external);
364
+ const at = linked.findIndex((i) => i.id === active.itemId);
365
+ if (at < 0) return {};
366
+ const prev = linked[at - 1];
367
+ const next = linked[at + 1];
368
+ return { ...(prev ? { prev } : {}), ...(next ? { next } : {}) };
369
+ }
370
+
371
+ /**
372
+ * Edge-cache tags of a page that renders `nav` (RFC-0003 §7.3): the menu node and the terms of
373
+ * the term items it shows. Derived navigation has no node and adds nothing (the site tag covers it).
374
+ */
375
+ export function navigationCacheTags(nav ) {
376
+ if (!nav?.menuId) return [];
377
+ const tags = [nodeCacheTag(nav.menuId)];
378
+ for (const { item } of flatten(nav.items))
379
+ if (item.target?.kind === "term" && "id" in item.target)
380
+ tags.push(termCacheTag(item.target.id));
381
+ return tags;
382
+ }