@vite-hub/docs 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +179 -19
  2. package/dist/{agent-copy-BJp_Yf5d.js → agent-copy-xPaWye_g.js} +1 -1
  3. package/dist/assistant-pages-CqNlHsx-.js +37 -0
  4. package/dist/{assistant-shared-Dll_F_yy.d.ts → assistant-shared-CWIKRtBv.d.ts} +3 -2
  5. package/dist/{assistant-shared-CdtXowot.js → assistant-shared-DhiLHKSl.js} +23 -7
  6. package/dist/assistant-worker.d.ts +1 -1
  7. package/dist/assistant-worker.js +1 -1
  8. package/dist/assistant.d.ts +1 -1
  9. package/dist/assistant.js +1 -1
  10. package/dist/{content-9CINWiRf.js → content-BQVlMshL.js} +57 -47
  11. package/dist/{draft-DUBx--r9.js → draft-CSsTYSeb.js} +2 -2
  12. package/dist/error-diagnostics-CmgtG9xa.js +157 -0
  13. package/dist/files-UY4h1_36.js +38 -0
  14. package/dist/index.d.ts +7 -6
  15. package/dist/index.js +4 -4
  16. package/dist/link-checker-redirects.js +1 -1
  17. package/dist/{manifest-Dzp5-_AJ.d.ts → manifest-Drbdw1us.d.ts} +9 -3
  18. package/dist/{manifest-D66AEF8F.js → manifest-DvECmwX-.js} +101 -51
  19. package/dist/{markdown-Cn9-4oVG.js → markdown-1M1FbjCw.js} +1 -1
  20. package/dist/{page-Dx2JD3y1.d.ts → markdown-BiKrT08O.d.ts} +2 -25
  21. package/dist/navigation.d.ts +10 -5
  22. package/dist/navigation.js +23 -10
  23. package/dist/{nuxt-B5LrERKc.d.ts → nuxt-8O2OB_hI.d.ts} +84 -7
  24. package/dist/nuxt.d.ts +2 -2
  25. package/dist/nuxt.js +1699 -105
  26. package/dist/{page-BbmSfZO8.js → page-Bb0TfRKi.js} +21 -4
  27. package/dist/page-BryUCmYf.d.ts +26 -0
  28. package/dist/primitive-rail.d.ts +2 -5
  29. package/dist/primitive-rail.js +8 -6
  30. package/dist/{raw-C03EUJKw.js → raw-BChwipz_.js} +6 -0
  31. package/dist/redirects-BJj58IsY.js +87 -0
  32. package/dist/runnable.d.ts +37 -0
  33. package/dist/runnable.js +105 -0
  34. package/dist/runtime/app/components/DocsAsideLeftBody.vue +2 -8
  35. package/dist/runtime/app/components/DocsLearn.vue +215 -0
  36. package/dist/runtime/app/components/DocsLearnCodePre.vue +98 -0
  37. package/dist/runtime/app/components/DocsLearnFile.vue +21 -0
  38. package/dist/runtime/app/components/DocsPage.vue +11 -5
  39. package/dist/runtime/app/components/DocsPlayground.vue +117 -0
  40. package/dist/runtime/app/components/content/Example.vue +18 -49
  41. package/dist/runtime/app/components/content/McpClient.vue +170 -0
  42. package/dist/runtime/app/components/content/McpInstall.vue +238 -0
  43. package/dist/runtime/app/components/content/PageList.vue +1 -5
  44. package/dist/runtime/app/layouts/docs.vue +36 -8
  45. package/dist/runtime/app/middleware/docs-layout.ts +2 -2
  46. package/dist/runtime/app/utils/docs-learn.ts +31 -0
  47. package/dist/runtime/app/utils/docs-playground.ts +3 -0
  48. package/dist/runtime/server/llms.js +1 -1
  49. package/dist/runtime/server/markdown.d.ts +0 -5
  50. package/dist/runtime/server/markdown.js +10 -1
  51. package/dist/runtime/server/mcp.js +1 -1
  52. package/dist/runtime/server/page.d.ts +1 -1
  53. package/dist/runtime/server/page.js +3 -3
  54. package/dist/runtime/server/raw.js +2 -9
  55. package/dist/runtime/server/search.d.ts +1 -1
  56. package/dist/runtime/server/search.js +3 -2
  57. package/dist/runtime/server/sitemap.js +1 -1
  58. package/dist/{schema-DwpXW0VZ.js → schema-DcWZ3Q3M.js} +97 -5
  59. package/dist/server.d.ts +3 -2
  60. package/dist/server.js +4 -4
  61. package/dist/snapshot-worker.mjs +40 -0
  62. package/dist/steps-DBlkJwtD.d.ts +105 -0
  63. package/dist/steps-DF-11dJn.js +32 -0
  64. package/dist/{types-BhG6vGfG.d.ts → types-CHU_fy9l.d.ts} +69 -4
  65. package/package.json +18 -11
  66. package/dist/error-diagnostics-BoOsP6Y4.js +0 -53
  67. package/dist/redirects-BrbWFSzW.js +0 -62
