@docs-sdk-dev/solid 0.0.1 → 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/assets/render.tsx CHANGED
@@ -1,59 +1,197 @@
1
- import { renderToString } from "@solidjs/web"
2
- import type { Document } from "@docs-sdk-dev/core"
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"
3
6
 
4
- export function htmlPage(document: Document, documents: Document[], revision: string, assets: { script?: string; styles: string[] }) {
5
- const examples = document.sections.some(section => section.artifacts.some(artifact => artifact.example))
6
- const groups = [...new Set(documents.map(page => page.identity.scope))]
7
- const guides = documents.find(page => page.identity.scope === "guide")
8
- const releases = documents.find(page => page.identity.scope === "releases")
9
- const page = renderToString(() => <html lang={document.identity.dimensions.locale ?? "en"}>
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("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;")
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}>
10
101
  <head>
11
102
  <meta charset="utf-8" />
12
103
  <meta name="viewport" content="width=device-width, initial-scale=1" />
13
104
  <meta name="docs-build" content={revision} />
14
- <title>{document.title} · Docs SDK</title>
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} />)}
15
118
  {assets.styles.map(style => <link rel="stylesheet" href={style} />)}
16
- {examples && assets.script && <script type="module" src={assets.script}></script>}
119
+ {assets.script && <script type="module" src={assets.script}></script>}
17
120
  </head>
18
- <body>
19
- <a class="skip" href="#main">Skip to content</a>
121
+ <body data-docs-labels={clientLabels}>
122
+ <a class="skip" href="#main">{labels.skipToContent}</a>
20
123
  <header class="bar">
21
- <a class="brand" href="/">Docs SDK</a>
22
- <nav aria-label="Primary">
23
- <a href={guides?.route ?? "/"}>Docs</a>
24
- {releases && <a href={releases.route}>Releases</a>}
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>)}
25
128
  </nav>
26
- <a class="manifest" href="/manifest.json">Manifest ↗</a>
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>
27
133
  </header>
28
- <div class="layout">
29
- <nav class="sidebar" aria-label="Documentation">
30
- {groups.map(group => <div class="nav-group">
31
- <p>{group === "guide" ? "Guide" : group === "components" ? "Components" : group === "releases" ? "Releases" : group}</p>
32
- {documents.filter(page => page.identity.scope === group).map(page =>
33
- <a aria-current={page.key === document.key ? "page" : undefined} href={page.route}>{page.title}</a>)}
34
- </div>)}
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>
35
143
  </nav>
36
144
  <main id="main">
37
- <p class="scope">{document.identity.scope}</p>
38
- <h1>{document.title}</h1>
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}
39
165
  {document.sections.map(section =>
40
166
  <section id={section.id} aria-labelledby={section.title ? `${section.id}-heading` : undefined}>
41
167
  {section.title && <h2 id={`${section.id}-heading`}>{section.title}</h2>}
42
168
  {section.artifacts.map(artifact => <>
43
- <div class="prose" innerHTML={artifact.html}></div>
44
- {artifact.example && <div class="example" data-docs-example={artifact.example.source} data-docs-example-name={artifact.example.id}></div>}
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>}
45
172
  </>)}
46
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>}
47
178
  </main>
48
- <aside class="outline">
49
- <nav aria-label="On this page">
50
- {document.sections.some(section => section.title) && <p>On this page</p>}
51
- {document.sections.filter(section => section.title).map(section =>
52
- <a href={`#${section.id}`}>{section.title}</a>)}
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>)}
53
183
  </nav>
54
- <a class="download" href={`/content${document.route}index.md`}>Read as Markdown ↗</a>
55
- </aside>
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>}
56
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>
57
195
  </body>
58
196
  </html>)
59
197
  return "<!doctype html>\n" + page
