@vite-hub/docs 0.4.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 (57) hide show
  1. package/README.md +164 -6
  2. package/dist/{assistant-pages-BN7hNsSZ.js → assistant-pages-CqNlHsx-.js} +1 -1
  3. package/dist/{assistant-shared-WzButktj.js → assistant-shared-DhiLHKSl.js} +2 -2
  4. package/dist/assistant-worker.js +1 -1
  5. package/dist/assistant.js +1 -1
  6. package/dist/{content-CPZGnn3S.js → content-BQVlMshL.js} +55 -15
  7. package/dist/{draft-BjWmaiLn.js → draft-CSsTYSeb.js} +2 -2
  8. package/dist/{error-diagnostics-B_ZOy7kF.js → error-diagnostics-CmgtG9xa.js} +64 -0
  9. package/dist/index.d.ts +7 -6
  10. package/dist/index.js +4 -4
  11. package/dist/link-checker-redirects.js +1 -1
  12. package/dist/{manifest-CMoxcwPm.d.ts → manifest-Drbdw1us.d.ts} +1 -1
  13. package/dist/{manifest-ZdxLrcvt.js → manifest-DvECmwX-.js} +62 -26
  14. package/dist/{markdown-DUWnEMPp.js → markdown-1M1FbjCw.js} +1 -1
  15. package/dist/{page-Dx2JD3y1.d.ts → markdown-BiKrT08O.d.ts} +2 -25
  16. package/dist/navigation.d.ts +9 -3
  17. package/dist/navigation.js +22 -8
  18. package/dist/{nuxt-CAGpKl_-.d.ts → nuxt-8O2OB_hI.d.ts} +80 -4
  19. package/dist/nuxt.d.ts +2 -2
  20. package/dist/nuxt.js +1269 -58
  21. package/dist/{page-GPt09oex.js → page-Bb0TfRKi.js} +19 -3
  22. package/dist/page-BryUCmYf.d.ts +26 -0
  23. package/dist/primitive-rail.d.ts +1 -4
  24. package/dist/primitive-rail.js +1 -4
  25. package/dist/{redirects-CmR1yu5A.js → redirects-BJj58IsY.js} +34 -21
  26. package/dist/runnable.d.ts +37 -0
  27. package/dist/runnable.js +105 -0
  28. package/dist/runtime/app/components/DocsAsideLeftBody.vue +2 -8
  29. package/dist/runtime/app/components/DocsLearn.vue +215 -0
  30. package/dist/runtime/app/components/DocsLearnCodePre.vue +98 -0
  31. package/dist/runtime/app/components/DocsLearnFile.vue +21 -0
  32. package/dist/runtime/app/components/DocsPage.vue +11 -5
  33. package/dist/runtime/app/components/DocsPlayground.vue +117 -0
  34. package/dist/runtime/app/components/content/Example.vue +18 -49
  35. package/dist/runtime/app/components/content/PageList.vue +1 -5
  36. package/dist/runtime/app/layouts/docs.vue +36 -8
  37. package/dist/runtime/app/middleware/docs-layout.ts +2 -2
  38. package/dist/runtime/app/utils/docs-learn.ts +31 -0
  39. package/dist/runtime/app/utils/docs-playground.ts +3 -0
  40. package/dist/runtime/server/llms.js +1 -1
  41. package/dist/runtime/server/markdown.d.ts +0 -5
  42. package/dist/runtime/server/markdown.js +10 -1
  43. package/dist/runtime/server/mcp.js +1 -1
  44. package/dist/runtime/server/page.d.ts +1 -1
  45. package/dist/runtime/server/page.js +3 -3
  46. package/dist/runtime/server/raw.js +2 -9
  47. package/dist/runtime/server/search.d.ts +1 -1
  48. package/dist/runtime/server/search.js +3 -2
  49. package/dist/runtime/server/sitemap.js +1 -1
  50. package/dist/{schema-DwpXW0VZ.js → schema-DcWZ3Q3M.js} +97 -5
  51. package/dist/server.d.ts +3 -2
  52. package/dist/server.js +3 -3
  53. package/dist/snapshot-worker.mjs +40 -0
  54. package/dist/steps-DBlkJwtD.d.ts +105 -0
  55. package/dist/steps-DF-11dJn.js +32 -0
  56. package/dist/{types-BhG6vGfG.d.ts → types-CHU_fy9l.d.ts} +69 -4
  57. package/package.json +17 -10
