@clarusjs/theme-docs 0.1.3 → 0.3.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": "@clarusjs/theme-docs",
3
- "version": "0.1.3",
3
+ "version": "0.3.0",
4
4
  "description": "A docs theme for clarusjs: layout with header, sidebar, content and on-this-page, design tokens, dark mode, copy buttons and callouts.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -16,7 +16,7 @@
16
16
  "access": "public"
17
17
  },
18
18
  "peerDependencies": {
19
- "clarusjs": "^0.10.0"
19
+ "clarusjs": "^0.12.0"
20
20
  },
21
21
  "engines": {
22
22
  "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
@@ -39,7 +39,7 @@
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/node": "^26.6.6",
42
- "clarusjs": "^0.10.0",
42
+ "clarusjs": "^0.12.0",
43
43
  "typescript": "^7.0.2",
44
44
  "vitest": "^5.1.1",
45
45
  "vite": "^8.3.8"
package/src/layout.tscl CHANGED
@@ -4,13 +4,14 @@
4
4
  1024px the sidebar is always there, from 1280px "On this page" is a column. Everything site-specific comes from config.
5
5
  Slots: sidebar-top, sidebar-bottom, content-top, content-bottom, footer.
6
6
  --}}
7
- @import themeToggle from './theme-toggle.tscl'
8
- @import pageTransitions from './view-transitions.tscl'
9
- @import siteSearch from './search.tscl'
10
7
  @import pageHead from './page-head.tscl'
11
- @import learnStatus from './learn-status.tscl'
8
+ @import siteHeader from './parts/header.tscl'
9
+ @import docsSidebar from './parts/sidebar.tscl'
10
+ @import contents from './parts/contents.tscl'
11
+ @import pageFooter from './parts/page-footer.tscl'
12
+ @import siteFooter from './parts/footer.tscl'
12
13
  @import type { ThemeConfig, Heading } from './nav.ts'
13
- @import { sectionKey, groupsOf, crumb, pager, editHref, updatedOf, lessonsOf } from './nav.ts'
14
+ @import { sectionKey, crumb } from './nav.ts'
14
15
  @import './theme.css'
15
16
  @input config: ThemeConfig
16
17
  @input title: string
@@ -22,6 +23,8 @@
22
23
  @input url: string = ''