@@ -0,0 +1,99 @@
1
+ import { closestSubheading, queryTerms } from "@docs-sdk-dev/core/reader"
2
+ import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from "@ui-sdk/solid/command"
3
+ import { Dialog, DialogBackdrop, DialogContent, DialogShortcut, DialogTitle, DialogTrigger } from "@ui-sdk/solid/dialog"
4
+ import { render } from "@solidjs/web"
5
+ import { createStaticSearchClient, type StaticSearchClient } from "@zbsearch/static"
6
+ import { createSignal, For } from "solid-js"
7
+ import { fill, readClientLabels } from "./labels.ts"
8
+
9
+ /** What a search record stores for a result; the index is built from these (see searchFiles). */
10
+ type Hit = { title: string; heading?: string; route: string; snippet: string; context: Partial<{ [key: string]: string }>;
11
+ subheadings?: { anchor: string; text: string }[] }
12
+ type SearchResult = { title: string; heading?: string; subheading?: string; route: string; snippet: string }
13
+
14
+ // As in Lenso Docs, the search box reads a static, sharded index: the dictionary first, then only the shards a query
15
+ // needs. Titles count most, then headings; body text least.
16
+ const fields = ["title", "heading", "subheadingText", "description", "text"]
17
+ const boost = { title: 4, heading: 3, subheadingText: 2, description: 2 }
18
+ let baseUrl = "/search/all/"
19
+ let client: Promise<StaticSearchClient> | undefined
20
+ const load = () => client ??= (async () => {
21
+ const searcher = createStaticSearchClient({ baseUrl })
22
+ await searcher.preload()
23
+ return searcher
24
+ })()
25
+ /** Editions agree when every dimension the record has matches the page's; a page without editions matches any. */
26
+ const compatible = (record: Hit["context"], context: { [key: string]: string }) =>
27
+ Object.entries(context).every(([key, value]) => !(key in record) || record[key] === value)
28
+
29
+ function Search(props: { context: Record<string, string>; initiallyOpen: boolean }) {
30
+ const labels = readClientLabels()
31
+ const [open, setOpen] = createSignal(props.initiallyOpen)
32
+ const [results, setResults] = createSignal<SearchResult[]>([])
33
+ const [failed, setFailed] = createSignal(false)
34
+ let latest = ""
35
+ async function query(text: string) {
36
+ latest = text
37
+ if (!text.trim()) {
38
+ setResults([])
39
+ return
40
+ }
41
+ try {
42
+ // The words that carry the question, as agent search ranks them: "how do I" and "the" do not count.
43
+ const term = queryTerms(text, props.context.locale).join(" ")
44
+ const hits = (await (await load()).search<Hit>({ term, properties: fields, boost, limit: 40 })).hits
45
+ const found = hits.map(hit => hit.document).filter(record => compatible(record.context, props.context)).slice(0, 8)
46
+ .map((record): SearchResult => {
47
+ const subheading = closestSubheading(record.subheadings, text, props.context.locale)
48
+ return { title: record.title, ...(record.heading ? { heading: record.heading } : {}), snippet: record.snippet,
49
+ ...(subheading ? { route: `${record.route.split("#")[0]}#${subheading.anchor}`, subheading: subheading.text } : { route: record.route }) }
50
+ })
51
+ if (latest === text) setResults(found)
52
+ } catch {
53
+ client = undefined
54
+ setFailed(true)
55
+ }
56
+ }
57
+ return (
58
+ <Dialog open={open()} onOpenChange={next => setOpen(next)}>
59
+ <DialogTrigger shortcut="mod+k">
60
+ {labels.search}
61
+ <DialogShortcut />
62
+ </DialogTrigger>
63
+ <DialogBackdrop />
64
+ <DialogContent>
65
+ <DialogTitle>{labels.searchTitle}</DialogTitle>
66
+ <Command filter={false} onQueryChange={query} onAction={route => {
67
+ setOpen(false)
68
+ location.assign(route)
69
+ }}>
70
+ <CommandInput aria-label={labels.searchQuery} placeholder={labels.searchPlaceholder} />
71
+ <CommandEmpty>
72
+ {state => failed() ? labels.searchFailed
73
+ : state.query.trim() ? fill(labels.searchNoResults, { query: state.query }) : labels.searchHint}
74
+ </CommandEmpty>
75
+ <CommandList>
76
+ <For each={results()}>
77
+ {result => (
78
+ <CommandItem value={result.route} label={[result.title, result.heading, result.subheading].filter(Boolean).join(" ")}>
79
+ <span data-search="title">{[result.title, result.heading, result.subheading].filter(Boolean).join(" › ")}</span>
80
+ <span data-search="snippet">{result.snippet}</span>
81
+ </CommandItem>
82
+ )}
83
+ </For>
84
+ </CommandList>
85
+ </Command>
86
+ </DialogContent>
87
+ </Dialog>
88
+ )
89
+ }
90
+
91
+ export function mountSearch(container: HTMLElement, initiallyOpen = true) {
92
+ const context = JSON.parse(container.dataset.docsContext ?? "{}") as Record<string, string>
93
+ baseUrl = container.dataset.docsSearchIndex ?? "/search/all/"
94
+ // Pages without a locale edition, such as guides, still have a language; search in it.
95
+ if (!context.locale && document.documentElement.lang) context.locale = document.documentElement.lang
96
+ container.replaceChildren()
97
+ render(() => <Search context={context} initiallyOpen={initiallyOpen} />, container)
98
+ void load().catch(() => undefined)
99
+ }