@@ -0,0 +1,215 @@
1
+ <script setup lang="ts">
2
+ import { webContainer, Workspace, type WorkspaceExample, type WorkspaceSlotProps, type WorkspaceStep } from "@vite-hub/ui/workspace"
3
+ import { fetchSnapshot } from "@vite-hub/web-container"
4
+ import { docsAppPath } from "#docs/navigation"
5
+ import { frameworkNodes, parseCurl, requestScript, restartsDevServer, splitTutorialDocument, tutorialStepFiles, tutorialWorkspaceFiles } from "#docs/runnable"
6
+ import DocsLearnCodePre from "./DocsLearnCodePre.vue"
7
+ import DocsLearnFile from "./DocsLearnFile.vue"
8
+ import { docsLearnActionsKey, docsLearnGuideNodes, docsLearnStepNodes } from "../utils/docs-learn"
9
+
10
+ import type { DocsLearnData } from "#docs/runnable"
11
+ import type { DocsLearnActions } from "../utils/docs-learn"
12
+ import type { DocsPageResponse } from "@vite-hub/docs"
13
+
14
+ type Files = Record<string, string>
15
+
16
+ const props = defineProps<{ response: DocsPageResponse, data: DocsLearnData }>()
17
+ const tutorial = props.data.tutorial
18
+ const route = useRoute()
19
+ const router = useRouter()
20
+ const { site, appBase } = useDocsConfig()
21
+
22
+ let lessonDocument = props.response.document
23
+ if (tutorial.page !== props.response.page.path) {
24
+ const { data } = await useFetch<DocsPageResponse>(docsAppPath(`/api/_docs/page${tutorial.page}.json`, appBase), { key: `docs:${tutorial.page}` })
25
+ if (!data.value) throw createError({ statusCode: 404, statusMessage: `The lesson page ${tutorial.page} was not found`, fatal: true })
26
+ lessonDocument = data.value.document
27
+ useHead({ link: [{ rel: "canonical", href: `${site.url}${docsAppPath(tutorial.page, appBase)}` }] })
28
+ }
29
+ const lesson = splitTutorialDocument(frameworkNodes(lessonDocument.nodes, "Vite"))
30
+ const steps: WorkspaceStep[] = tutorial.steps.map(item => ({ title: item.title }))
31
+ const total = steps.length
32
+
33
+ const step = computed({
34
+ get: () => {
35
+ const value = Number(route.query.step)
36
+ return Number.isInteger(value) && value >= 1 && value <= total ? value - 1 : 0
37
+ },
38
+ set: value => void router.replace({ query: { ...route.query, step: value === 0 ? undefined : String(value + 1) } }),
39
+ })
40
+
41
+ const paths = [...new Set([...Object.keys(tutorial.files), ...tutorial.steps.flatMap(item => Object.keys(item.files))])]
42
+ const guideNodes = computed(() => docsLearnGuideNodes([
43
+ ...step.value === 0 ? lesson.intro : [],
44
+ ...docsLearnStepNodes(lesson.steps[step.value]),
45
+ ...step.value === total - 1 ? lesson.outro : [],
46
+ ], new Set(paths)))
47
+
48
+ const stepFiles = (index: number, state: "start" | "solution"): Files => tutorialStepFiles(tutorial, index, state)
49
+
50
+ const prebuilt = tutorial.snapshot
51
+ const snapshot = prebuilt && (() => fetchSnapshot(prebuilt.parts, { cache: `vitehub-tutorial-${tutorial.slug}`, sha256: prebuilt.sha256 }))
52
+
53
+ const baseline = shallowRef<Files>(stepFiles(step.value, "start"))
54
+ const examples = computed<WorkspaceExample[]>(() => [
55
+ { id: tutorial.slug, label: tutorial.title, files: stepFiles(step.value, "start"), preview: props.data.preview },
56
+ ])
57
+ const resetStep = (files: Files) => tutorialWorkspaceFiles(tutorial, files, stepFiles(step.value, "start"))
58
+ const runner = webContainer({ port: props.data.port, snapshot: () => snapshot || undefined })
59
+ type Container = NonNullable<typeof runner.workspace.value>
60
+ const selected = ref(Object.keys(tutorial.steps[step.value]?.files ?? {})[0])
61
+ const open = ref(false)
62
+
63
+ const edited = computed(() => {
64
+ const files = runner.workspace.value?.files.value
65
+ if (!files) return []
66
+ const all = new Set([...Object.keys(baseline.value), ...Object.keys(files)])
67
+ return [...all].filter(path => baseline.value[path] !== files[path])
68
+ })
69
+
70
+ async function write(workspace: Container, next: Files) {
71
+ const restart = restartsDevServer(workspace.files.value, next) && ["starting", "ready"].includes(workspace.status.value)
72
+ await workspace.setFiles(next, { mode: "replace" })
73
+ if (restart) await workspace.restart()
74
+ }
75
+
76
+ async function load(target: Files) {
77
+ pendingStep.value = undefined
78
+ const workspace = runner.workspace.value
79
+ const next = workspace && tutorialWorkspaceFiles(tutorial, workspace.files.value, target)
80
+ baseline.value = target
81
+ if (workspace && next) await write(workspace, next)
82
+ }
83
+
84
+ const pendingStep = ref<number>()
85
+ watch(step, (index) => {
86
+ const first = Object.keys(tutorial.steps[index]?.files ?? {})[0]
87
+ if (first) selected.value = first
88
+ if (!runner.workspace.value || edited.value.length === 0) void load(stepFiles(index, "start"))
89
+ else pendingStep.value = index
90
+ })
91
+ function loadPending() {
92
+ if (pendingStep.value !== undefined) void load(stepFiles(pendingStep.value, "start"))
93
+ }
94
+ function keepMine() {
95
+ if (pendingStep.value === undefined) return
96
+ baseline.value = stepFiles(pendingStep.value, "start")
97
+ pendingStep.value = undefined
98
+ }
99
+ function solve(guard: WorkspaceSlotProps["guard"]) {
100
+ guard(`Replace your changes with the solution of step ${step.value + 1}?`, "Replace files", () => void load(stepFiles(step.value, "solution")))
101
+ }
102
+
103
+ const requestPath = "node_modules/.vitehub-tutorial-request.mjs"
104
+ async function run(command: string): Promise<string> {
105
+ const request = parseCurl(command)
106
+ const container = runner.workspace.value?.container.value
107
+ if (!request || !container) return "The workspace is not running."
108
+ await container.fs.mkdir("node_modules", { recursive: true })
109
+ await container.fs.writeFile(requestPath, requestScript(request))
110
+ const process = await container.run(["node", requestPath])
111
+ void process.output.cancel()
112
+ await process.exit
113
+ return (await process.text()).replace(/\u001B\[[\d;]*m/g, "").trim()
114
+ }
115
+
116
+ const actions: DocsLearnActions = {
117
+ get available() {
118
+ return !!runner.workspace.value
119
+ },
120
+ get running() {
121
+ return runner.workspace.value?.status.value === "ready" && !!runner.workspace.value.previewUrl.value
122
+ },
123
+ paths,
124
+ show(path: string) {
125
+ const workspace = runner.workspace.value
126
+ if (workspace && !(path in workspace.files.value)) void write(workspace, { ...workspace.files.value, [path]: "" })
127
+ selected.value = path
128
+ },
129
+ run,
130
+ }
131
+ provide(docsLearnActionsKey, actions)
132
+ const guideComponents = { pre: DocsLearnCodePre, DocsLearnFile }
133
+ </script>
134
+
135
+ <template>
136
+ <div class="vh-docs-workspace" :data-path="response.page.path">
137
+ <Workspace
138
+ v-model:open="open"
139
+ v-model:selected="selected"
140
+ v-model:step="step"
141
+ :steps="steps"
142
+ :guide="data.guide"
143
+ :examples="examples"
144
+ :runner="runner"
145
+ :reset="resetStep"
146
+ :share="false"
147
+ label="lesson"
148
+ >
149
+ <template #guide>
150
+ <!-- A lesson that takes its steps from a docs page links back to that page. -->
151
+ <p v-if="tutorial.page !== response.page.path" class="mb-4 text-sm text-muted">
152
+ <NuxtLink :to="tutorial.page" class="hover:text-highlighted">Read in the docs</NuxtLink>
153
+ </p>
154
+ <UPageBody prose class="docs-content docs-tutorial-content !my-0 !px-0 !pb-0">
155
+ <DocsMarkdown :key="step" :document="{ nodes: guideNodes, toc: [] }" :components="guideComponents" />
156
+ </UPageBody>
157
+ </template>
158
+
159
+ <template #bar-actions="{ guard }">
160
+ <UButton color="neutral" variant="outline" label="Solve" icon="i-lucide-wand-sparkles" @click="solve(guard)" />
161
+ </template>
162
+
163
+ <template v-if="pendingStep !== undefined" #banner>
164
+ <div class="vh-docs-learn-bar" role="status">
165
+ <span class="min-w-0 flex-1">You changed {{ edited.length === 1 ? "1 file" : `${edited.length} files` }}. Step {{ pendingStep + 1 }} has its own version.</span>
166
+ <UButton size="xs" color="neutral" variant="outline" :label="`Load step ${pendingStep + 1}`" @click="loadPending" />
167
+ <UButton size="xs" color="neutral" variant="ghost" label="Keep mine" @click="keepMine" />
168
+ </div>
169
+ </template>
170
+
171
+ <template #intro>
172
+ <h1 class="text-balance text-3xl font-semibold text-highlighted">{{ response.page.sourceTitle }}</h1>
173
+ <p v-if="response.page.description" class="mt-3 text-muted">{{ response.page.description }}</p>
174
+ </template>
175
+
176
+ <!-- Without the workspace, such as on a phone, the page is the whole lesson. -->
177
+ <template #fallback>
178
+ <UPageBody prose class="docs-content docs-tutorial-content !px-0 !pb-0">
179
+ <DocsMarkdown :document="lessonDocument" />
180
+ </UPageBody>
181
+ </template>
182
+ </Workspace>
183
+ </div>
184
+ </template>
185
+
186
+ <style scoped>
187
+ .vh-docs-workspace {
188
+ display: flex;
189
+ height: 100%;
190
+ min-height: 0;
191
+ flex-direction: column;
192
+ }
193
+
194
+ .vh-docs-workspace :deep(.vh-workspace) {
195
+ flex: 1 1 0;
196
+ min-height: 0;
197
+ }
198
+
199
+ .vh-docs-workspace :deep(.vh-workspace-gate-content) {
200
+ width: 100%;
201
+ max-width: calc(65ch + 2rem);
202
+ margin-inline: auto;
203
+ padding: 2.5rem 1rem 4rem;
204
+ }
205
+
206
+ .vh-docs-learn-bar {
207
+ display: flex;
208
+ align-items: center;
209
+ gap: 0.5rem;
210
+ border-bottom: 1px solid var(--ui-border);
211
+ background: var(--ui-bg-elevated);
212
+ padding: 0.5rem 0.75rem;
213
+ font-size: 0.8125rem;
214
+ }
215
+ </style>
@@ -0,0 +1,98 @@
1
+ <script setup lang="ts">
2
+ import { parseCurl } from "#docs/runnable"
3
+ import { docsLearnActionsKey } from "../utils/docs-learn"
4
+
5
+ const props = defineProps<{
6
+ code?: string
7
+ language?: string | null
8
+ filename?: string | null
9
+ highlights?: number[]
10
+ meta?: string | null
11
+ class?: string | null
12
+ }>()
13
+
14
+ const actions = inject(docsLearnActionsKey, undefined)
15
+ const root = useTemplateRef<HTMLElement>("root")
16
+ const command = ref(props.code)
17
+ onMounted(() => { command.value ??= root.value?.querySelector("pre")?.textContent ?? undefined })
18
+ const isFile = computed(() => !!props.filename && !!actions?.available && actions.paths.includes(props.filename))
19
+ const isRequest = computed(() => !!actions?.available && !!command.value && parseCurl(command.value) !== undefined)
20
+ const output = ref<string>()
21
+ const pending = ref(false)
22
+
23
+ async function run() {
24
+ if (!actions || !command.value) return
25
+ pending.value = true
26
+ try {
27
+ output.value = await actions.run(command.value)
28
+ }
29
+ catch (error) {
30
+ output.value = `The request did not run: ${error instanceof Error ? error.message : String(error)}`
31
+ }
32
+ finally {
33
+ pending.value = false
34
+ }
35
+ }
36
+ </script>
37
+
38
+ <template>
39
+ <div ref="root" class="vh-docs-learn-code">
40
+ <DocsCodePre v-bind="props"><slot /></DocsCodePre>
41
+ <UButton
42
+ v-if="isFile"
43
+ class="vh-docs-learn-code-action"
44
+ size="xs"
45
+ variant="ghost"
46
+ color="neutral"
47
+ icon="i-lucide-file-code"
48
+ label="Show in editor"
49
+ @click="actions?.show(filename!)"
50
+ />
51
+ <div v-if="isRequest" class="vh-docs-learn-run">
52
+ <UButton
53
+ size="xs"
54
+ variant="outline"
55
+ color="neutral"
56
+ icon="i-lucide-play"
57
+ :label="pending ? 'Running' : 'Run in workspace'"
58
+ :loading="pending"
59
+ :disabled="!actions?.running || pending"
60
+ @click="run"
61
+ />
62
+ <span v-if="!actions?.running" class="text-xs text-muted">Available when the dev server runs.</span>
63
+ </div>
64
+ <pre v-if="output !== undefined" class="vh-docs-learn-output" aria-live="polite"><code>{{ output }}</code></pre>
65
+ </div>
66
+ </template>
67
+
68
+ <style scoped>
69
+ .vh-docs-learn-code {
70
+ position: relative;
71
+ }
72
+
73
+ /* Inside the file name bar, before the copy button. */
74
+ .vh-docs-learn-code-action {
75
+ position: absolute;
76
+ top: 0.4375rem;
77
+ right: 2.5rem;
78
+ }
79
+
80
+ .vh-docs-learn-run {
81
+ display: flex;
82
+ align-items: center;
83
+ gap: 0.75rem;
84
+ margin-top: -0.5rem;
85
+ margin-bottom: 1rem;
86
+ }
87
+
88
+ .vh-docs-learn-output {
89
+ margin-block: 0 1rem;
90
+ border: 1px solid var(--ui-border);
91
+ border-radius: calc(var(--ui-radius) * 2);
92
+ background: var(--ui-bg-muted);
93
+ padding: 0.75rem;
94
+ font-size: 0.8125rem;
95
+ white-space: pre-wrap;
96
+ overflow-wrap: anywhere;
97
+ }
98
+ </style>
@@ -0,0 +1,21 @@
1
+ <script setup lang="ts">
2
+ import { WorkspaceFileLink } from "@vite-hub/ui/workspace"
3
+
4
+ defineProps<{ path: string }>()
5
+ </script>
6
+
7
+ <template>
8
+ <WorkspaceFileLink :path="path" class="vh-docs-learn-file"><slot /></WorkspaceFileLink>
9
+ </template>
10
+
11
+ <style scoped>
12
+ .vh-docs-learn-file {
13
+ cursor: pointer;
14
+ text-decoration: underline dotted var(--ui-border-accented);
15
+ text-underline-offset: 0.25em;
16
+ }
17
+
18
+ .vh-docs-learn-file:hover {
19
+ text-decoration-color: var(--ui-text-muted);
20
+ }
21
+ </style>
@@ -1,8 +1,9 @@
1
1
  <script setup lang="ts">
2
2
  import { camelize, capitalize } from "vue"
3
3
  import { pageBlocks } from "#docs/components"
4
- import { docsAppPath, docsRawPath, normalizeDocsPath } from "#docs/navigation"
4
+ import { docsAppPath, docsRawPath, isDocsWorkspaceLayout, normalizeDocsPath } from "#docs/navigation"
5
5
  import { articleLayout } from "#docs/shell"
6
+ import workspaces from "#docs/workspaces"
6
7
 
7
8
  import type { Node as ComarkNode } from "comark"
8
9
  import type { DocsDocument, DocsPageResponse } from "@vite-hub/docs"
@@ -20,15 +21,17 @@ const { page } = response
20
21
  const isRoot = page.path === manifest.root?.path
21
22
  // A page that `start.links` lists opens inside the start section, like the pages of a section.
22
23
  const isStartLink = isDocsStartLink(useDocsConfig(), page.path)
24
+ const loadWorkspace = isDocsWorkspaceLayout(page.layout) ? workspaces[page.path] : undefined
25
+ const workspace = loadWorkspace && (await loadWorkspace()).default
23
26
  // Content previews can change a page's layout or add a home page after the manifest was built.
24
- const layout = page.layout !== "home" && (response.section || isRoot || isStartLink) ? "docs" : articleLayout
27
+ const layout = isDocsWorkspaceLayout(page.layout) || (page.layout !== "home" && (response.section || isRoot || isStartLink)) ? "docs" : articleLayout
25
28
  if (import.meta.client && route.meta.layout !== layout) {
26
29
  // The server has already rendered the manifest's layout. Finish hydrating it before switching shells.
27
30
  if (useNuxtApp().isHydrating) onNuxtReady(() => setPageLayout(layout))
28
31
  else setPageLayout(layout)
29
32
  }
30
33
  // A page outside the docs base has no section. It reads as a plain article under the site header.
31
- const isStandalone = !response.section && !isRoot && !isStartLink && page.layout !== "home"
34
+ const isStandalone = !response.section && !isRoot && !isStartLink && page.layout !== "home" && !isDocsWorkspaceLayout(page.layout)
32
35
 
33
36
  // A home page draws the app's `components/content/` blocks at full width. The Markdown between two of them, such as a
34
37
  // heading and a list, goes in one column with the prose styles of a docs page.
@@ -66,13 +69,16 @@ useDocsSeo({
66
69
  description: page.seo?.description ?? page.description,
67
70
  section: section && { title: section.title, path: docsAppPath(section.path, appBase) },
68
71
  image: indexed ? page.seo?.image : false,
69
- type: isRoot || page.layout === "landing" || page.layout === "home" ? "page" : "article",
72
+ type: isRoot || page.layout === "landing" || page.layout === "home" || page.layout === "playground" ? "page" : "article",
70
73
  })
71
74
  </script>
72
75
 
73
76
  <template>
74
77
  <!-- The layout's UMain is the page's only main landmark. -->
75
- <div v-if="isStandalone" class="mx-auto w-full max-w-3xl px-4 pb-24 pt-14 sm:px-6 sm:pt-20 lg:px-8 lg:pt-24" :data-path="page.path">
78
+ <LazyDocsLearn v-if="workspace?.layout === 'learn'" :key="page.path" :response="response" :data="workspace" />
79
+ <LazyDocsPlayground v-else-if="workspace" :key="page.path" :response="response" :data="workspace" />
80
+
81
+ <div v-else-if="isStandalone" class="mx-auto w-full max-w-3xl px-4 pb-24 pt-14 sm:px-6 sm:pt-20 lg:px-8 lg:pt-24" :data-path="page.path">
76
82
  <UPageHeader
77
83
  :headline="page.eyebrow ?? undefined"
78
84
  :title="page.sourceTitle"
@@ -0,0 +1,117 @@
1
+ <script setup lang="ts">
2
+ import { defineAsyncComponent } from "vue"
3
+ import { render, webContainer, Workspace, type WorkspaceExample, type WorkspaceRunner, type WorkspaceSnapshot } from "@vite-hub/ui/workspace"
4
+ import { fetchSnapshot } from "@vite-hub/web-container"
5
+ import { defineConnect, type ConnectConfig } from "@vite-hub/web-container/connect"
6
+ import { docsAppPath } from "#docs/navigation"
7
+ import { docsPlaygroundExampleQuery } from "../utils/docs-playground"
8
+
9
+ import type { DocsWorkspaceData } from "#docs/runnable"
10
+ import type { DocsPageResponse } from "@vite-hub/docs"
11
+
12
+ const props = defineProps<{ response: DocsPageResponse, data: Exclude<DocsWorkspaceData, { layout: "learn" }> }>()
13
+ const route = useRoute()
14
+ const router = useRouter()
15
+ const { page } = props.response
16
+ const { appBase, site } = useDocsConfig()
17
+
18
+ const snapshots = new Map<string, WorkspaceSnapshot>()
19
+ const snapshotOf = new Map<string, string>()
20
+ const examples: WorkspaceExample[] = props.data.examples.map(({ snapshot: prebuilt, snapshotOf: key, ...example }) => {
21
+ if (key && prebuilt && !snapshots.has(key)) {
22
+ snapshots.set(key, () => fetchSnapshot(prebuilt.parts, { cache: `vitehub-tutorial-${key}`, sha256: prebuilt.sha256 }))
23
+ }
24
+ if (key) snapshotOf.set(example.id, key)
25
+ return example
26
+ })
27
+ const connectConfig: ConnectConfig = {}
28
+ for (const name of props.data.connect ?? []) connectConfig[name] = true
29
+ const connect = props.data.connect?.length ? defineConnect(connectConfig) : undefined
30
+ const load = props.data.render
31
+ const runner: WorkspaceRunner = load
32
+ ? render(async (files, context) => (await load()).default(files, context))
33
+ : webContainer({ connect, port: props.data.port, snapshot: example => snapshots.get(snapshotOf.get(example.id) ?? "") })
34
+ const zipPrefix = site.name.toLowerCase().replace(/[^a-z\d]+/g, "-").replace(/^-|-$/g, "")
35
+ const tabs = (props.data.tabs ?? []).map(tab => ({ value: tab.value, label: tab.label, component: defineAsyncComponent(async () => (await tab.component()).default) }))
36
+ const tabItems = tabs.map(({ value, label }) => ({ value, label }))
37
+
38
+ const example = computed(() => [route.query.example, route.query.template].find((value): value is string => typeof value === "string" && examples.some(example => example.id === value)))
39
+ const open = ref(false)
40
+
41
+ function keep(id: string) {
42
+ void router.replace({ query: { ...route.query, example: docsPlaygroundExampleQuery(examples, id), template: undefined }, hash: "" })
43
+ }
44
+ function exampleHref(id: string) {
45
+ const query = docsPlaygroundExampleQuery(examples, id)
46
+ return docsAppPath(query ? `${page.path}?example=${encodeURIComponent(query)}` : page.path, appBase)
47
+ }
48
+ </script>
49
+
50
+ <template>
51
+ <div class="vh-docs-workspace" :data-path="page.path">
52
+ <Workspace
53
+ v-model:open="open"
54
+ :examples="examples"
55
+ :example="example"
56
+ :runner="runner"
57
+ :tabs="tabItems"
58
+ :start="examples.length > 1 && !example"
59
+ label="playground"
60
+ :name="zipPrefix"
61
+ @update:example="keep"
62
+ >
63
+ <template v-for="tab in tabs" :key="tab.value" #[tab.value]>
64
+ <component :is="tab.component" />
65
+ </template>
66
+
67
+ <template #intro>
68
+ <h1 class="text-balance text-3xl font-semibold text-highlighted">{{ page.sourceTitle }}</h1>
69
+ <p v-if="page.description" class="mt-3 text-muted">{{ page.description }}</p>
70
+ </template>
71
+
72
+ <!-- Without the workspace, such as on a phone, the page shows its own text and the examples. -->
73
+ <template #fallback>
74
+ <UPageBody prose class="docs-content !px-0 !pb-0">
75
+ <DocsMarkdown :document="response.document" />
76
+ </UPageBody>
77
+ <h2 class="mt-10 text-lg font-semibold text-highlighted">Examples</h2>
78
+ <ul class="vh-docs-playground-list">
79
+ <li v-for="item in examples" :key="item.id">
80
+ <!-- A new document boots the example, as a link from another page does. -->
81
+ <a :href="exampleHref(item.id)" class="font-medium text-highlighted">{{ item.label }}</a>
82
+ <span v-if="item.description" class="text-muted">: {{ item.description }}</span>
83
+ </li>
84
+ </ul>
85
+ </template>
86
+ </Workspace>
87
+ </div>
88
+ </template>
89
+
90
+ <style scoped>
91
+ .vh-docs-workspace {
92
+ display: flex;
93
+ height: 100%;
94
+ min-height: 0;
95
+ flex-direction: column;
96
+ }
97
+
98
+ .vh-docs-workspace :deep(.vh-workspace) {
99
+ flex: 1 1 0;
100
+ min-height: 0;
101
+ }
102
+
103
+ .vh-docs-workspace :deep(.vh-workspace-gate-content) {
104
+ width: 100%;
105
+ max-width: calc(65ch + 2rem);
106
+ margin-inline: auto;
107
+ padding: 2.5rem 1rem 4rem;
108
+ }
109
+
110
+ .vh-docs-playground-list {
111
+ margin-top: 0.75rem;
112
+ display: grid;
113
+ gap: 0.5rem;
114
+ padding-inline-start: 1.25rem;
115
+ list-style: disc;
116
+ }
117
+ </style>
@@ -23,24 +23,21 @@ const view = defineModel<"preview" | "code">("view", { default: "preview" })
23
23
  const loader = props.name ? examples[props.name] : undefined
24
24
  const live = loader ? defineAsyncComponent(loader) : undefined
25
25
  const mounts = ref(0)
26
- const seg = useTemplateRef<HTMLElement>("seg")
27
- const thumb = ref<{ left: number, width: number, slide: boolean } | null>(null)
28
-
29
- // The thumb slides under the pressed button. Its place is measured, because "Preview" and "Code" differ in width.
30
- function place(slide = false) {
31
- const button = seg.value?.querySelector<HTMLElement>(`[data-view="${view.value}"]`)
32
- if (button?.offsetWidth) thumb.value = { left: button.offsetLeft, width: button.offsetWidth, slide }
26
+ const views = ["preview", "code"] as const
27
+
28
+ // A segmented switch is a radio group: arrow keys move the choice and the focus, and only the checked radio is a tab
29
+ // stop. The motion layer moves the raised look from one radio to the other.
30
+ function onKeydown(event: KeyboardEvent) {
31
+ const step = { ArrowLeft: -1, ArrowUp: -1, ArrowRight: 1, ArrowDown: 1 }[event.key]
32
+ if (!step) return
33
+ event.preventDefault()
34
+ const group = event.currentTarget
35
+ const next = views[(views.indexOf(view.value) + step + views.length) % views.length]!
36
+ view.value = next
37
+ nextTick(() => {
38
+ if (group instanceof HTMLElement) group.querySelector<HTMLElement>(`[data-view="${next}"]`)?.focus()
39
+ })
33
40
  }
34
-
35
- // A switch in a hidden tab measures zero, so it's placed again, without sliding, whenever its size changes: when its
36
- // tab opens or the font loads.
37
- let resizes: ResizeObserver | undefined
38
- watch(view, () => nextTick(() => place(true)))
39
- onMounted(() => {
40
- resizes = new ResizeObserver(() => place())
41
- if (seg.value) resizes.observe(seg.value)
42
- })
43
- onBeforeUnmount(() => resizes?.disconnect())
44
41
  </script>
45
42
 
46
43
  <template>
@@ -55,10 +52,8 @@ onBeforeUnmount(() => resizes?.disconnect())
55
52
  <UIcon name="i-lucide-rotate-ccw" class="size-3.5" />
56
53
  Reset
57
54
  </button>
58
- <div ref="seg" class="vh-seg" role="group" aria-label="View">
59
- <span v-if="thumb" class="vh-seg-thumb" :class="{ 'is-still': !thumb.slide }" :style="{ transform: `translateX(${thumb.left - 3}px)`, width: `${thumb.width}px` }" aria-hidden="true" />
60
- <button type="button" data-focus-inset data-view="preview" :aria-pressed="view === 'preview'" :class="{ 'is-unmeasured': !thumb }" @click="view = 'preview'">Preview</button>
61
- <button type="button" data-focus-inset data-view="code" :aria-pressed="view === 'code'" :class="{ 'is-unmeasured': !thumb }" @click="view = 'code'">Code</button>
55
+ <div class="vh-seg" role="radiogroup" aria-label="View" @keydown="onKeydown">
56
+ <button v-for="name in views" :key="name" type="button" role="radio" data-focus-inset :data-view="name" :aria-checked="view === name" :tabindex="view === name ? 0 : -1" @click="view = name">{{ name === "preview" ? "Preview" : "Code" }}</button>
62
57
  </div>
63
58
  </div>
64
59
  <div class="vh-example-body">
@@ -121,7 +116,7 @@ onBeforeUnmount(() => resizes?.disconnect())
121
116
  }
122
117
  }