23
24
  {{-- The page's h2/h3 for "On this page" (Markdown pages pass them; none: the region is left out). --}}
24
25
  @input headings: Heading[] = []
26
+ {{-- A tool (a playground) rather than a page: the header and a full-height main, without sidebar, crumb or footers. --}}
27
+ @input app: boolean = false
25
28
 
26
29
  <html lang="en">
27
30
  <head>
@@ -30,136 +33,29 @@
30
33
  <body>
31
34
  {{-- First in the tab order: keyboard and screen reader users jump past the header and page list. --}}
32
35
  <a class="skip-link" href="#content">Skip to content</a>
33
- <header class="site-header">
34
- @if (sectionKey(config.sections, path)) {
35
- <button type="button" class="menu-button" popovertarget="sidebar" aria-label="Open menu">
36
- <svg
37
- width="22"
38
- height="22"
39
- viewBox="0 0 24 24"
40
- fill="none"
41
- stroke="currentColor"
42
- stroke-width="2.2"
43
- stroke-linecap="round"
44
- aria-hidden="true"
45
- >
46
- <path d="M4 7h16M4 12h16M4 17h16"></path>
47
- </svg>
48
- </button>
49
- }
50
- <a class="brand" href="/"
51
- >@if (config.brand.logo) {<img [src]="config.brand.logo" alt="" width="28" height="28">}<span>{{ config.brand.text }}@if (config.brand.accent) {<span class="js">{{ config.brand.accent }}</span>}</span></a
52
- >
53
- <nav class="top-nav" aria-label="Main">@for (s of config.sections; track s.key) {<a [href]="s.href" [aria-current]="sectionKey(config.sections, path) === s.key ? 'true' : false">{{ s.title }}</a>}</nav>
54
- <div class="header-end">
55
- {{-- On Learn pages: the XP chip, and the sidebar's lessons marked done, current or locked. --}}
56
- @if (config.learn && sectionKey(config.sections, path) === config.learn.section) {<learnStatus [lessons]="lessonsOf(config).map((l) => l.href)" [progress]="config.learn.progress" />}
57
- {{-- Kept across fragment navigations, like the theme toggle: its shortcut listener is added once. --}}
58
- @if (config.search) {<span class="persist" data-cl-persist="search"><siteSearch /></span>}
59
- @if ((config.social ?? []).length) {
60
- <span class="social">
61
- @for (link of config.social ?? []; track link.href) {
62
- <a [href]="link.href" [aria-label]="link.label" [title]="link.label"> @if (link.icon === 'github') {<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 19c-4 1.5-4-2-6-2.5m12 5v-3.5c0-1 .1-1.4-.5-2 2.8-.3 5.5-1.4 5.5-6a4.6 4.6 0 0 0-1.3-3.2 4.2 4.2 0 0 0-.1-3.2s-1.1-.3-3.5 1.3a12.3 12.3 0 0 0-6.2 0C6.5 2.8 5.4 3.1 5.4 3.1a4.2 4.2 0 0 0-.1 3.2A4.6 4.6 0 0 0 4 9.5c0 4.6 2.7 5.7 5.5 6-.6.6-.6 1.2-.5 2V21"></path></svg>} @else if (link.icon === 'npm') {<span class="npm" aria-hidden="true">npm</span>} @else {<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"></path></svg>} </a>
63
- }
64
- </span>
65
- {{-- When the header runs out of room, the social links fold into this menu (native popover). --}}
66
- <button type="button" class="more-button" popovertarget="more" aria-label="More links">
67
- <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
68
- <circle cx="5" cy="12" r="2"></circle>
69
- <circle cx="12" cy="12" r="2"></circle>
70
- <circle cx="19" cy="12" r="2"></circle>
71
- </svg>
72
- </button>
73
- <div id="more" class="more" popover>@for (link of config.social ?? []; track link.href) {<a [href]="link.href">{{ link.label }}</a>}</div>
74
- }
75
- {{-- Kept across fragment navigations: the same element, with its state. --}}
76
- <span class="persist" data-cl-persist="theme"><themeToggle /></span>
77
- @if (config.viewTransitions) {<span class="persist" data-cl-persist="view-transitions"><pageTransitions /></span>}
78
- </div>
79
- </header>
80
- @if (sectionKey(config.sections, path)) {
36
+ <siteHeader [config]="config" [path]="path" [app]="app" />
37
+ @if (app) {
38
+ <main class="content app" id="content" tabindex="-1"><slot /></main>
39
+ } @else if (sectionKey(config.sections, path)) {
81
40
  <div class="docs">
82
41
  {{-- A drawer below 1024px (popover: Escape and a click outside close it), always visible from 1024px. --}}
83
- <nav id="sidebar" class="sidebar" aria-label="Pages" popover>
84
- <div class="sidebar-head">
85
- <span>{{ config.brand.text }}{{ config.brand.accent ?? '' }}</span>
86
- <button type="button" popovertarget="sidebar" popovertargetaction="hide" aria-label="Close the menu">
87
- <svg
88
- width="20"
89
- height="20"
90
- viewBox="0 0 24 24"
91
- fill="none"
92
- stroke="currentColor"
93
- stroke-width="2.2"
94
- stroke-linecap="round"
95
- aria-hidden="true"
96
- >
97
- <path d="M6 6l12 12M18 6L6 18"></path>
98
- </svg>
99
- </button>
100
- </div>
101
- <slot name="sidebar-top"></slot>
102
- @for (group of groupsOf(config.sections, path); track group.title) {
103
- <p class="group">{{ group.title }}</p>
104
- <ul>
105
- @for (item of group.items; track item.href) {
106
- <li>
107
- <a [href]="item.href" [aria-current]="item.href === path ? 'page' : false">{{ item.title }}</a>
108
- </li>
109
- }
110
- </ul>
111
- }
112
- <slot name="sidebar-bottom"></slot>
113
- {{-- On phones, the header's links live here. --}}
114
- <div class="sidebar-links">@for (s of config.sections; track s.key) {<a [href]="s.href">{{ s.title }}</a>} @for (link of config.social ?? []; track link.href) {<a [href]="link.href">{{ link.label }}</a>}</div>
115
- </nav>
42
+ <docsSidebar [config]="config" [path]="path">@slot('top') {<slot name="sidebar-top"></slot>}@slot('bottom') {<slot name="sidebar-bottom"></slot>}</docsSidebar>
116
43
  {{-- tabindex -1: the skip link (and navigation) can move focus here. --}}
117
44
  <main class="content" id="content" tabindex="-1">
118
45
  <p class="crumb">{{ crumb(config.sections, path) }}</p>
119
- @if (headings.length) {
120
- <details class="toc-inline">
121
- <summary>On this page</summary>
122
- <ul>
123
- @for (h of headings; track h.id) {
124
- <li [class]="h.level === 3 ? 'sub' : false">
125
- <a [href]="'#' + h.id">{{ h.text }}</a>
126
- </li>
127
- }
128
- </ul>
129
- </details>
130
- }
46
+ <contents [headings]="headings" [inline]="true" />
131
47
  <slot name="content-top"></slot>
132
48
  <slot />
133
49
  <slot name="content-bottom"></slot>
134
- <footer class="page-footer">
135
- @if (editHref(config, source || path)) {<a class="edit" [href]="editHref(config, source || path)">Edit this page on GitHub</a>}
136
- @if (updatedOf(config, source || path)) {
137
- <p class="updated">
138
- Last updated
139
- <time [datetime]="updatedOf(config, source || path)?.iso">{{
140
- updatedOf(config, source || path)?.text
141
- }}</time>
142
- </p>
143
- }
144
- <nav class="pager" aria-label="Previous and next">@if (pager(config.sections, path).prev.href) {<a class="prev" [href]="pager(config.sections, path).prev.href"><small>Previous</small>{{ pager(config.sections, path).prev.title }}</a>} @if (pager(config.sections, path).next.href) {<a class="next" [href]="pager(config.sections, path).next.href"><small>Next</small>{{ pager(config.sections, path).next.title }}</a>}</nav>
145
- </footer>
50
+ <pageFooter [config]="config" [path]="path" [source]="source" />
146
51
  </main>
147
- @if (headings.length) {
148
- <aside class="toc" aria-label="On this page">
149
- <p>On this page</p>
150
- <ul>
151
- @for (h of headings; track h.id) {
152
- <li [class]="h.level === 3 ? 'sub' : false">
153
- <a [href]="'#' + h.id">{{ h.text }}</a>
154
- </li>
155
- }
156
- </ul>
157
- </aside>
158
- }
52
+ <contents [headings]="headings" />
159
53
  </div>
160
54
  } @else {
161
55
  <main class="content home" id="content" tabindex="-1"><slot /></main>
162
56
  }
163
- <footer class="site-footer"><slot name="footer">@if (config.footer) {<p>{{ config.footer }}</p>}</slot></footer>
57
+ @if (!app) {
58
+ <siteFooter [config]="config"><slot name="footer">@if (config.footer) {<p>{{ config.footer }}</p>}</slot></siteFooter>
59
+ }
164
60
  </body>
165
61
  </html>
package/src/nav.ts CHANGED
@@ -10,6 +10,28 @@ export type Social = { label: string; href: string; icon: 'github' | 'npm' | 'li
10
10
  /** A heading on the page, for "On this page". */
11
11
  export type Heading = { id: string; text: string; level: number }
12
12
 
13
+ /**
14
+ * What a site's layout passes to a theme's `layout.tscl`: the contract a theme implements (#362). `config` and
15
+ * `title` always; the rest optional, with the defaults the docs theme uses. A theme's layout also has the slots
16
+ * `sidebar-top`, `sidebar-bottom`, `content-top`, `content-bottom` and `footer`, beside its default one.
17
+ * @see https://clarusjs.com/guide/writing-a-theme
18
+ */
19
+ export type LayoutInputs = {
20
+ config: ThemeConfig
21
+ title: string
22
+ description?: string
23
+ /** The page's sidebar entry (default '/'). */
24
+ path?: string
25
+ /** The page's own route, when it differs from its sidebar entry. */
26
+ source?: string
27
+ /** The page's own address, when path names its sidebar entry instead. */
28
+ url?: string
29
+ /** The page's h2 and h3, for "On this page". */
30
+ headings?: Heading[]
31
+ /** A tool rather than a page: no sidebar, crumb or footers. */
32
+ app?: boolean
33
+ }
34
+
13
35
  export type ThemeConfig = {
14
36
  /** The site's name in the header: `{ text: 'clarus', accent: '.js' }` shows the accent in the brand colour. */
15
37
  brand: { text: string; accent?: string; logo?: string }
@@ -0,0 +1,32 @@
1
+ {{--
2
+ "On this page" (a public part, #360): the page's h2/h3 as a column (an aside, shown from 1280px) or, with inline, a
3
+ collapsible box above the content (below 1280px). Nothing without headings. Replace it with
4
+ themeDocs({ components: { contents } }) (#361).
5
+ --}}
6
+ @import type { Heading } from '../nav.ts'
7
+ @input headings: Heading[] = []
8
+ @input inline: boolean = false
9
+
10
+ @if (headings.length && inline) {
11
+ <details class="toc-inline">
12
+ <summary>On this page</summary>
13
+ <ul>
14
+ @for (h of headings; track h.id) {
15
+ <li [class]="h.level === 3 ? 'sub' : false">
16
+ <a [href]="'#' + h.id">{{ h.text }}</a>
17
+ </li>
18
+ }
19
+ </ul>
20
+ </details>
21
+ } @else if (headings.length) {
22
+ <aside class="toc" aria-label="On this page">
23
+ <p>On this page</p>
24
+ <ul>
25
+ @for (h of headings; track h.id) {
26
+ <li [class]="h.level === 3 ? 'sub' : false">
27
+ <a [href]="'#' + h.id">{{ h.text }}</a>
28
+ </li>
29
+ }
30
+ </ul>
31
+ </aside>
32
+ }
@@ -0,0 +1,8 @@
1
+ {{--
2
+ The site footer (a public part, #360): its default content is config.footer. Replace it with
3
+ themeDocs({ components: { footer } }) (#361).
4
+ --}}
5
+ @import type { ThemeConfig } from '../nav.ts'
6
+ @input config: ThemeConfig
7
+
8
+ <footer class="site-footer"><slot>@if (config.footer) {<p>{{ config.footer }}</p>}</slot></footer>
@@ -0,0 +1,62 @@
1
+ {{--
2
+ The site header (a public part, #360): the menu button, brand, section links, Learn status, search, social links and
3
+ the theme toggle. Replace it with themeDocs({ components: { header } }) (#361).
4
+ --}}
5
+ @import themeToggle from '../theme-toggle.tscl'
6
+ @import pageTransitions from '../view-transitions.tscl'
7
+ @import siteSearch from '../search.tscl'
8
+ @import learnStatus from '../learn-status.tscl'
9
+ @import type { ThemeConfig } from '../nav.ts'
10
+ @import { sectionKey, lessonsOf } from '../nav.ts'
11
+ @input config: ThemeConfig
12
+ @input path: string = '/'
13
+ {{-- An app page (a tool) has no sidebar, so no menu button. --}}
14
+ @input app: boolean = false
15
+
16
+ <header class="site-header">
17
+ @if (!app && sectionKey(config.sections, path)) {
18
+ <button type="button" class="menu-button" popovertarget="sidebar" aria-label="Open menu">
19
+ <svg
20
+ width="22"
21
+ height="22"
22
+ viewBox="0 0 24 24"
23
+ fill="none"
24
+ stroke="currentColor"
25
+ stroke-width="2.2"
26
+ stroke-linecap="round"
27
+ aria-hidden="true"
28
+ >
29
+ <path d="M4 7h16M4 12h16M4 17h16"></path>
30
+ </svg>
31
+ </button>
32
+ }
33
+ <a class="brand" href="/"
34
+ >@if (config.brand.logo) {<img [src]="config.brand.logo" alt="" width="28" height="28">}<span>{{ config.brand.text }}@if (config.brand.accent) {<span class="js">{{ config.brand.accent }}</span>}</span></a
35
+ >
36
+ <nav class="top-nav" aria-label="Main">@for (s of config.sections; track s.key) {<a [href]="s.href" [aria-current]="sectionKey(config.sections, path) === s.key ? 'true' : false">{{ s.title }}</a>}</nav>
37
+ <div class="header-end">
38
+ {{-- On Learn pages: the XP chip, and the sidebar's lessons marked done, current or locked. --}}
39
+ @if (config.learn && sectionKey(config.sections, path) === config.learn.section) {<learnStatus [lessons]="lessonsOf(config).map((l) => l.href)" [progress]="config.learn.progress" />}
40
+ {{-- Kept across fragment navigations, like the theme toggle: its shortcut listener is added once. --}}
41
+ @if (config.search) {<span class="persist" data-cl-persist="search"><siteSearch /></span>}
42
+ @if ((config.social ?? []).length) {
43
+ <span class="social">
44
+ @for (link of config.social ?? []; track link.href) {
45
+ <a [href]="link.href" [aria-label]="link.label" [title]="link.label"> @if (link.icon === 'github') {<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 19c-4 1.5-4-2-6-2.5m12 5v-3.5c0-1 .1-1.4-.5-2 2.8-.3 5.5-1.4 5.5-6a4.6 4.6 0 0 0-1.3-3.2 4.2 4.2 0 0 0-.1-3.2s-1.1-.3-3.5 1.3a12.3 12.3 0 0 0-6.2 0C6.5 2.8 5.4 3.1 5.4 3.1a4.2 4.2 0 0 0-.1 3.2A4.6 4.6 0 0 0 4 9.5c0 4.6 2.7 5.7 5.5 6-.6.6-.6 1.2-.5 2V21"></path></svg>} @else if (link.icon === 'npm') {<span class="npm" aria-hidden="true">npm</span>} @else {<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"></path></svg>} </a>
46
+ }
47
+ </span>
48
+ {{-- When the header runs out of room, the social links fold into this menu (native popover). --}}
49
+ <button type="button" class="more-button" popovertarget="more" aria-label="More links">
50
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
51
+ <circle cx="5" cy="12" r="2"></circle>
52
+ <circle cx="12" cy="12" r="2"></circle>
53
+ <circle cx="19" cy="12" r="2"></circle>
54
+ </svg>
55
+ </button>
56
+ <div id="more" class="more" popover>@for (link of config.social ?? []; track link.href) {<a [href]="link.href">{{ link.label }}</a>}</div>
57
+ }
58
+ {{-- Kept across fragment navigations: the same element, with its state. --}}
59
+ <span class="persist" data-cl-persist="theme"><themeToggle /></span>
60
+ @if (config.viewTransitions) {<span class="persist" data-cl-persist="view-transitions"><pageTransitions /></span>}
61
+ </div>
62
+ </header>
@@ -0,0 +1,21 @@
1
+ {{--
2
+ Under the content (a public part, #360): the edit link, when the page was last updated, and the previous and next
3
+ pages. Replace it with themeDocs({ components: { pageFooter } }) (#361).
4
+ --}}
5
+ @import type { ThemeConfig } from '../nav.ts'
6
+ @import { editHref, updatedOf, pager } from '../nav.ts'
7
+ @input config: ThemeConfig
8
+ @input path: string = '/'
9
+ {{-- The page's own route, when it differs from its sidebar entry (see the layout's source input). --}}
10
+ @input source: string = ''
11
+
12
+ <footer class="page-footer">
13
+ @if (editHref(config, source || path)) {<a class="edit" [href]="editHref(config, source || path)">Edit this page on GitHub</a>}
14
+ @if (updatedOf(config, source || path)) {
15
+ <p class="updated">
16
+ Last updated
17
+ <time [datetime]="updatedOf(config, source || path)?.iso">{{ updatedOf(config, source || path)?.text }}</time>
18
+ </p>
19
+ }
20
+ <nav class="pager" aria-label="Previous and next">@if (pager(config.sections, path).prev.href) {<a class="prev" [href]="pager(config.sections, path).prev.href"><small>Previous</small>{{ pager(config.sections, path).prev.title }}</a>} @if (pager(config.sections, path).next.href) {<a class="next" [href]="pager(config.sections, path).next.href"><small>Next</small>{{ pager(config.sections, path).next.title }}</a>}</nav>
21
+ </footer>
@@ -0,0 +1,42 @@
1
+ {{--
2
+ The page list (a public part, #360): a drawer below 1024px (popover: Escape and a click outside close it), always
3
+ visible from 1024px. Slots: top, bottom. Replace it with themeDocs({ components: { sidebar } }) (#361).
4
+ --}}
5
+ @import type { ThemeConfig } from '../nav.ts'
6
+ @import { groupsOf } from '../nav.ts'
7
+ @input config: ThemeConfig
8
+ @input path: string = '/'
9
+
10
+ <nav id="sidebar" class="sidebar" aria-label="Pages" popover>
11
+ <div class="sidebar-head">
12
+ <span>{{ config.brand.text }}{{ config.brand.accent ?? '' }}</span>
13
+ <button type="button" popovertarget="sidebar" popovertargetaction="hide" aria-label="Close the menu">
14
+ <svg
15
+ width="20"
16
+ height="20"
17
+ viewBox="0 0 24 24"
18
+ fill="none"
19
+ stroke="currentColor"
20
+ stroke-width="2.2"
21
+ stroke-linecap="round"
22
+ aria-hidden="true"
23
+ >
24
+ <path d="M6 6l12 12M18 6L6 18"></path>
25
+ </svg>
26
+ </button>
27
+ </div>
28
+ <slot name="top"></slot>
29
+ @for (group of groupsOf(config.sections, path); track group.title) {
30
+ <p class="group">{{ group.title }}</p>
31
+ <ul>
32
+ @for (item of group.items; track item.href) {
33
+ <li>
34
+ <a [href]="item.href" [aria-current]="item.href === path ? 'page' : false">{{ item.title }}</a>
35
+ </li>
36
+ }
37
+ </ul>
38
+ }
39
+ <slot name="bottom"></slot>
40
+ {{-- On phones, the header's links live here. --}}
41
+ <div class="sidebar-links">@for (s of config.sections; track s.key) {<a [href]="s.href">{{ s.title }}</a>} @for (link of config.social ?? []; track link.href) {<a [href]="link.href">{{ link.label }}</a>}</div>
42
+ </nav>
package/src/search.js CHANGED
@@ -15,7 +15,10 @@ export const CHUNK = 64
15
15
 
16
16
  /** The site's base path ('/' unless Vite's `base` is set), where the search index is fetched from. */
17
17
  /** @type {string} */
18
- export const base = /** @type {any} */ (import.meta).env?.BASE_URL ?? '/' // Vite's import.meta.env, when there is one
18
+ // Written out as import.meta.env.BASE_URL, which Vite replaces: Vite's dev module runner refuses any other way of
19
+ // reading import.meta.env (a cast in parentheses included). Outside Vite there is no env: '/'.
20
+ // @ts-ignore import.meta.env is Vite's
21
+ export const base = import.meta.env?.BASE_URL ?? '/'
19
22
 
20
23
  /** @param {string} text @returns {string[]} lowercase words of two or more letters, accents folded */
21
24
  export function tokens(text) {
package/src/theme.css CHANGED
@@ -99,6 +99,9 @@ a:focus-visible, button:focus-visible { outline: 2px solid var(--accent); outlin
99
99
  margin: 0 auto;
100
100
  padding: 32px max(16px, env(safe-area-inset-right, 0px)) 56px max(16px, env(safe-area-inset-left, 0px));
101
101
  }
102
+ /* app: a tool that fills the window under the header (a playground); it lays itself out. */
103
+ .content.app { max-width: none; margin: 0; padding: 0; height: calc(100dvh - var(--header-height)); display: flex; flex-direction: column; }
104
+ @media (max-width: 899px) { .content.app { height: auto; } }
102
105
  h1, h2 { line-height: 1.2; text-wrap: balance; }
103
106
  h1 { font-size: clamp(30px, 5vw, 40px); margin: 0 0 16px; letter-spacing: -0.01em; }
104
107
  h2 { font-size: 22px; margin: 40px 0 12px; }
package/src/vite.d.ts CHANGED
@@ -7,12 +7,31 @@ export type Options = {
7
7
  * false: no search index (it's written to the client output's search/ after the build)
8
8
  */
9
9
  search?: boolean;
10
+ /**
11
+ * write llms.txt and llms-full.txt to the client output after the build (llmstxt.org)
12
+ */
13
+ llms?: LlmsOptions;
14
+ /**
15
+ * parts of the layout replaced by files of the site's own, from
16
+ * the Vite root: `{ header: '/src/theme/header.tscl' }`. Each gets the inputs and slots the theme's part gets.
17
+ */
18
+ components?: Partial<Record<PartName, string>>;
19
+ };
20
+ export type PartName = 'header' | 'sidebar' | 'contents' | 'pageFooter' | 'footer';
21
+ export type LlmsOptions = {
22
+ /**
23
+ * the site's name, the file's heading
24
+ */
25
+ title: string;
26
+ /**
27
+ * one or two sentences about the site
28
+ */
29
+ summary?: string;
30
+ /**
31
+ * the public address (https://example.com): links are absolute with it, root-relative without
32
+ */
33
+ site?: string;
10
34
  };
11
- /**
12
- * @typedef {object} Options
13
- * @property {string} [pages] the pages folder, from the Vite root (default src/pages)
14
- * @property {boolean} [search] false: no search index (it's written to the client output's search/ after the build)
15
- */
16
35
  /**
17
36
  * Reads the pages for the sidebar (served as `virtual:theme-docs/pages`) and writes the search index after the build.
18
37
  * @param {Options} [options]
@@ -45,3 +64,20 @@ export declare function sectionsOf(html: string, url: string): import('./search.
45
64
  * @returns {Map<string, string>}
46
65
  */
47
66
  export declare function buildIndex(sections: import('./search.js').Section[]): Map<string, string>;
67
+ /**
68
+ * llms.txt (llmstxt.org): the site's title and summary, then each sidebar group's pages as links with their
69
+ * descriptions.
70
+ * @param {string} dir the pages folder
71
+ * @param {LlmsOptions} options
72
+ * @returns {string}
73
+ */
74
+ export declare function llmsTxt(dir: string, options: LlmsOptions): string;
75
+ /**
76
+ * llms-full.txt: the same pages' text, one after another. A Markdown page is its Markdown (no frontmatter, no leading
77
+ * component import lines); a template page is what `textOf(href)` gives (its built page's text).
78
+ * @param {string} dir the pages folder
79
+ * @param {LlmsOptions} options
80
+ * @param {(href: string) => string} textOf
81
+ * @returns {string}
82
+ */
83
+ export declare function llmsFull(dir: string, options: LlmsOptions, textOf: (href: string) => string): string;
package/src/vite.js CHANGED
@@ -2,8 +2,10 @@
2
2
  // `virtual:theme-docs/pages`, so the sidebar data (not the files) reaches pages rendered in the browser too.
3
3
  // Plain JavaScript: vite.config loads it from node_modules, where Node doesn't strip types. Types are the JSDoc here;
4
4
  // vite.d.ts is generated from it (pnpm types; typecheck and prepack run it).
5
- import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
6
- import { join, resolve } from 'node:path'
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
6
+ import { dirname, join, resolve } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { parse } from 'clarusjs/compiler'
7
9
  import { gitDates } from 'clarusjs/vite'
8
10
  import { CHUNK, termFile, tokens } from './search.js'
9
11
 
@@ -13,8 +15,79 @@ const ID = 'virtual:theme-docs/pages'
13
15
  * @typedef {object} Options
14
16
  * @property {string} [pages] the pages folder, from the Vite root (default src/pages)
15
17
  * @property {boolean} [search] false: no search index (it's written to the client output's search/ after the build)
18
+ * @property {LlmsOptions} [llms] write llms.txt and llms-full.txt to the client output after the build (llmstxt.org)
19
+ * @property {Partial<Record<PartName, string>>} [components] parts of the layout replaced by files of the site's own, from
20
+ * the Vite root: `{ header: '/src/theme/header.tscl' }`. Each gets the inputs and slots the theme's part gets.
16
21
  */
17
22
 
23
+ /** @typedef {'header' | 'sidebar' | 'contents' | 'pageFooter' | 'footer'} PartName */
24
+
25
+ /**
26
+ * @typedef {object} LlmsOptions
27
+ * @property {string} title the site's name, the file's heading
28
+ * @property {string} [summary] one or two sentences about the site
29
+ * @property {string} [site] the public address (https://example.com): links are absolute with it, root-relative without
30
+ */
31
+
32
+ /** The layout's replaceable parts (#361) and their files in src/parts/. */
33
+ const PARTS = { header: 'header.tscl', sidebar: 'sidebar.tscl', contents: 'contents.tscl', pageFooter: 'page-footer.tscl', footer: 'footer.tscl' }
34
+ const PARTS_DIR = fileURLToPath(new URL('./parts/', import.meta.url))
35
+ const real = (/** @type {string} */ p) => { try { return realpathSync(p) } catch { return p } }
36
+
37
+ /**
38
+ * A .tscl file's inputs (name, and whether it has a default) and slot names ('default' for the unnamed one).
39
+ * @param {string} file
40
+ */
41
+ function contractOf(file) {
42
+ const parsed = parse(readFileSync(file, 'utf8'), file)
43
+ /** @type {Set<string>} */
44
+ const slots = new Set()
45
+ /** @param {any[]} nodes */
46
+ const walk = (nodes) => {
47
+ for (const n of nodes) {
48
+ if (n.type === 'element' && n.tag === 'slot') {
49
+ const name = n.attrs.find((/** @type {any} */ a) => a.name === 'name' && a.kind === 'static')
50
+ slots.add(name ? String(name.value) : 'default')
51
+ }
52
+ for (const key of ['children', 'empty']) if (Array.isArray(n[key])) walk(n[key])
53
+ if (n.type === 'if') for (const b of n.branches) walk(b.children)
54
+ }
55
+ }
56
+ walk(parsed.nodes)
57
+ return { inputs: parsed.inputs.map((i) => ({ name: i.name, required: i.default === undefined })), slots }
58
+ }
59
+
60
+ /**
61
+ * The site's replacements for the layout's parts, as absolute paths by part file, checked against the parts they
62
+ * replace: every part named exists, every file exists, a replacement needs no input the layout doesn't pass, and has
63
+ * every slot the layout fills.
64
+ * @param {Partial<Record<string, string>>} components
65
+ * @param {string} root
66
+ * @returns {Map<string, string>}
67
+ */
68
+ function overridesOf(components, root) {
69
+ /** @type {Map<string, string>} */
70
+ const out = new Map()
71
+ for (const [key, path] of Object.entries(components)) {
72
+ const part = /** @type {Record<string, string>} */ (PARTS)[key]
73
+ if (!part) throw new Error(`themeDocs: components.${key} isn't a part of the theme; the parts are ${Object.keys(PARTS).join(', ')}`)
74
+ if (!path) continue
75
+ const file = resolve(root, path.startsWith('/') ? '.' + path : path)
76
+ if (!existsSync(file)) throw new Error(`themeDocs: components.${key}: no file at ${path}`)
77
+ const theirs = contractOf(join(PARTS_DIR, part))
78
+ const mine = contractOf(file)
79
+ const passed = new Set(theirs.inputs.map((i) => i.name))
80
+ for (const i of mine.inputs) {
81
+ if (i.required && !passed.has(i.name)) throw new Error(`themeDocs: components.${key} (${path}) requires @input ${i.name}, which the layout never passes: give it a default, or remove it`)
82
+ }
83
+ for (const slot of theirs.slots) {
84
+ if (!mine.slots.has(slot)) throw new Error(`themeDocs: components.${key} (${path}) has no ${slot === 'default' ? '<slot />' : `<slot name="${slot}">`}, which the layout fills`)
85
+ }
86
+ out.set(real(join(PARTS_DIR, part)), file)
87
+ }
88
+ return out
89
+ }
90
+
18
91
  /**
19
92
  * Reads the pages for the sidebar (served as `virtual:theme-docs/pages`) and writes the search index after the build.
20
93
  * @param {Options} [options]
@@ -22,15 +95,37 @@ const ID = 'virtual:theme-docs/pages'
22
95
  */
23
96
  export function themeDocs(options = {}) {
24
97
  let dir = resolve(options.pages ?? 'src/pages')
98
+ /** @type {Map<string, string>} */
99
+ let overrides = new Map()
25
100
  return {
26
101
  name: 'clarusjs:theme-docs',
102
+ // Before Vite resolves the layout's relative import of a part itself.
103
+ enforce: 'pre',
104
+ // The replacements, for clarusjs to find like its own components (their styles and islands): no page imports
105
+ // them by path, and they may be outside src/.
106
+ api: {
107
+ /** @param {string} root */
108
+ clarusComponents: (root) => [...overridesOf(options.components ?? {}, root).values()],
109
+ },
27
110
  /** @param {{ root: string }} config */
28
111
  configResolved(config) {
29
112
  dir = resolve(config.root, options.pages ?? 'src/pages')
113
+ overrides = overridesOf(options.components ?? {}, config.root)
30
114
  },
31
- /** @param {string} id */
32
- resolveId(id) {
33
- return id === ID ? '\0' + ID : undefined
115
+ /**
116
+ * @param {string} id
117
+ * @param {string} [importer]
118
+ */
119
+ resolveId(id, importer) {
120
+ if (id === ID) return '\0' + ID
121
+ // The layout's import of a part the site replaced (./parts/x.tscl from the theme): the site's file.
122
+ // The query (?render: the layout rendered in the browser) stays on the site's file.
123
+ if (overrides.size && importer && id.startsWith('./parts/')) {
124
+ const [path, query] = id.split('?', 2)
125
+ const file = overrides.get(real(resolve(dirname(importer.replace(/\?.*$/, '')), /** @type {string} */ (path))))
126
+ if (file) return query === undefined ? file : `${file}?${query}`
127
+ }
128
+ return undefined
34
129
  },
35
130
  /** @param {string} id */
36
131
  load(id) {
@@ -41,8 +136,21 @@ export function themeDocs(options = {}) {
41
136
  order: 'post',
42
137
  /** @param {any} builder */
43
138
  async handler(builder) {
44
- if (options.search === false) return
45
139
  const out = resolve(builder.config.root, builder.environments.client.config.build.outDir)
140
+ if (options.llms) {
141
+ const base = builder.config.base.replace(/\/$/, '')
142
+ // A template page's text: its built page, as the search index reads it.
143
+ /** @param {string} href */
144
+ const textOf = (href) => {
145
+ const file = join(out, href === '/' ? 'index.html' : href.slice(1) + '/index.html')
146
+ let html = ''
147
+ try { html = readFileSync(file, 'utf8') } catch { return '' }
148
+ return sectionsOf(html, base + href).map((x) => [x.h, x.t].filter(Boolean).join('\n\n')).join('\n\n')
149
+ }
150
+ writeFileSync(join(out, 'llms.txt'), llmsTxt(dir, options.llms))
151
+ writeFileSync(join(out, 'llms-full.txt'), llmsFull(dir, options.llms, textOf))
152
+ }
153
+ if (options.search === false) return
46
154
  const base = builder.config.base.replace(/\/$/, '')
47
155
  /** @type {import('./search.js').Section[]} */
48
156
  const sections = []
@@ -116,6 +224,13 @@ const plain = (html) => html.replace(/<[^>]*>/g, (tag) => (BLOCK.test(tag) ? ' '
116
224
  .replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (all, e) => e[0] !== '#' ? ENTITIES[e.toLowerCase()] ?? all : String.fromCodePoint(e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : Number(e.slice(1))))
117
225
  .replace(/\s+/g, ' ').trim()
118
226
 
227
+ /**
228
+ * An element (its tag, through its closing tag) whose class attribute has `name` as a whole token.
229
+ * @param {string} tag
230
+ * @param {string} name
231
+ */
232
+ const withClass = (tag, name) => new RegExp(`<${tag}\\b[^>]*\\bclass="(?:[^"]*\\s)?${name}(?:\\s[^"]*)?"[^>]*>[\\s\\S]*?<\\/${tag}>`)
233
+
119
234
  /**
120
235
  * A built page's search sections: its main content (main#content, without the theme's crumb, inline contents and
121
236
  * footer) split at each h1-h3 with an id. None for pages without one, noindex pages and pages with
@@ -131,9 +246,11 @@ export function sectionsOf(html, url) {
131
246
  if (main === undefined || /\bdata-search="false"/.test(main)) return []
132
247
  const body = main.replace(/<!--[\s\S]*?-->/g, '')
133
248
  .replace(/<(script|style|template)\b[\s\S]*?<\/\1>/gi, '')
134
- .replace(/<p class="crumb">[\s\S]*?<\/p>/, '')
135
- .replace(/<details class="toc-inline">[\s\S]*?<\/details>/, '')
136
- .replace(/<footer class="page-footer">[\s\S]*?<\/footer>/, '')
249
+ // By whole class token: the layout's parts carry their scope class too (class="page-footer cl-c-…"), and a class
250
+ // that only starts the same (crumb-note) isn't one of them.
251
+ .replace(withClass('p', 'crumb'), '')
252
+ .replace(withClass('details', 'toc-inline'), '')
253
+ .replace(withClass('footer', 'page-footer'), '')
137
254
  .replace(/<a class="header-anchor"[\s\S]*?<\/a>/g, '')
138
255
  const parts = body.split(/(<h[1-3]\b[^>]*\bid="[^"]*"[^>]*>[\s\S]*?<\/h[1-3]>)/i)
139
256
  const page = plain(/<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(body)?.[1] ?? /<title>([\s\S]*?)<\/title>/i.exec(html)?.[1] ?? '')
@@ -201,3 +318,65 @@ function frontmatter(text) {
201
318
 
202
319
  /** @param {string} name */
203
320
  const words = (name) => name.replace(/[-_]+/g, ' ').replace(/^\w/, (c) => c.toUpperCase())
321
+
322
+ /**
323
+ * The pages llms.txt lists, with their descriptions: those in the sidebar (not hidden, not dynamic, not 404/500), in
324
+ * groups ordered by their lowest page `order` (pages without a group last, as "Other pages").
325
+ * @param {string} dir
326
+ */
327
+ function llmsPages(dir) {
328
+ const pages = readPages(dir).filter((p) => !p.hidden && p.href !== '/404' && p.href !== '/500')
329
+ /** @type {Map<string, (import('./nav.ts').PageInfo & { description?: string; text: string })[]>} */
330
+ const groups = new Map()
331
+ for (const p of pages) {
332
+ const text = readFileSync(join(dir, /** @type {string} */ (p.file)), 'utf8')
333
+ const description = /\.md$/.test(p.file ?? '') ? frontmatter(text).description : undefined
334
+ const key = p.group ?? ''
335
+ if (!groups.has(key)) groups.set(key, [])
336
+ groups.get(key)?.push({ ...p, ...(description ? { description } : {}), text })
337
+ }
338
+ const rank = (/** @type {string} */ key) => (key === '' ? Infinity : Math.min(...(groups.get(key) ?? []).map((p) => p.order ?? Infinity)))
339
+ return [...groups.keys()].sort((a, b) => rank(a) - rank(b)).map((key) => ({
340
+ title: key || 'Other pages',
341
+ pages: (groups.get(key) ?? []).sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity) || a.title.localeCompare(b.title)),
342
+ }))
343
+ }
344
+
345
+ /** @param {LlmsOptions} o */
346
+ const llmsHead = (o) => `# ${o.title}\n${o.summary ? `\n> ${o.summary}\n` : ''}`
347
+ /** @param {LlmsOptions} o @param {string} href */
348
+ const llmsUrl = (o, href) => (o.site ? o.site.replace(/\/$/, '') : '') + href
349
+
350
+ /**
351
+ * llms.txt (llmstxt.org): the site's title and summary, then each sidebar group's pages as links with their
352
+ * descriptions.
353
+ * @param {string} dir the pages folder
354
+ * @param {LlmsOptions} options
355
+ * @returns {string}
356
+ */
357
+ export function llmsTxt(dir, options) {
358
+ const sections = llmsPages(dir).map(({ title, pages }) =>
359
+ `## ${title}\n\n${pages.map((p) => `- [${p.title}](${llmsUrl(options, p.href)})${p.description ? `: ${p.description}` : ''}`).join('\n')}\n`)
360
+ return [llmsHead(options), ...sections].join('\n')
361
+ }
362
+
363
+ /**
364
+ * llms-full.txt: the same pages' text, one after another. A Markdown page is its Markdown (no frontmatter, no leading
365
+ * component import lines); a template page is what `textOf(href)` gives (its built page's text).
366
+ * @param {string} dir the pages folder
367
+ * @param {LlmsOptions} options
368
+ * @param {(href: string) => string} textOf
369
+ * @returns {string}
370
+ */
371
+ export function llmsFull(dir, options, textOf) {
372
+ const parts = [llmsHead(options)]
373
+ for (const { pages } of llmsPages(dir)) {
374
+ for (const p of pages) {
375
+ const body = /\.md$/.test(p.file ?? '')
376
+ ? p.text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').replace(/^(?:[ \t]*(?:@import\b[^\n]*)?\r?\n)+/, '').trim()
377
+ : textOf(p.href).trim()
378
+ parts.push(`---\n\nSource: ${llmsUrl(options, p.href)}\n\n${body}\n`)
379
+ }
380
+ }
381
+ return parts.join('\n')
382
+ }