@docs-sdk-dev/solid 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +4 -2
- package/assets/agent.ts +11 -0
- package/assets/client.tsx +65 -0
- package/assets/copy.ts +30 -0
- package/assets/examples.tsx +96 -0
- package/assets/highlight.ts +64 -0
- package/assets/labels.ts +109 -0
- package/assets/render.tsx +198 -0
- package/assets/search.tsx +99 -0
- package/assets/style.css +779 -0
- package/assets/virtual.d.ts +6 -0
- package/dist/component-reference.d.ts +55 -0
- package/dist/component-reference.js +146 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +158 -0
- package/package.json +38 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lenso contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Docs SDK Solid Adapter
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@docs-sdk-dev/solid` supplies the Solid 2 static site renderer and UI SDK example previews for the Docs SDK CLI. Install it alongside Core and CLI at the same version.
|
|
4
|
+
|
|
5
|
+
Import `componentReference` from `@docs-sdk-dev/solid/component-reference` to build pages from exported Solid components (functions or consts) with local props types. Extraction comes from `@docs-sdk-dev/typescript`; the preset adds the Solid example entity, installation text and page template. The props table gains a Default column when any prop has a `@default` tag, and marks `@deprecated` props. The text the preset writes inside sections (the installation, preview and source sentences, table headers, Yes/No) follows the entry's `locale`: English and French are built in, a regional locale uses its language, others use English, and `componentReference({ text: { fr: { required: "Obligatoire" } } })` replaces single strings. Section titles are named per entry with section overrides, like any template's. The sidebar and edition switcher come from Core `buildNavigation`. Set an entry's `example` to any project-relative module that exports a default component. The build bundles exactly the declared examples, each as its own chunk, and previews load only when opened. Supply `site/style.css` to override the default stylesheet.
|
package/assets/agent.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createAgent } from "@ui-sdk/solid/agent"
|
|
2
|
+
|
|
3
|
+
// Agents may open example previews and use search; nothing on the site changes data, so no step needs a person.
|
|
4
|
+
const allowed = new Set(["collapsible", "dialog", "command"])
|
|
5
|
+
|
|
6
|
+
export function connect() {
|
|
7
|
+
const agent = createAgent({ allow: ({ component }) => allowed.has(component) })
|
|
8
|
+
Object.defineProperty(window, "docsAgent", { value: agent })
|
|
9
|
+
Object.defineProperty(window, "docsExamples", { value: agent })
|
|
10
|
+
return agent
|
|
11
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Every page loads only this bootstrap. Examples and search load when a page has them or a reader asks.
|
|
2
|
+
// On localhost, ?agent=1 connects the UI SDK Agent Bridge first and mounts search at once, so agents can see it.
|
|
3
|
+
const agentMode = ["localhost", "127.0.0.1"].includes(location.hostname) && new URLSearchParams(location.search).get("agent") === "1"
|
|
4
|
+
const container = document.querySelector<HTMLElement>("[data-docs-search]")
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Search loads when a reader asks for it, so what they type before its input takes focus would be lost. Keep those
|
|
8
|
+
* keys and type them into the input once it is focused. Buffering stops then, after a few seconds, or if loading fails,
|
|
9
|
+
* so keys are never held back for long.
|
|
10
|
+
*/
|
|
11
|
+
function keepEarlyKeys(loading: Promise<void>) {
|
|
12
|
+
let text = ""
|
|
13
|
+
const stop = () => {
|
|
14
|
+
window.removeEventListener("keydown", keep, true)
|
|
15
|
+
document.removeEventListener("focusin", deliver)
|
|
16
|
+
clearTimeout(timer)
|
|
17
|
+
}
|
|
18
|
+
const keep = (event: KeyboardEvent) => {
|
|
19
|
+
if (event.ctrlKey || event.metaKey || event.altKey || event.isComposing) return
|
|
20
|
+
if (event.key.length === 1) text += event.key
|
|
21
|
+
else if (event.key === "Backspace") text = text.slice(0, -1)
|
|
22
|
+
else return
|
|
23
|
+
event.preventDefault()
|
|
24
|
+
}
|
|
25
|
+
const deliver = (event: FocusEvent) => {
|
|
26
|
+
const input = event.target
|
|
27
|
+
if (!(input instanceof HTMLInputElement) || !input.closest("[role=dialog]")) return
|
|
28
|
+
stop()
|
|
29
|
+
if (!text) return
|
|
30
|
+
input.value += text
|
|
31
|
+
input.dispatchEvent(new Event("input", { bubbles: true }))
|
|
32
|
+
}
|
|
33
|
+
const timer = setTimeout(stop, 5000)
|
|
34
|
+
window.addEventListener("keydown", keep, true)
|
|
35
|
+
document.addEventListener("focusin", deliver)
|
|
36
|
+
loading.catch(stop)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function start() {
|
|
40
|
+
if (agentMode) (await import("./agent.ts")).connect()
|
|
41
|
+
if (document.querySelector("[data-docs-example]")) (await import("./examples.tsx")).mount()
|
|
42
|
+
if (document.querySelector(".prose pre")) (await import("./copy.ts")).mount()
|
|
43
|
+
if (!container) return
|
|
44
|
+
container.hidden = false
|
|
45
|
+
let loading: Promise<void> | undefined
|
|
46
|
+
const open = (initiallyOpen: boolean) => loading ??= import("./search.tsx").then(module => module.mountSearch(container, initiallyOpen))
|
|
47
|
+
if (agentMode) {
|
|
48
|
+
await open(false)
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
const request = () => {
|
|
52
|
+
window.removeEventListener("keydown", shortcut)
|
|
53
|
+
keepEarlyKeys(open(true))
|
|
54
|
+
}
|
|
55
|
+
const shortcut = (event: KeyboardEvent) => {
|
|
56
|
+
if (event.key.toLowerCase() !== "k" || !(event.metaKey || event.ctrlKey)) return
|
|
57
|
+
event.preventDefault()
|
|
58
|
+
// Once mounted, the dialog trigger owns the shortcut.
|
|
59
|
+
request()
|
|
60
|
+
}
|
|
61
|
+
window.addEventListener("keydown", shortcut)
|
|
62
|
+
container.querySelector("button")?.addEventListener("click", request, { once: true })
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
void start()
|
package/assets/copy.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { readClientLabels } from "./labels.ts"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A copy button for each code block. Plain DOM: no framework code loads for it. The button keeps its accessible name;
|
|
5
|
+
* the result is announced through a polite live region so screen readers hear "Copied" without the focus moving.
|
|
6
|
+
*/
|
|
7
|
+
export function mount() {
|
|
8
|
+
const labels = readClientLabels()
|
|
9
|
+
const status = document.createElement("span")
|
|
10
|
+
status.className = "visually-hidden"
|
|
11
|
+
status.setAttribute("role", "status")
|
|
12
|
+
document.body.append(status)
|
|
13
|
+
for (const block of document.querySelectorAll<HTMLPreElement>(".prose pre")) {
|
|
14
|
+
const button = document.createElement("button")
|
|
15
|
+
button.type = "button"
|
|
16
|
+
button.className = "copy"
|
|
17
|
+
button.textContent = labels.copyCode
|
|
18
|
+
button.addEventListener("click", async () => {
|
|
19
|
+
try {
|
|
20
|
+
await navigator.clipboard.writeText(block.querySelector("code")?.textContent ?? block.textContent ?? "")
|
|
21
|
+
status.textContent = button.textContent = labels.copied
|
|
22
|
+
} catch {
|
|
23
|
+
status.textContent = button.textContent = labels.copyFailed
|
|
24
|
+
}
|
|
25
|
+
setTimeout(() => { button.textContent = labels.copyCode }, 2000)
|
|
26
|
+
})
|
|
27
|
+
block.classList.add("has-copy")
|
|
28
|
+
block.append(button)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { createSignal, For, untrack } from "solid-js"
|
|
2
|
+
import { render, type JSX } from "@solidjs/web"
|
|
3
|
+
import { Collapsible, CollapsibleTrigger, CollapsiblePanel } from "@ui-sdk/solid/collapsible"
|
|
4
|
+
import examples from "virtual:docs-examples"
|
|
5
|
+
import { Field, FieldLabel } from "@ui-sdk/solid/field"
|
|
6
|
+
import { Input } from "@ui-sdk/solid/input"
|
|
7
|
+
import { Select, SelectContent, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@ui-sdk/solid/select"
|
|
8
|
+
import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"
|
|
9
|
+
import type { ExampleControls } from "@docs-sdk-dev/core"
|
|
10
|
+
import { fill, readClientLabels } from "./labels.ts"
|
|
11
|
+
|
|
12
|
+
type Example = () => JSX.Element
|
|
13
|
+
type Loader = () => Promise<{ default: Example }>
|
|
14
|
+
|
|
15
|
+
type Value = string | number | boolean | undefined
|
|
16
|
+
|
|
17
|
+
/** Controls for the props a reader can change, from the facts the build extracted. */
|
|
18
|
+
function Controls(props: { controls: ExampleControls; values: Record<string, Value>; set: (name: string, value: Value) => void; reset: () => void }) {
|
|
19
|
+
const labels = readClientLabels()
|
|
20
|
+
return <fieldset class="playground-controls">
|
|
21
|
+
<legend>{labels.props}</legend>
|
|
22
|
+
<For each={props.controls.props}>{control => {
|
|
23
|
+
const value = () => props.values[control.name]
|
|
24
|
+
if (control.kind === "boolean") return <label class="control" data-kind="boolean">
|
|
25
|
+
<span>{control.name}</span>
|
|
26
|
+
<Switch checked={value() === true} onCheckedChange={checked => props.set(control.name, checked)}><SwitchThumb /></Switch>
|
|
27
|
+
</label>
|
|
28
|
+
if (control.kind === "select") return <Select value={typeof value() === "string" ? value() as string : null}
|
|
29
|
+
onValueChange={next => props.set(control.name, next ?? undefined)} placeholder="—">
|
|
30
|
+
<SelectLabel>{control.name}</SelectLabel>
|
|
31
|
+
<SelectTrigger><SelectValue /></SelectTrigger>
|
|
32
|
+
<SelectContent><For each={control.options ?? []}>{option => <SelectItem value={option}>{option}</SelectItem>}</For></SelectContent>
|
|
33
|
+
</Select>
|
|
34
|
+
return <Field class="control" data-kind={control.kind}>
|
|
35
|
+
<FieldLabel>{control.name}</FieldLabel>
|
|
36
|
+
<Input type={control.kind === "number" ? "number" : "text"} value={value() === undefined ? "" : String(value())}
|
|
37
|
+
onValueChange={text => props.set(control.name, control.kind === "number" ? (text === "" ? undefined : Number(text)) : text)} />
|
|
38
|
+
</Field>
|
|
39
|
+
}}</For>
|
|
40
|
+
<button type="button" class="playground-reset" onClick={() => props.reset()}>{labels.resetProps}</button>
|
|
41
|
+
</fieldset>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function Playground(props: { name: string; load: Loader; controls?: ExampleControls; component?: () => Promise<Record<string, unknown>> }) {
|
|
45
|
+
const labels = readClientLabels()
|
|
46
|
+
const [example, setExample] = createSignal<Example>()
|
|
47
|
+
const [error, setError] = createSignal(false)
|
|
48
|
+
// With controls, the component itself renders with the reader's props, starting from the example's own.
|
|
49
|
+
const initial = () => Object.fromEntries((props.controls?.props ?? []).map(control => [control.name, control.value]))
|
|
50
|
+
const [values, setValues] = createSignal<Record<string, Value>>(initial())
|
|
51
|
+
let pending: Promise<void> | undefined
|
|
52
|
+
function open(opened: boolean) {
|
|
53
|
+
if (!opened || pending || example()) return
|
|
54
|
+
setError(false)
|
|
55
|
+
const loaded = props.controls && props.component
|
|
56
|
+
? props.component().then(module => {
|
|
57
|
+
const Component = module[props.controls!.export] as ((input: Record<string, unknown>) => JSX.Element) | undefined
|
|
58
|
+
if (!Component) throw new Error("missing export")
|
|
59
|
+
return { default: () => {
|
|
60
|
+
// Reading the values here mounts the component again on each change, so props such as defaultOpen apply.
|
|
61
|
+
const { children, ...rest } = { ...props.controls!.fixed, ...values() }
|
|
62
|
+
return untrack(() => <Component {...rest}>{children as JSX.Element}</Component>)
|
|
63
|
+
} }
|
|
64
|
+
})
|
|
65
|
+
: props.load()
|
|
66
|
+
pending = loaded.then(module => { setExample(() => module.default) }).catch(() => { setError(true) })
|
|
67
|
+
.finally(() => { pending = undefined })
|
|
68
|
+
}
|
|
69
|
+
return <Collapsible onOpenChange={open}>
|
|
70
|
+
<CollapsibleTrigger aria-label={fill(labels.runExampleNamed, { name: props.name })}>{labels.runExample}</CollapsibleTrigger>
|
|
71
|
+
<CollapsiblePanel>
|
|
72
|
+
<div class="example-body" aria-live="polite">
|
|
73
|
+
{(() => {
|
|
74
|
+
const Component = example()
|
|
75
|
+
if (Component) return Component()
|
|
76
|
+
return error() ? labels.exampleFailed : labels.exampleLoading
|
|
77
|
+
})()}
|
|
78
|
+
</div>
|
|
79
|
+
{props.controls && example() && <Controls controls={props.controls} values={values()}
|
|
80
|
+
set={(name, value) => setValues(current => ({ ...current, [name]: value }))} reset={() => setValues(initial())} />}
|
|
81
|
+
</CollapsiblePanel>
|
|
82
|
+
</Collapsible>
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function mount() {
|
|
86
|
+
for (const element of document.querySelectorAll<HTMLElement>("[data-docs-example]")) {
|
|
87
|
+
const file = element.dataset.docsExample
|
|
88
|
+
const name = element.dataset.docsExampleName
|
|
89
|
+
if (!file || !name) continue
|
|
90
|
+
const load = Object.hasOwn(examples, file) ? examples[file] : undefined
|
|
91
|
+
const controls = element.dataset.docsControls ? JSON.parse(element.dataset.docsControls) as ExampleControls : undefined
|
|
92
|
+
const component = controls && Object.hasOwn(examples, controls.source) ? examples[controls.source] as unknown as () => Promise<Record<string, unknown>> : undefined
|
|
93
|
+
if (load) render(() => <Playground name={name} load={load} controls={component ? controls : undefined} component={component} />, element)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { codeToTokens, isSupportedLanguage, type Theme } from "@pierre/highlights"
|
|
2
|
+
import dark from "@pierre/highlights/themes/github-dark"
|
|
3
|
+
import light from "@pierre/highlights/themes/github-light"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Syntax highlighting for the site, as Lenso Docs does it: Pierre Highlights tokenizes each labelled code block at
|
|
7
|
+
* build time, and every token carries its light and dark colors as CSS variables, so one HTML page serves both color
|
|
8
|
+
* schemes with no script. Core's HTML, the published Markdown and agent output stay plain; this runs only when the
|
|
9
|
+
* site renders a page.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
// GitHub's comment colors are too faint on these backgrounds; these keep 4.5:1 contrast, as in Lenso Docs.
|
|
13
|
+
function withCommentColor(theme: Theme, color: string): Theme {
|
|
14
|
+
const syntax = Object.fromEntries(Object.entries(theme.style.syntax ?? {}).map(([scope, style]) => [scope,
|
|
15
|
+
scope === "comment" || scope.startsWith("comment.") ? typeof style === "string" ? color : { ...style, color } : style]))
|
|
16
|
+
return { ...theme, style: { ...theme.style, syntax } }
|
|
17
|
+
}
|
|
18
|
+
const themes = { light: withCommentColor(light, "#616973"), dark: withCommentColor(dark, "#a1aab7") }
|
|
19
|
+
|
|
20
|
+
const hex = /^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i
|
|
21
|
+
const decode = (html: string) => html.replace(/&(?:#x([\da-f]+)|#(\d+)|(amp|lt|gt|quot|apos));/gi, (_, hexCode: string, decimal: string, name: string) =>
|
|
22
|
+
hexCode ? String.fromCodePoint(parseInt(hexCode, 16)) : decimal ? String.fromCodePoint(Number(decimal))
|
|
23
|
+
: ({ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" } as Record<string, string>)[name.toLowerCase()]!)
|
|
24
|
+
const encode = (text: string) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">")
|
|
25
|
+
|
|
26
|
+
const cache = new Map<string, string | null>()
|
|
27
|
+
|
|
28
|
+
/** The highlighted inner HTML of a code block, or null to keep it as it is (unknown language, or tokens that do not
|
|
29
|
+
* reproduce the source exactly). */
|
|
30
|
+
function highlight(code: string, language: string): string | null {
|
|
31
|
+
const key = `${language}\n${code}`
|
|
32
|
+
const cached = cache.get(key)
|
|
33
|
+
if (cached !== undefined) return cached
|
|
34
|
+
let result: string | null = null
|
|
35
|
+
if (language !== "ansi" && isSupportedLanguage(language)) {
|
|
36
|
+
try {
|
|
37
|
+
const lines = codeToTokens(code, { lang: language, themes, defaultColor: false, tokenizeMaxLineLength: 10_000 }).tokens
|
|
38
|
+
const source = code.split("\n")
|
|
39
|
+
if (lines.length === source.length && lines.every((line, index) => line.map(token => token.content).join("") === source[index])) {
|
|
40
|
+
result = lines.map(line => line.map(token => {
|
|
41
|
+
const lightColor = token.htmlStyle?.["--hls-light"]
|
|
42
|
+
const darkColor = token.htmlStyle?.["--hls-dark"]
|
|
43
|
+
if ((lightColor && !hex.test(lightColor)) || (darkColor && !hex.test(darkColor)) || (!lightColor && !darkColor)) return encode(token.content)
|
|
44
|
+
return `<span style="--docs-token-light:${lightColor ?? "currentColor"};--docs-token-dark:${darkColor ?? "currentColor"}">${encode(token.content)}</span>`
|
|
45
|
+
}).join("")).join("\n")
|
|
46
|
+
}
|
|
47
|
+
} catch {
|
|
48
|
+
result = null
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
cache.set(key, result)
|
|
52
|
+
return result
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Highlight the labelled code blocks of a section's sanitized HTML; other blocks and content are left as they are. */
|
|
56
|
+
export function highlightHtml(html: string) {
|
|
57
|
+
if (!html.includes('<pre><code class="language-')) return html
|
|
58
|
+
return html.replace(/<pre><code class="language-([\w#+.-]+)">([^]*?)<\/code><\/pre>/g, (block, language: string, body: string) => {
|
|
59
|
+
const code = decode(body)
|
|
60
|
+
const trailing = code.endsWith("\n") ? "\n" : ""
|
|
61
|
+
const inner = highlight(trailing ? code.slice(0, -1) : code, language)
|
|
62
|
+
return inner === null ? block : `<pre data-highlighted><code class="language-${language}">${inner}${trailing}</code></pre>`
|
|
63
|
+
})
|
|
64
|
+
}
|
package/assets/labels.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/** Interface text of the default site, per locale. `{query}` and `{name}` are filled in where they appear. */
|
|
2
|
+
export const englishLabels = {
|
|
3
|
+
skipToContent: "Skip to content",
|
|
4
|
+
primaryNavigation: "Primary",
|
|
5
|
+
documentationNavigation: "Documentation",
|
|
6
|
+
editions: "Editions",
|
|
7
|
+
editionVersion: "Version",
|
|
8
|
+
editionLocale: "Language",
|
|
9
|
+
editionUnavailable: "{value} (unavailable)",
|
|
10
|
+
editionFallback: "{value} (in {target})",
|
|
11
|
+
allEditions: "All editions",
|
|
12
|
+
onThisPage: "On this page",
|
|
13
|
+
readAsMarkdown: "Read as Markdown ↗",
|
|
14
|
+
manifest: "Manifest ↗",
|
|
15
|
+
forAgents: "For agents",
|
|
16
|
+
pageAsMarkdown: "This page in Markdown",
|
|
17
|
+
editPage: "Edit this page ↗",
|
|
18
|
+
pagination: "Pages",
|
|
19
|
+
previousPage: "Previous",
|
|
20
|
+
nextPage: "Next",
|
|
21
|
+
search: "Search",
|
|
22
|
+
searchTitle: "Documentation search",
|
|
23
|
+
searchQuery: "Search query",
|
|
24
|
+
searchPlaceholder: "Search this edition…",
|
|
25
|
+
searchHint: "Type a question or a name.",
|
|
26
|
+
searchNoResults: "No sections match “{query}”.",
|
|
27
|
+
searchFailed: "Search is unavailable. Close and try again.",
|
|
28
|
+
runExample: "Run example",
|
|
29
|
+
runExampleNamed: "Run {name} example",
|
|
30
|
+
exampleLoading: "Loading example…",
|
|
31
|
+
exampleFailed: "Example could not load. Close and reopen to retry.",
|
|
32
|
+
copyCode: "Copy",
|
|
33
|
+
copied: "Copied",
|
|
34
|
+
copyFailed: "Copy failed",
|
|
35
|
+
props: "Props",
|
|
36
|
+
resetProps: "Reset props",
|
|
37
|
+
table: "Table",
|
|
38
|
+
menu: "Menu",
|
|
39
|
+
}
|
|
40
|
+
export type Labels = typeof englishLabels
|
|
41
|
+
|
|
42
|
+
const builtIn: Record<string, Labels> = {
|
|
43
|
+
en: englishLabels,
|
|
44
|
+
fr: {
|
|
45
|
+
skipToContent: "Aller au contenu",
|
|
46
|
+
primaryNavigation: "Principale",
|
|
47
|
+
documentationNavigation: "Documentation",
|
|
48
|
+
editions: "Éditions",
|
|
49
|
+
editionVersion: "Version",
|
|
50
|
+
editionLocale: "Langue",
|
|
51
|
+
editionUnavailable: "{value} (indisponible)",
|
|
52
|
+
editionFallback: "{value} (en {target})",
|
|
53
|
+
allEditions: "Toutes les éditions",
|
|
54
|
+
onThisPage: "Sur cette page",
|
|
55
|
+
readAsMarkdown: "Lire en Markdown ↗",
|
|
56
|
+
manifest: "Manifeste ↗",
|
|
57
|
+
forAgents: "Pour les agents",
|
|
58
|
+
pageAsMarkdown: "Cette page en Markdown",
|
|
59
|
+
editPage: "Modifier cette page ↗",
|
|
60
|
+
pagination: "Pages",
|
|
61
|
+
previousPage: "Précédent",
|
|
62
|
+
nextPage: "Suivant",
|
|
63
|
+
search: "Rechercher",
|
|
64
|
+
searchTitle: "Recherche dans la documentation",
|
|
65
|
+
searchQuery: "Requête de recherche",
|
|
66
|
+
searchPlaceholder: "Rechercher dans cette édition…",
|
|
67
|
+
searchHint: "Saisissez une question ou un nom.",
|
|
68
|
+
searchNoResults: "Aucune section ne correspond à « {query} ».",
|
|
69
|
+
searchFailed: "La recherche est indisponible. Fermez puis réessayez.",
|
|
70
|
+
runExample: "Lancer l’exemple",
|
|
71
|
+
runExampleNamed: "Lancer l’exemple {name}",
|
|
72
|
+
exampleLoading: "Chargement de l’exemple…",
|
|
73
|
+
exampleFailed: "L’exemple n’a pas pu être chargé. Fermez puis rouvrez pour réessayer.",
|
|
74
|
+
copyCode: "Copier",
|
|
75
|
+
copied: "Copié",
|
|
76
|
+
copyFailed: "Échec de la copie",
|
|
77
|
+
props: "Propriétés",
|
|
78
|
+
resetProps: "Rétablir les propriétés",
|
|
79
|
+
table: "Tableau",
|
|
80
|
+
menu: "Menu",
|
|
81
|
+
},
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Labels for a locale: the project's overrides for it, then the built-in labels for its language (English and French
|
|
86
|
+
* ship), then English. Unknown keys and non-text values are configuration errors.
|
|
87
|
+
*/
|
|
88
|
+
export function labelsFor(locale: string, overrides: Record<string, Partial<Record<string, unknown>>> = {}): Labels {
|
|
89
|
+
for (const [key, values] of Object.entries(overrides)) for (const [name, value] of Object.entries(values ?? {})) {
|
|
90
|
+
if (!(name in englishLabels)) throw new Error(`site.labels.${key}.${name} is not a label. Labels: ${Object.keys(englishLabels).join(", ")}.`)
|
|
91
|
+
if (typeof value !== "string" || !value.trim()) throw new Error(`site.labels.${key}.${name} must be non-empty text.`)
|
|
92
|
+
}
|
|
93
|
+
const language = locale.split("-")[0]!
|
|
94
|
+
return { ...englishLabels, ...builtIn[language], ...builtIn[locale], ...overrides[language], ...overrides[locale] } as Labels
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export const fill = (text: string, values: Record<string, string>) => text.replace(/\{(\w+)\}/g, (match, key: string) => values[key] ?? match)
|
|
98
|
+
|
|
99
|
+
/** The labels the browser needs, embedded on each page so search and examples speak the page's language. */
|
|
100
|
+
export const clientLabelKeys = ["search", "searchTitle", "searchQuery", "searchPlaceholder", "searchHint", "searchNoResults",
|
|
101
|
+
"searchFailed", "runExample", "runExampleNamed", "exampleLoading", "exampleFailed", "copyCode", "copied", "copyFailed", "props", "resetProps"] as const
|
|
102
|
+
export type ClientLabels = Pick<Labels, typeof clientLabelKeys[number]>
|
|
103
|
+
export function readClientLabels(): ClientLabels {
|
|
104
|
+
try {
|
|
105
|
+
return { ...englishLabels, ...JSON.parse(document.body.dataset.docsLabels ?? "{}") }
|
|
106
|
+
} catch {
|
|
107
|
+
return englishLabels
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { renderToString, type JSX } from "@solidjs/web"
|
|
2
|
+
import type { Document, EditionPolicy } from "@docs-sdk-dev/core"
|
|
3
|
+
import { createEditions, createNavigation, editionParts, editSource, englishEditionText, localeAlternates, localizedTitles, pageOutline, type EditionPart, type Editions, type EditionText, type LocalizedText, type NavigationItem, type NavigationNode } from "@docs-sdk-dev/core/reader"
|
|
4
|
+
import { highlightHtml } from "./highlight.ts"
|
|
5
|
+
import { clientLabelKeys, fill, labelsFor, type Labels } from "./labels.ts"
|
|
6
|
+
|
|
7
|
+
// One grouping per document list, reused for every page of the build.
|
|
8
|
+
// One navigation per page locale, since section titles may differ by language.
|
|
9
|
+
const navigations = new WeakMap<readonly Document[], Map<string, ReturnType<typeof createNavigation>>>()
|
|
10
|
+
|
|
11
|
+
const alternatesOf = new WeakMap<readonly Document[], ReturnType<typeof localeAlternates>>()
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Render one page under the site's title. With `site.root` (the validated site URL without a trailing slash), the head
|
|
15
|
+
* names the page's canonical URL and its locale editions as hreflang alternates; both must be absolute, so they are
|
|
16
|
+
* omitted without it.
|
|
17
|
+
*/
|
|
18
|
+
/**
|
|
19
|
+
* Wrap each table so a wide one scrolls inside its own box instead of widening the page on narrow screens. The box is
|
|
20
|
+
* focusable, so keyboard users can scroll it, and named, as focusable regions must be. Sanitized HTML writes tables
|
|
21
|
+
* as a bare `<table>` tag.
|
|
22
|
+
*/
|
|
23
|
+
const escapeAttribute = (text: string) => text.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<")
|
|
24
|
+
export const scrollableTables = (html: string, label: string) => html.includes("<table>")
|
|
25
|
+
? html.replaceAll("<table>", `<div class="table-scroll" role="region" tabindex="0" aria-label="${escapeAttribute(label)}"><table>`).replaceAll("</table>", "</table></div>")
|
|
26
|
+
: html
|
|
27
|
+
|
|
28
|
+
/** A scope's first page: its own, or the first one nested in it. */
|
|
29
|
+
/** The words of edition parts in the page's language: the site's labels, with languages named in their own language. */
|
|
30
|
+
const editionText = (labels: Labels): EditionText => ({
|
|
31
|
+
...englishEditionText,
|
|
32
|
+
dimension: name => name === "version" ? labels.editionVersion : name === "locale" ? labels.editionLocale : englishEditionText.dimension(name),
|
|
33
|
+
unavailable: value => fill(labels.editionUnavailable, { value }),
|
|
34
|
+
fallback: (value, original) => fill(labels.editionFallback, { value, target: original }),
|
|
35
|
+
allEditions: labels.allEditions,
|
|
36
|
+
})
|
|
37
|
+
/** Render one edition part from Core as it is: its element, its attributes, its text. */
|
|
38
|
+
const EditionPart = (props: { part: EditionPart }) => props.part.element === "a"
|
|
39
|
+
? <a {...props.part.attrs}>{props.part.text}</a> : <span {...props.part.attrs}>{props.part.text}</span>
|
|
40
|
+
const editionModels = new WeakMap<readonly Document[], Editions<Document>>()
|
|
41
|
+
|
|
42
|
+
const firstRoute = (node: NavigationNode): string | undefined => node.items[0]?.route ?? node.children.map(firstRoute).find(Boolean)
|
|
43
|
+
|
|
44
|
+
export function htmlPage(document: Document, documents: Document[], revision: string, assets: { script?: string; styles: string[] },
|
|
45
|
+
site: { root?: string; title: string; labels?: Record<string, Record<string, unknown>>; search?: Record<string, string>; editUrl?: string; image?: string; sidebar?: "all" | "section"; titles?: Record<string, LocalizedText>; dimensions?: readonly string[]; editions?: EditionPolicy }) {
|
|
46
|
+
const siteRoot = site.root
|
|
47
|
+
const lang = document.identity.dimensions.locale ?? "en"
|
|
48
|
+
const labels = labelsFor(lang, site.labels)
|
|
49
|
+
const clientLabels = JSON.stringify(Object.fromEntries(clientLabelKeys.map(key => [key, labels[key]])))
|
|
50
|
+
let byLocale = navigations.get(documents)
|
|
51
|
+
if (!byLocale) navigations.set(documents, byLocale = new Map())
|
|
52
|
+
const locale = document.identity.dimensions.locale ?? ""
|
|
53
|
+
let navigator = byLocale.get(locale)
|
|
54
|
+
if (!navigator) byLocale.set(locale, navigator = createNavigation(documents, {
|
|
55
|
+
labels: localizedTitles(site.titles, document.identity.dimensions.locale, site.editions?.defaultLocale),
|
|
56
|
+
dimensions: site.dimensions, editions: site.editions }))
|
|
57
|
+
let alternates = alternatesOf.get(documents)
|
|
58
|
+
if (!alternates && siteRoot) alternatesOf.set(documents, alternates = localeAlternates(documents))
|
|
59
|
+
const navigation = navigator.for(document)
|
|
60
|
+
// Edition switching is Core's Editions primitive; this adapter only renders its parts.
|
|
61
|
+
let editionModel = editionModels.get(documents)
|
|
62
|
+
if (!editionModel) {
|
|
63
|
+
editionModel = createEditions(documents, { dimensions: site.dimensions, editions: site.editions })
|
|
64
|
+
editionModels.set(documents, editionModel)
|
|
65
|
+
}
|
|
66
|
+
const editions = editionParts(editionModel.state(document), editionText(labels), site.dimensions)
|
|
67
|
+
// Every page carries its navigation, so listing every page on every page makes a site grow with its page count
|
|
68
|
+
// squared. With sidebar "section", as in Lenso Docs, a page lists only its own section and path in full.
|
|
69
|
+
const compact = site.sidebar === "section"
|
|
70
|
+
const outline = pageOutline(document)
|
|
71
|
+
// A page with layout: home in its frontmatter opens the site: the site's name, the page's description as the lead,
|
|
72
|
+
// its actions, then its content. Everything it shows is also in the page's Markdown, except the actions' links.
|
|
73
|
+
const home = document.meta?.layout === "home"
|
|
74
|
+
const actions = home && Array.isArray(document.meta?.actions) ? (document.meta.actions as unknown[]).flatMap(item =>
|
|
75
|
+
typeof item === "object" && item !== null && typeof (item as { text?: unknown }).text === "string" && typeof (item as { href?: unknown }).href === "string"
|
|
76
|
+
? [item as { text: string; href: string }] : []) : []
|
|
77
|
+
const source = site.editUrl && editSource(document)
|
|
78
|
+
const edit = source ? site.editUrl!.replaceAll("{path}", source.split("/").map(encodeURIComponent).join("/")) : undefined
|
|
79
|
+
// The navigation label of the page's scope; pages outside the navigation, such as the 404 page, show none.
|
|
80
|
+
const scope = navigation.groups.find(group => group.scope === document.identity.scope)?.label
|
|
81
|
+
const links = (items: readonly NavigationItem[]) =>
|
|
82
|
+
items.map(item => <a aria-current={item.current ? "page" : undefined} href={item.route}>{item.title}</a>)
|
|
83
|
+
// As in Lenso Docs, a nested scope is a folder, open only on the current page's path, so deep trees stay short and
|
|
84
|
+
// still open without JavaScript.
|
|
85
|
+
const folder = (node: NavigationNode): JSX.Element => compact && !node.active
|
|
86
|
+
// On a large site a folder off the current path is one link, like another section, rather than all its pages.
|
|
87
|
+
? <div class="nav-folder" data-collapsed><a href={firstRoute(node)}>{node.label}</a></div>
|
|
88
|
+
: <details class="nav-folder" open={node.active || undefined}>
|
|
89
|
+
<summary>{node.label}</summary>{links(node.items)}{node.children.map(folder)}
|
|
90
|
+
</details>
|
|
91
|
+
const groups = () => <div class="nav-groups">
|
|
92
|
+
{navigation.sections.map(section => compact && !section.active
|
|
93
|
+
// A large site lists only the current section's pages; another section is one link to its first page.
|
|
94
|
+
? <div class="nav-group" data-collapsed><p><a href={firstRoute(section)}>{section.label}</a></p></div>
|
|
95
|
+
: <div class="nav-group">
|
|
96
|
+
<p>{section.label}</p>
|
|
97
|
+
{links(section.items)}{section.children.map(folder)}
|
|
98
|
+
</div>)}
|
|
99
|
+
</div>
|
|
100
|
+
const page = renderToString(() => <html lang={lang}>
|
|
101
|
+
<head>
|
|
102
|
+
<meta charset="utf-8" />
|
|
103
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
104
|
+
<meta name="docs-build" content={revision} />
|
|
105
|
+
<title>{document.title} · {site.title}</title>
|
|
106
|
+
{document.description && <meta name="description" content={document.description} />}
|
|
107
|
+
{siteRoot && <link rel="canonical" href={siteRoot + document.route} />}
|
|
108
|
+
{/* Link previews in chat apps and social networks read Open Graph; the URL needs site.url, as canonical does. */}
|
|
109
|
+
<meta property="og:type" content="article" />
|
|
110
|
+
<meta property="og:site_name" content={site.title} />
|
|
111
|
+
<meta property="og:title" content={document.title} />
|
|
112
|
+
{document.description && <meta property="og:description" content={document.description} />}
|
|
113
|
+
{siteRoot && <meta property="og:url" content={siteRoot + document.route} />}
|
|
114
|
+
{site.image && <meta property="og:image" content={site.image} />}
|
|
115
|
+
<meta name="twitter:card" content={site.image ? "summary_large_image" : "summary"} />
|
|
116
|
+
{siteRoot && (alternates?.get(document.key) ?? []).map(link =>
|
|
117
|
+
<link rel="alternate" hreflang={link.locale} href={siteRoot + link.route} />)}
|
|
118
|
+
{assets.styles.map(style => <link rel="stylesheet" href={style} />)}
|
|
119
|
+
{assets.script && <script type="module" src={assets.script}></script>}
|
|
120
|
+
</head>
|
|
121
|
+
<body data-docs-labels={clientLabels}>
|
|
122
|
+
<a class="skip" href="#main">{labels.skipToContent}</a>
|
|
123
|
+
<header class="bar">
|
|
124
|
+
<a class="brand" href="/">{site.title}</a>
|
|
125
|
+
<nav aria-label={labels.primaryNavigation}>
|
|
126
|
+
{navigation.sections.map(section => <a aria-current={section.active ? "true" : undefined}
|
|
127
|
+
href={firstRoute(section)}>{section.label}</a>)}
|
|
128
|
+
</nav>
|
|
129
|
+
<div class="search" data-docs-search data-docs-context={JSON.stringify(document.identity.dimensions)}
|
|
130
|
+
data-docs-search-index={site.search?.[lang] ?? site.search?.all ?? "/search/all/"} hidden>
|
|
131
|
+
<button type="button">{labels.search}</button>
|
|
132
|
+
</div>
|
|
133
|
+
</header>
|
|
134
|
+
<div class="layout" data-layout={home ? "home" : undefined}>
|
|
135
|
+
<nav class="sidebar" aria-label={labels.documentationNavigation}>
|
|
136
|
+
{/* As in Lenso Docs, the groups are written twice: open for wider screens, and inside a closed Menu for
|
|
137
|
+
phones. CSS shows one of them, so phones start at the content with or without JavaScript. */}
|
|
138
|
+
<div class="nav-desktop">{groups()}</div>
|
|
139
|
+
<details class="nav-mobile">
|
|
140
|
+
<summary>{labels.menu}</summary>
|
|
141
|
+
{groups()}
|
|
142
|
+
</details>
|
|
143
|
+
</nav>
|
|
144
|
+
<main id="main">
|
|
145
|
+
{home ? <header class="hero">
|
|
146
|
+
<h1>{site.title}</h1>
|
|
147
|
+
{document.description && <p class="lead">{document.description}</p>}
|
|
148
|
+
{actions.length > 0 && <div class="actions">
|
|
149
|
+
{actions.map((action, index) => <a class="action" data-primary={index === 0 ? "" : undefined} href={action.href}>{action.text}</a>)}
|
|
150
|
+
</div>}
|
|
151
|
+
</header> : <>
|
|
152
|
+
{scope && <p class="scope">{scope}</p>}
|
|
153
|
+
<h1>{document.title}</h1>
|
|
154
|
+
</>}
|
|
155
|
+
{editions.dimensions.length > 0 || editions.list ? <div {...editions.root}>
|
|
156
|
+
{editions.dimensions.map(dimension => <nav {...dimension.attrs}>
|
|
157
|
+
<span>{dimension.label}</span>
|
|
158
|
+
<ul>{dimension.choices.map(choice => <li><EditionPart part={choice} /></li>)}</ul>
|
|
159
|
+
</nav>)}
|
|
160
|
+
{editions.list && <details {...editions.list.attrs}>
|
|
161
|
+
<summary>{editions.list.summary}</summary>
|
|
162
|
+
<nav aria-label={editions.list.summary}><ul>{editions.list.items.map(item => <li><EditionPart part={item} /></li>)}</ul></nav>
|
|
163
|
+
</details>}
|
|
164
|
+
</div> : null}
|
|
165
|
+
{document.sections.map(section =>
|
|
166
|
+
<section id={section.id} aria-labelledby={section.title ? `${section.id}-heading` : undefined}>
|
|
167
|
+
{section.title && <h2 id={`${section.id}-heading`}>{section.title}</h2>}
|
|
168
|
+
{section.artifacts.map(artifact => <>
|
|
169
|
+
<div class="prose" innerHTML={scrollableTables(highlightHtml(artifact.html), labels.table)}></div>
|
|
170
|
+
{artifact.example && <div class="example" data-docs-example={artifact.example.source} data-docs-example-name={artifact.example.id}
|
|
171
|
+
data-docs-controls={artifact.example.controls ? JSON.stringify(artifact.example.controls) : undefined}></div>}
|
|
172
|
+
</>)}
|
|
173
|
+
</section>)}
|
|
174
|
+
{(navigation.previous || navigation.next) && <nav class="pager" aria-label={labels.pagination}>
|
|
175
|
+
{navigation.previous && <a rel="prev" href={navigation.previous.route}><span>{labels.previousPage}</span>{navigation.previous.title}</a>}
|
|
176
|
+
{navigation.next && <a rel="next" href={navigation.next.route}><span>{labels.nextPage}</span>{navigation.next.title}</a>}
|
|
177
|
+
</nav>}
|
|
178
|
+
</main>
|
|
179
|
+
{!home && <aside class="outline">
|
|
180
|
+
<nav aria-label={labels.onThisPage}>
|
|
181
|
+
{outline.length > 0 && <p>{labels.onThisPage}</p>}
|
|
182
|
+
{outline.map(item => <a href={`#${item.anchor}`} data-level={item.level}>{item.text}</a>)}
|
|
183
|
+
</nav>
|
|
184
|
+
<a class="download" href={`/content${document.route}index.md`}>{labels.readAsMarkdown}</a>
|
|
185
|
+
{edit && <a class="edit" href={edit}>{labels.editPage}</a>}
|
|
186
|
+
</aside>}
|
|
187
|
+
</div>
|
|
188
|
+
{/* What agents read: the site's guide, its manifest, and this page as Markdown. */}
|
|
189
|
+
<footer class="site-footer">
|
|
190
|
+
<span>{labels.forAgents}</span>
|
|
191
|
+
<a href="/llms.txt">llms.txt</a>
|
|
192
|
+
<a href="/manifest.json">manifest.json</a>
|
|
193
|
+
<a href={`/content${document.route}index.md`}>{labels.pageAsMarkdown}</a>
|
|
194
|
+
</footer>
|
|
195
|
+
</body>
|
|
196
|
+
</html>)
|
|
197
|
+
return "<!doctype html>\n" + page
|
|
198
|
+
}
|