123
118
 
124
- /* A segmented switch: a muted track and a raised thumb that slides to the pressed button. */
119
+ /* A segmented switch: a muted track, and a raised look on the checked radio, which the motion layer moves. */
125
120
  .vh-seg {
126
121
  position: relative;
127
122
  display: inline-flex;
@@ -130,17 +125,6 @@ onBeforeUnmount(() => resizes?.disconnect())
130
125
  padding: 3px;
131
126
  }
132
127
 
133
- .vh-seg-thumb {
134
- position: absolute;
135
- top: 3px;
136
- bottom: 3px;
137
- left: 3px;
138
- border-radius: 6px;
139
- background: var(--vh-raised);
140
- box-shadow: 0 0 0 1px var(--ui-border);
141
- transition: transform 200ms var(--vh-ease-out), width 200ms var(--vh-ease-out);
142
- }
143
-
144
128
  .vh-seg button {
145
129
  position: relative;
146
130
  border-radius: 6px;
@@ -152,13 +136,9 @@ onBeforeUnmount(() => resizes?.disconnect())
152
136
  transition: color 150ms ease;
153
137
  }
154
138
 
155
- /* Before the thumb is measured, the pressed button carries the raised surface itself. */
156
- .vh-seg button.is-unmeasured[aria-pressed="true"] {
139
+ .vh-seg button[aria-checked="true"] {
157
140
  background: var(--vh-raised);
158
141
  box-shadow: 0 0 0 1px var(--ui-border);
159
- }
160
-
161
- .vh-seg button[aria-pressed="true"] {
162
142
  color: var(--ui-text-highlighted);
163
143
  }
164
144
 
@@ -168,7 +148,6 @@ onBeforeUnmount(() => resizes?.disconnect())
168
148
  }
169
149
  }
170
150
 
171
-
172
151
  /* Touch screens get 44px targets. */
173
152
  @media (pointer: coarse) {
174
153
  .vh-seg button {
@@ -181,16 +160,6 @@ onBeforeUnmount(() => resizes?.disconnect())
181
160
  }
182
161
  }
183
162
 
184
- .vh-seg-thumb.is-still {
185
- transition: none;
186
- }
187
-
188
- @media (prefers-reduced-motion: reduce) {
189
- .vh-seg-thumb {
190
- transition: none;
191
- }
192
- }
193
-
194
163
  /* The preview sits in a hairline frame. The source shows in its own code block. */
195
164
  .vh-example[data-view="preview"] > .vh-example-body:has(> .docs-example-preview) > :deep(:not(.docs-example-preview)),
196
165
  .vh-example[data-view="code"] > .vh-example-body > :deep(.docs-example-preview) {