@@ -1,4 +1,4 @@
1
- import { docsManifestPages, docsPanelOf, docsPanelPages, isDocsPath } from "./navigation.js";
1
+ import { docsManifestPages, docsPanelOf, docsPanelPages, isDocsPath, isDocsWorkspaceLayout } from "./navigation.js";
2
2
  //#region src/page.ts
3
3
  /** Previous and next follow the sidebar order of the page's section, or of its panel for a page inside one. */
4
4
  function docsPageResponse(manifest, found, document, credits = null) {
@@ -23,6 +23,7 @@ function docsPageResponse(manifest, found, document, credits = null) {
23
23
  function docsPageOf(frontmatter, at) {
24
24
  const navigation = frontmatter.navigation === false ? void 0 : frontmatter.navigation;
25
25
  const layout = frontmatter.layout ?? "article";
26
+ const workspace = isDocsWorkspaceLayout(layout);
26
27
  return {
27
28
  id: at.id,
28
29
  path: at.path || "/",
@@ -39,8 +40,9 @@ function docsPageOf(frontmatter, at) {
39
40
  ...frontmatter.tutorial ? { tutorial: frontmatter.tutorial } : {},
40
41
  ...frontmatter.codePanel ? { codePanel: true } : {},
41
42
  ...frontmatter.seo ? { seo: frontmatter.seo } : {},
42
- sidebar: frontmatter.sidebar ?? true,
43
- toc: frontmatter.toc ?? (layout !== "landing" && layout !== "home"),
43
+ ...workspace ? { workspace: workspaceOf(frontmatter) } : {},
44
+ sidebar: frontmatter.sidebar ?? (workspace ? "collapsed" : true),
45
+ toc: frontmatter.toc ?? (layout !== "landing" && layout !== "home" && !workspace),
44
46
  kind: navigation?.kind ?? null,
45
47
  group: navigation?.group ?? null,
46
48
  navigation: frontmatter.navigation !== false,
@@ -48,6 +50,20 @@ function docsPageOf(frontmatter, at) {
48
50
  order: navigation?.order ?? Number.MAX_SAFE_INTEGER
49
51
  };
50
52
  }
53
+ function workspaceOf(frontmatter) {
54
+ const { examples, tabs, render, connect, port, fixture, guide, lesson, preview } = frontmatter;
55
+ return {
56
+ examples,
57
+ tabs,
58
+ render,
59
+ connect,
60
+ port,
61
+ fixture,
62
+ guide,
63
+ lesson,
64
+ preview
65
+ };
66
+ }
51
67
  /**
52
68
  * The URL of a page file, from its path below the content folder without `.md`: `docs/kv/index` is `/docs/kv`, `about`
53
69
  * is `/about`, and `index` is `/`.
@@ -0,0 +1,26 @@
1
+ import { n as DocsManifest, o as DocsSection, r as DocsPage } from "./types-CHU_fy9l.js";
2
+ import { t as DocsDocument } from "./markdown-BiKrT08O.js";
3
+ //#region src/page.d.ts
4
+ interface DocsPageLink {
5
+ path: string;
6
+ title: string;
7
+ description: string | null;
8
+ }
9
+ /** What the page route returns for one URL. The client renders it as is. */
10
+ interface DocsPageResponse {
11
+ page: DocsPage;
12
+ /** Id of the section that owns the page, or `null` for the root page and pages outside the base. */
13
+ section: string | null;
14
+ document: DocsDocument;
15
+ /** The page's `credits`, parsed like its body, or `null` without them. */
16
+ credits: DocsDocument | null;
17
+ prev: DocsPageLink | null;
18
+ next: DocsPageLink | null;
19
+ }
20
+ /** Previous and next follow the sidebar order of the page's section, or of its panel for a page inside one. */
21
+ declare function docsPageResponse(manifest: DocsManifest, found: {
22
+ page: DocsPage;
23
+ section: DocsSection | null;
24
+ }, document: DocsDocument, credits?: DocsDocument | null): DocsPageResponse;
25
+ //#endregion
26
+ export { DocsPageResponse as n, docsPageResponse as r, DocsPageLink as t };
@@ -10,10 +10,7 @@ export declare function isPrimitiveIconName(value: unknown): value is PrimitiveI
10
10
  export declare const primitiveIconNames: readonly PrimitiveIconName[];
11
11
  /** Returns the set icon that an Iconify name such as `i-vitehub-kv` or `vitehub:kv` names, or a bare name such as `kv`. */
12
12
  export declare function resolvePrimitiveIconName(icon: string): PrimitiveIconName | undefined;
13
- /**
14
- * Inline SVG of a `@vite-hub/icons` icon, so the part that each icon marks with `data-motion` can move when its rail item
15
- * gets a pointer or keyboard focus. `styles.css` sets the motion of each icon. Strokes use currentColor.
16
- */
13
+ /** Inline SVG of a `@vite-hub/icons` icon. Strokes use currentColor. */
17
14
  export declare const PrimitiveIcon: import("vue").DefineComponent<import("vue").ExtractPropTypes<{
18
15
  name: {
19
16
  required: true;
@@ -85,10 +85,7 @@ function resolvePrimitiveIconName(icon) {
85
85
  const name = icon.replace(/^(?:i-vitehub-|vitehub:)/, "");
86
86
  return isPrimitiveIconName(name) ? name : void 0;
87
87
  }
88
- /**
89
- * Inline SVG of a `@vite-hub/icons` icon, so the part that each icon marks with `data-motion` can move when its rail item
90
- * gets a pointer or keyboard focus. `styles.css` sets the motion of each icon. Strokes use currentColor.
91
- */
88
+ /** Inline SVG of a `@vite-hub/icons` icon. Strokes use currentColor. */
92
89
  const PrimitiveIcon = defineComponent({
93
90
  name: "PrimitiveIcon",
94
91
  props: { name: {
@@ -1,5 +1,5 @@
1
1
  import { docsManifestPages, docsRawPath, docsSectionForPath, isDocsPath, normalizeDocsPath } from "./navigation.js";
2
- import { t as docsErrorDiagnostics } from "./error-diagnostics-B_ZOy7kF.js";
2
+ import { t as docsErrorDiagnostics } from "./error-diagnostics-CmgtG9xa.js";
3
3
  import { addRoute, createRouter, findRoute } from "rou3";
4
4
  //#region src/redirects.ts
5
5
  /**
@@ -16,7 +16,6 @@ function docsRedirects(routeRules) {
16
16
  }];
17
17
  });
18
18
  }
19
- /** A docs page or the Markdown copy of one that answers a URL path. */
20
19
  function docsPaths(manifest) {
21
20
  return new Set(docsManifestPages(manifest).flatMap((page) => [page.path, docsRawPath(page.path)]));
22
21
  }
@@ -38,34 +37,48 @@ function docsRedirectProblems(manifest, redirects, serverRoutes = []) {
38
37
  const pages = docsPaths(manifest);
39
38
  const routes = createRouter();
40
39
  for (const { route, method } of serverRoutes) addRoute(routes, method, route, true);
41
- const next = new Map(redirects.map((redirect) => [normalizeDocsPath(redirect.from), redirect.to]));
40
+ const next = new Map(redirects.filter((redirect) => !isTrailingSlashRedirect(redirect)).map((redirect) => [routeRulePath(redirect.from), redirect.to]));
42
41
  const problems = [];
43
- for (const { from, to } of redirects) {
44
- const source = normalizeDocsPath(from);
45
- const page = docsManifestPages(manifest).find((candidate) => candidate.path === source || docsRawPath(candidate.path) === source);
42
+ for (const redirect of redirects) {
43
+ const { from, to } = redirect;
44
+ const source = routeRulePath(from);
45
+ const trailingSlashRedirect = isTrailingSlashRedirect(redirect);
46
+ const page = trailingSlashRedirect ? void 0 : docsManifestPages(manifest).find((candidate) => candidate.path === source || docsRawPath(candidate.path) === source);
46
47
  if (page) problems.push(`The redirect from ${from} hides the page ${page.file}. Remove the route rule, or move the page.`);
47
- const seen = /* @__PURE__ */ new Set([source]);
48
+ const seen = new Set(trailingSlashRedirect ? [] : [source]);
48
49
  let end = to;
49
- let target = targetPath(end);
50
- while (target !== void 0 && next.has(target) && !seen.has(target)) {
51
- seen.add(target);
52
- end = next.get(target);
53
- target = targetPath(end);
50
+ let path = localTargetPath(end);
51
+ while (path !== void 0) {
52
+ const target = normalizeDocsPath(path);
53
+ const rulePath = routeRulePath(path);
54
+ const key = !next.has(rulePath) && path.endsWith("/") && pages.has(target) ? target : rulePath;
55
+ const redirectTarget = next.get(key);
56
+ if (seen.has(key)) {
57
+ problems.push(`The redirect from ${from} comes back to ${key} and never reaches a page. Point one of its route rules to a page.`);
58
+ break;
59
+ }
60
+ if (redirectTarget === void 0) {
61
+ if ((target.startsWith("/raw/") || docsSectionForPath(manifest, target) !== null || manifest.base !== "/" && isDocsPath(target, manifest.base)) && !pages.has(target) && !findRoute(routes, "GET", path)) problems.push(`The redirect from ${from} goes to ${end}, which is not a docs page. Point it to a page, or remove the route rule.`);
62
+ break;
63
+ }
64
+ seen.add(key);
65
+ end = redirectTarget;
66
+ path = localTargetPath(end);
54
67
  }
55
- if (target === void 0) continue;
56
- if (seen.has(target)) {
57
- problems.push(`The redirect from ${from} comes back to ${target} and never reaches a page. Point one of its route rules to a page.`);
58
- continue;
59
- }
60
- if ((target.startsWith("/raw/") || docsSectionForPath(manifest, target) !== null || manifest.base !== "/" && isDocsPath(target, manifest.base)) && !pages.has(target) && !findRoute(routes, "GET", end.replace(/[?#].*$/, ""))) problems.push(`The redirect from ${from} goes to ${end}, which is not a docs page. Point it to a page, or remove the route rule.`);
61
68
  }
62
69
  return problems;
63
70
  }
64
- function targetPath(to) {
71
+ function routeRulePath(path) {
72
+ return path.replace(/\/$/, "") || "/";
73
+ }
74
+ function isTrailingSlashRedirect({ from, to }) {
75
+ const target = localTargetPath(to);
76
+ return target !== void 0 && target !== from && target === routeRulePath(from);
77
+ }
78
+ function localTargetPath(to) {
65
79
  if (!to.startsWith("/") || to.startsWith("//")) return void 0;
66
- return normalizeDocsPath(to.replace(/[?#].*$/, ""));
80
+ return to.replace(/[?#].*$/, "");
67
81
  }
68
- /** Redirect route rules that break links. The build stops on them while the link checker is on. */
69
82
  /** `DOCS_REDIRECTS_BROKEN`, with the list of problems in `problems`. */
70
83
  function docsRedirectError(problems) {
71
84
  return Object.assign(docsErrorDiagnostics.DOCS_REDIRECTS_BROKEN({ problems }), { problems });
@@ -0,0 +1,37 @@
1
+ import { t as DocsDocument } from "./markdown-BiKrT08O.js";
2
+ import { a as DocsWorkspaceData, c as RunnableTutorialData, d as dependencyKey, f as restartsDevServer, i as DocsRenderFunction, l as RunnableTutorialStep, m as tutorialWorkspaceFiles, n as DocsPlaygroundData, o as DocsWorkspaceTab, p as tutorialStepFiles, r as DocsPlaygroundExampleData, s as PlaygroundTemplate, t as DocsLearnData, u as TutorialFiles } from "./steps-DBlkJwtD.js";
3
+ //#region src/runnable/document.d.ts
4
+ type DocsNode = DocsDocument["nodes"][number];
5
+ /**
6
+ * The nodes as a reader of one framework sees them: each `::tabs{sync="framework"}` block becomes the content of that
7
+ * framework's tab. A runnable lesson runs a Vite workspace, so its guide shows the Vite tab, whatever the reader picked.
8
+ */
9
+ export declare function frameworkNodes(nodes: readonly DocsNode[], framework: string): DocsNode[];
10
+ /** Splits a lesson page into the prose before the first step, one node per `::tutorial-step`, and the prose after the last. */
11
+ export declare function splitTutorialDocument(nodes: readonly DocsNode[]): {
12
+ intro: DocsNode[];
13
+ steps: DocsNode[];
14
+ outro: DocsNode[];
15
+ };
16
+ /** A request of a lesson command, which the workspace sends from inside the WebContainer. */
17
+ interface TutorialRequest {
18
+ method: string;
19
+ url: string;
20
+ headers: Record<string, string>;
21
+ body?: string;
22
+ }
23
+ /** Reads the `curl` command of a lesson, such as `curl -X POST http://localhost:3000/api/greet -d '{}'`. Other commands return `undefined`. */
24
+ export declare function parseCurl(command: string): TutorialRequest | undefined;
25
+ /** A Node script that sends the request from inside the workspace and prints the status and the body, like `curl`. */
26
+ export declare function requestScript(request: TutorialRequest): string;
27
+ //#endregion
28
+ //#region src/runnable/learn.d.ts
29
+ /** What the Learn page shows about one tutorial page, read from its Markdown. */
30
+ interface LearnPageFacts {
31
+ /** The `::tutorial-step` blocks. */
32
+ steps: number;
33
+ /** About how long the tutorial takes, in minutes. */
34
+ minutes: number;
35
+ }
36
+ //#endregion
37
+ export { type DocsLearnData, type DocsPlaygroundData, type DocsPlaygroundExampleData, type DocsRenderFunction, type DocsWorkspaceData, type DocsWorkspaceTab, type LearnPageFacts, type PlaygroundTemplate, type RunnableTutorialData, type RunnableTutorialStep, type TutorialFiles, type TutorialRequest, dependencyKey, restartsDevServer, tutorialStepFiles, tutorialWorkspaceFiles };
@@ -0,0 +1,105 @@
1
+ import { i as tutorialWorkspaceFiles, n as restartsDevServer, r as tutorialStepFiles, t as dependencyKey } from "./steps-DF-11dJn.js";
2
+ //#region src/runnable/document.ts
3
+ /**
4
+ * The nodes as a reader of one framework sees them: each `::tabs{sync="framework"}` block becomes the content of that
5
+ * framework's tab. A runnable lesson runs a Vite workspace, so its guide shows the Vite tab, whatever the reader picked.
6
+ */
7
+ function frameworkNodes(nodes, framework) {
8
+ return nodes.flatMap((node) => {
9
+ if (!Array.isArray(node) || node[0] === null) return [node];
10
+ const [tag, props, ...children] = node;
11
+ if (tag === "tabs" && props?.sync === "framework") {
12
+ const item = children.find((child) => Array.isArray(child) && child[0] === "tabs-item" && child[1]?.label === framework);
13
+ if (!Array.isArray(item)) return [];
14
+ const [, , ...content] = item;
15
+ return frameworkNodes(content, framework);
16
+ }
17
+ return [[
18
+ tag,
19
+ props,
20
+ ...frameworkNodes(children, framework)
21
+ ]];
22
+ });
23
+ }
24
+ function isStep(node) {
25
+ return Array.isArray(node) && node[0] === "tutorial-step";
26
+ }
27
+ /** Splits a lesson page into the prose before the first step, one node per `::tutorial-step`, and the prose after the last. */
28
+ function splitTutorialDocument(nodes) {
29
+ const first = nodes.findIndex(isStep);
30
+ const last = nodes.findLastIndex(isStep);
31
+ if (first === -1) return {
32
+ intro: [...nodes],
33
+ steps: [],
34
+ outro: []
35
+ };
36
+ return {
37
+ intro: nodes.slice(0, first),
38
+ steps: nodes.slice(first, last + 1).filter(isStep),
39
+ outro: nodes.slice(last + 1)
40
+ };
41
+ }
42
+ function tokenize(command) {
43
+ const tokens = [];
44
+ let current = "";
45
+ let quote;
46
+ let started = false;
47
+ const source = command.replace(/\\\n/g, " ");
48
+ for (let index = 0; index < source.length; index++) {
49
+ const char = source[index];
50
+ if (quote) {
51
+ if (char === quote) quote = void 0;
52
+ else if (char === "\\" && quote === "\"" && index + 1 < source.length) current += source[++index];
53
+ else current += char;
54
+ } else if (char === "'" || char === "\"") {
55
+ quote = char;
56
+ started = true;
57
+ } else if (/\s/.test(char)) {
58
+ if (started || current) tokens.push(current);
59
+ current = "";
60
+ started = false;
61
+ } else current += char;
62
+ }
63
+ if (started || current) tokens.push(current);
64
+ return tokens;
65
+ }
66
+ /** Reads the `curl` command of a lesson, such as `curl -X POST http://localhost:3000/api/greet -d '{}'`. Other commands return `undefined`. */
67
+ function parseCurl(command) {
68
+ const tokens = tokenize(command.trim());
69
+ if (tokens[0] !== "curl") return void 0;
70
+ const request = {
71
+ method: "",
72
+ url: "",
73
+ headers: {}
74
+ };
75
+ for (let index = 1; index < tokens.length; index++) {
76
+ const token = tokens[index];
77
+ const value = () => tokens[++index] ?? "";
78
+ if (token === "-X" || token === "--request") request.method = value().toUpperCase();
79
+ else if (token === "-H" || token === "--header") {
80
+ const header = value();
81
+ const colon = header.indexOf(":");
82
+ if (colon > 0) request.headers[header.slice(0, colon).trim()] = header.slice(colon + 1).trim();
83
+ } else if (token === "-d" || token === "--data" || token === "--data-raw") request.body = value();
84
+ else if (token.startsWith("-")) return void 0;
85
+ else request.url = token;
86
+ }
87
+ if (!/^https?:\/\/localhost(?::\d+)?\//.test(request.url)) return void 0;
88
+ request.method ||= request.body === void 0 ? "GET" : "POST";
89
+ return request;
90
+ }
91
+ /** A Node script that sends the request from inside the workspace and prints the status and the body, like `curl`. */
92
+ function requestScript(request) {
93
+ const init = {
94
+ method: request.method,
95
+ headers: request.headers,
96
+ body: request.body
97
+ };
98
+ return [
99
+ `const response = await fetch(${JSON.stringify(request.url)}, ${JSON.stringify(init)})`,
100
+ `console.log(response.status + " " + response.statusText)`,
101
+ `console.log(await response.text())`
102
+ ].join("\n");
103
+ }
104
+ //#endregion
105
+ export { dependencyKey, frameworkNodes, parseCurl, requestScript, restartsDevServer, splitTutorialDocument, tutorialStepFiles, tutorialWorkspaceFiles };
@@ -478,7 +478,8 @@ function toggleGroup(pageGroup: DocsSidebarGroup<DocsAppPage>, event: Event) {
478
478
  cursor: pointer;
479
479
  }
480
480
 
481
- /* A folded group: the summary is its heading, and its chevron points right while the group is shut. */
481
+ /* A folded group: the summary is its heading, and its chevron points right while the group is shut. The disclosure effect
482
+ of the motion layer turns the chevron when the group opens or closes. */
482
483
  .vh-docs-sidebar-fold > summary {
483
484
  cursor: pointer;
484
485
  list-style: none;
@@ -490,7 +491,6 @@ function toggleGroup(pageGroup: DocsSidebarGroup<DocsAppPage>, event: Event) {
490
491
 
491
492
  .vh-docs-sidebar-fold-icon {
492
493
  color: var(--ui-text-dimmed);
493
- transition: transform 150ms ease;
494
494
  }
495
495
 
496
496
  .vh-docs-sidebar-fold:not([open]) .vh-docs-sidebar-fold-icon {
@@ -507,12 +507,6 @@ function toggleGroup(pageGroup: DocsSidebarGroup<DocsAppPage>, event: Event) {
507
507
  }
508
508
  }
509
509
 
510
- @media (prefers-reduced-motion: reduce) {
511
- .vh-docs-sidebar-fold-icon {
512
- transition: none;
513
- }
514
- }
515
-
516
510
  /* A section without a listed home page has a title row that opens nothing. */
517
511
  .vh-docs-sidebar-section-title {
518
512
  display: flex;
@@ -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>