@docs-sdk-dev/solid 0.0.1 → 0.0.3

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/README.md CHANGED
@@ -2,4 +2,4 @@
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
4
 
5
- Import `componentReference` from `@docs-sdk-dev/solid/component-reference` to build pages from exported Solid component functions with local props interfaces. Register each runnable `site/*-example.tsx` as an entry's example source. The module should export a default component. Interactive previews load only when opened. Supply `site/style.css` to override the default stylesheet.
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.
@@ -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
+ }
package/assets/client.tsx CHANGED
@@ -1,49 +1,65 @@
1
- import { createSignal } from "solid-js"
2
- import { render, type JSX } from "@solidjs/web"
3
- import { Collapsible, CollapsibleTrigger, CollapsiblePanel } from "@ui-sdk/solid/collapsible"
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]")
4
5
 
5
- type Example = () => JSX.Element
6
- type Loader = () => Promise<{ default: Example }>
7
- const examples = import.meta.glob<{ default: Example }>("/site/*-example.tsx")
8
-
9
- function Playground(props: { name: string; load: Loader }) {
10
- const [example, setExample] = createSignal<Example>()
11
- const [error, setError] = createSignal(false)
12
- let pending: Promise<void> | undefined
13
- function open(opened: boolean) {
14
- if (!opened || pending || example()) return
15
- setError(false)
16
- pending = props.load().then(module => { setExample(() => module.default) }).catch(() => { setError(true) })
17
- .finally(() => { pending = undefined })
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()
18
24
  }
19
- return <Collapsible onOpenChange={open}>
20
- <CollapsibleTrigger aria-label={`Run ${props.name} example`}>Run example</CollapsibleTrigger>
21
- <CollapsiblePanel>
22
- <div class="example-body" aria-live="polite">
23
- {(() => {
24
- const Component = example()
25
- if (Component) return <Component />
26
- return error() ? "Example could not load. Close and reopen to retry." : "Loading example…"
27
- })()}
28
- </div>
29
- </CollapsiblePanel>
30
- </Collapsible>
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)
31
37
  }
32
38
 
33
- async function mount() {
34
- if (["localhost", "127.0.0.1"].includes(location.hostname)
35
- && new URLSearchParams(location.search).get("agent") === "1") {
36
- const { createAgent } = await import("@ui-sdk/solid/agent")
37
- const agent = createAgent({ allow: ({ component }) => component === "collapsible" })
38
- Object.defineProperty(window, "docsExamples", { value: agent })
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))
39
54
  }
40
- for (const element of document.querySelectorAll<HTMLElement>("[data-docs-example]")) {
41
- const file = element.dataset.docsExample
42
- const name = element.dataset.docsExampleName
43
- if (!file || !name) continue
44
- const load = examples["/" + file]
45
- if (load) render(() => <Playground name={name} load={load} />, element)
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()
46
60
  }
61
+ window.addEventListener("keydown", shortcut)
62
+ container.querySelector("button")?.addEventListener("click", request, { once: true })
47
63
  }
48
64
 
49
- void mount()
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("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
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
+ }
@@ -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
+ }