@thedatagrid/docs-kit 0.3.0 → 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 (182) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +172 -4
  3. package/dist/code/demoFiles.d.ts.map +1 -1
  4. package/dist/code/demoFiles.js +2 -2
  5. package/dist/code/demoFiles.js.map +1 -1
  6. package/dist/code/index.d.ts +1 -0
  7. package/dist/code/index.d.ts.map +1 -1
  8. package/dist/code/index.js +1 -0
  9. package/dist/code/index.js.map +1 -1
  10. package/dist/code/regions.d.ts +2 -1
  11. package/dist/code/regions.d.ts.map +1 -1
  12. package/dist/code/regions.js +12 -8
  13. package/dist/code/regions.js.map +1 -1
  14. package/dist/code/vueBlocks.d.ts +3 -0
  15. package/dist/code/vueBlocks.d.ts.map +1 -0
  16. package/dist/code/vueBlocks.js +29 -0
  17. package/dist/code/vueBlocks.js.map +1 -0
  18. package/dist/demos/build.d.ts +5 -2
  19. package/dist/demos/build.d.ts.map +1 -1
  20. package/dist/demos/build.js +244 -85
  21. package/dist/demos/build.js.map +1 -1
  22. package/dist/demos/compile/core.d.ts +9 -1
  23. package/dist/demos/compile/core.d.ts.map +1 -1
  24. package/dist/demos/compile/core.js +19 -8
  25. package/dist/demos/compile/core.js.map +1 -1
  26. package/dist/demos/compile/vue.d.ts +107 -0
  27. package/dist/demos/compile/vue.d.ts.map +1 -0
  28. package/dist/demos/compile/vue.js +187 -0
  29. package/dist/demos/compile/vue.js.map +1 -0
  30. package/dist/demos/config.d.ts +41 -7
  31. package/dist/demos/config.d.ts.map +1 -1
  32. package/dist/demos/config.js.map +1 -1
  33. package/dist/demos/index.d.ts +3 -2
  34. package/dist/demos/index.d.ts.map +1 -1
  35. package/dist/demos/index.js +1 -0
  36. package/dist/demos/index.js.map +1 -1
  37. package/dist/demos/pages.d.ts +1 -1
  38. package/dist/demos/pages.d.ts.map +1 -1
  39. package/dist/demos/pages.js +4 -1
  40. package/dist/demos/pages.js.map +1 -1
  41. package/dist/demos/runtime/vue.d.ts +3 -0
  42. package/dist/demos/runtime/vue.d.ts.map +1 -0
  43. package/dist/demos/runtime/vue.js +15 -0
  44. package/dist/demos/runtime/vue.js.map +1 -0
  45. package/dist/demos/vendor.d.ts +5 -1
  46. package/dist/demos/vendor.d.ts.map +1 -1
  47. package/dist/demos/vendor.js +6 -2
  48. package/dist/demos/vendor.js.map +1 -1
  49. package/dist/demos/worker/compile.worker.js +3 -22
  50. package/dist/demos/worker/compile.worker.js.map +1 -1
  51. package/dist/demos/worker/compileVue.worker.d.ts +2 -0
  52. package/dist/demos/worker/compileVue.worker.d.ts.map +1 -0
  53. package/dist/demos/worker/compileVue.worker.js +11 -0
  54. package/dist/demos/worker/compileVue.worker.js.map +1 -0
  55. package/dist/demos/worker/start.d.ts +7 -0
  56. package/dist/demos/worker/start.d.ts.map +1 -0
  57. package/dist/demos/worker/start.js +27 -0
  58. package/dist/demos/worker/start.js.map +1 -0
  59. package/dist/fork/codesandbox.d.ts +19 -1
  60. package/dist/fork/codesandbox.d.ts.map +1 -1
  61. package/dist/fork/codesandbox.js +35 -22
  62. package/dist/fork/codesandbox.js.map +1 -1
  63. package/dist/fork/index.d.ts +30 -0
  64. package/dist/fork/index.d.ts.map +1 -1
  65. package/dist/fork/index.js +37 -0
  66. package/dist/fork/index.js.map +1 -1
  67. package/dist/fork/stackblitz.d.ts +18 -0
  68. package/dist/fork/stackblitz.d.ts.map +1 -0
  69. package/dist/fork/stackblitz.js +98 -0
  70. package/dist/fork/stackblitz.js.map +1 -0
  71. package/dist/frameworks/index.d.ts +4 -0
  72. package/dist/frameworks/index.d.ts.map +1 -0
  73. package/dist/frameworks/index.js +4 -0
  74. package/dist/frameworks/index.js.map +1 -0
  75. package/dist/frameworks/preference.d.ts +10 -0
  76. package/dist/frameworks/preference.d.ts.map +1 -0
  77. package/dist/frameworks/preference.js +34 -0
  78. package/dist/frameworks/preference.js.map +1 -0
  79. package/dist/frameworks/react/FrameworkBanner.d.ts +34 -0
  80. package/dist/frameworks/react/FrameworkBanner.d.ts.map +1 -0
  81. package/dist/frameworks/react/FrameworkBanner.js +50 -0
  82. package/dist/frameworks/react/FrameworkBanner.js.map +1 -0
  83. package/dist/frameworks/react/FrameworkContent.d.ts +21 -0
  84. package/dist/frameworks/react/FrameworkContent.d.ts.map +1 -0
  85. package/dist/frameworks/react/FrameworkContent.js +25 -0
  86. package/dist/frameworks/react/FrameworkContent.js.map +1 -0
  87. package/dist/frameworks/react/FrameworkLinks.d.ts +16 -0
  88. package/dist/frameworks/react/FrameworkLinks.d.ts.map +1 -0
  89. package/dist/frameworks/react/FrameworkLinks.js +50 -0
  90. package/dist/frameworks/react/FrameworkLinks.js.map +1 -0
  91. package/dist/frameworks/react/FrameworkSwitcher.d.ts +27 -0
  92. package/dist/frameworks/react/FrameworkSwitcher.d.ts.map +1 -0
  93. package/dist/frameworks/react/FrameworkSwitcher.js +42 -0
  94. package/dist/frameworks/react/FrameworkSwitcher.js.map +1 -0
  95. package/dist/frameworks/react/index.d.ts +6 -0
  96. package/dist/frameworks/react/index.d.ts.map +1 -0
  97. package/dist/frameworks/react/index.js +6 -0
  98. package/dist/frameworks/react/index.js.map +1 -0
  99. package/dist/frameworks/react/useFrameworkPreference.d.ts +32 -0
  100. package/dist/frameworks/react/useFrameworkPreference.d.ts.map +1 -0
  101. package/dist/frameworks/react/useFrameworkPreference.js +45 -0
  102. package/dist/frameworks/react/useFrameworkPreference.js.map +1 -0
  103. package/dist/frameworks/routeTree.d.ts +24 -0
  104. package/dist/frameworks/routeTree.d.ts.map +1 -0
  105. package/dist/frameworks/routeTree.js +31 -0
  106. package/dist/frameworks/routeTree.js.map +1 -0
  107. package/dist/frameworks/routing.d.ts +105 -0
  108. package/dist/frameworks/routing.d.ts.map +1 -0
  109. package/dist/frameworks/routing.js +142 -0
  110. package/dist/frameworks/routing.js.map +1 -0
  111. package/dist/frameworks/styles.css +104 -0
  112. package/dist/react/Demo.d.ts +12 -0
  113. package/dist/react/Demo.d.ts.map +1 -1
  114. package/dist/react/Demo.js +10 -4
  115. package/dist/react/Demo.js.map +1 -1
  116. package/dist/react/DemoShell.d.ts +5 -1
  117. package/dist/react/DemoShell.d.ts.map +1 -1
  118. package/dist/react/DemoShell.js +9 -6
  119. package/dist/react/DemoShell.js.map +1 -1
  120. package/dist/react/editor.d.ts.map +1 -1
  121. package/dist/react/editor.js +3 -0
  122. package/dist/react/editor.js.map +1 -1
  123. package/dist/react/fork.d.ts +4 -3
  124. package/dist/react/fork.d.ts.map +1 -1
  125. package/dist/react/fork.js +8 -6
  126. package/dist/react/fork.js.map +1 -1
  127. package/dist/react/styles.css +10 -0
  128. package/dist/remark/index.d.ts +2 -0
  129. package/dist/remark/index.d.ts.map +1 -1
  130. package/dist/remark/index.js +2 -0
  131. package/dist/remark/index.js.map +1 -1
  132. package/dist/remark/remarkDemoFences.d.ts +13 -0
  133. package/dist/remark/remarkDemoFences.d.ts.map +1 -1
  134. package/dist/remark/remarkDemoFences.js +48 -4
  135. package/dist/remark/remarkDemoFences.js.map +1 -1
  136. package/dist/remark/remarkFrameworkLinks.d.ts +36 -0
  137. package/dist/remark/remarkFrameworkLinks.d.ts.map +1 -0
  138. package/dist/remark/remarkFrameworkLinks.js +77 -0
  139. package/dist/remark/remarkFrameworkLinks.js.map +1 -0
  140. package/dist/remark/remarkFrameworkText.d.ts +16 -0
  141. package/dist/remark/remarkFrameworkText.d.ts.map +1 -0
  142. package/dist/remark/remarkFrameworkText.js +39 -0
  143. package/dist/remark/remarkFrameworkText.js.map +1 -0
  144. package/package.json +29 -4
  145. package/src/code/demoFiles.ts +2 -2
  146. package/src/code/index.ts +1 -0
  147. package/src/code/regions.ts +14 -8
  148. package/src/code/vueBlocks.ts +25 -0
  149. package/src/demos/build.ts +293 -99
  150. package/src/demos/compile/core.ts +27 -7
  151. package/src/demos/compile/vue.ts +259 -0
  152. package/src/demos/config.ts +59 -7
  153. package/src/demos/index.ts +13 -0
  154. package/src/demos/pages.ts +4 -2
  155. package/src/demos/runtime/vue.ts +17 -0
  156. package/src/demos/vendor.ts +6 -2
  157. package/src/demos/worker/compile.worker.ts +3 -30
  158. package/src/demos/worker/compileVue.worker.ts +13 -0
  159. package/src/demos/worker/start.ts +35 -0
  160. package/src/fork/codesandbox.ts +51 -24
  161. package/src/fork/index.ts +56 -0
  162. package/src/fork/stackblitz.ts +108 -0
  163. package/src/frameworks/index.ts +21 -0
  164. package/src/frameworks/preference.ts +35 -0
  165. package/src/frameworks/react/FrameworkBanner.tsx +112 -0
  166. package/src/frameworks/react/FrameworkContent.tsx +33 -0
  167. package/src/frameworks/react/FrameworkLinks.tsx +52 -0
  168. package/src/frameworks/react/FrameworkSwitcher.tsx +78 -0
  169. package/src/frameworks/react/index.ts +10 -0
  170. package/src/frameworks/react/useFrameworkPreference.ts +91 -0
  171. package/src/frameworks/routeTree.ts +54 -0
  172. package/src/frameworks/routing.ts +194 -0
  173. package/src/frameworks/styles.css +104 -0
  174. package/src/react/Demo.tsx +21 -2
  175. package/src/react/DemoShell.tsx +15 -7
  176. package/src/react/editor.ts +2 -0
  177. package/src/react/fork.ts +14 -6
  178. package/src/react/styles.css +10 -0
  179. package/src/remark/index.ts +6 -0
  180. package/src/remark/remarkDemoFences.ts +58 -3
  181. package/src/remark/remarkFrameworkLinks.ts +96 -0
  182. package/src/remark/remarkFrameworkText.ts +44 -0
@@ -4,8 +4,11 @@
4
4
  *
5
5
  * The demo's files keep their folder structure: they are placed under `src/`
6
6
  * relative to their common ancestor folder, so imports that leave the demo's
7
- * folder (`../shared/data`) still resolve. The entry (`src/index.tsx`) imports
8
- * the demo by its relative path.
7
+ * folder (`../shared/data`) still resolve. The sandbox entry (`src/index.tsx`)
8
+ * imports the demo by its relative path.
9
+ *
10
+ * React demos fork to CodeSandbox (create-react-app + TypeScript, in its
11
+ * browser bundler). Vue demos fork to StackBlitz: see `stackblitz.ts`.
9
12
  */
10
13
  import LZString from 'lz-string';
11
14
 
@@ -29,12 +32,14 @@ export type ForkTemplateOptions = {
29
32
  */
30
33
  dependencies?: Record<string, string>;
31
34
  devDependencies?: Record<string, string>;
32
- /** Top of `src/index.tsx`, e.g. `import '@pkg/index.css';`. */
35
+ /** Top of the entry (`src/index.tsx` / `src/main.ts`), e.g. `import '@pkg/index.css';`. */
33
36
  entryPrelude?: string;
34
37
  /** Appended to `src/styles.css`. */
35
38
  styles?: string;
36
39
  /** Literal replacements applied to every demo file. */
37
40
  sourceReplacements?: Record<string, string>;
41
+ /** HTML put in the `<head>` of the sandbox page (`index.html`), e.g. a `<script src>`. */
42
+ indexHtmlHead?: string;
38
43
  };
39
44
 
40
45
  export type SandboxFiles = Record<string, { content: string | Record<string, unknown> }>;
@@ -58,14 +63,14 @@ export function commonDir(paths: string[]): string {
58
63
  return common.join('/');
59
64
  }
60
65
 
61
- function replaceAll(source: string, replacements: Record<string, string> | undefined): string {
66
+ export function replaceAll(source: string, replacements: Record<string, string> | undefined): string {
62
67
  if (!replacements) return source;
63
68
  let result = source;
64
69
  for (const [search, replacement] of Object.entries(replacements)) result = result.split(search).join(replacement);
65
70
  return result;
66
71
  }
67
72
 
68
- const BASE_STYLES = `html,
73
+ export const BASE_STYLES = `html,
69
74
  body,
70
75
  #root {
71
76
  height: 100%;
@@ -87,29 +92,37 @@ body {
87
92
  }
88
93
  `;
89
94
 
90
- const INDEX_HTML = (title: string) => `<!DOCTYPE html>
95
+ /** `indexHtmlHead`, indented to sit in the page's `<head>`. */
96
+ export const indexHtmlHead = (head: string | undefined) => (head?.trim() ? ` ${head.trim()}\n` : '');
97
+
98
+ const INDEX_HTML = (title: string, head?: string) => `<!DOCTYPE html>
91
99
  <html lang="en">
92
100
  <head>
93
101
  <meta charset="UTF-8" />
94
102
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
95
103
  <title>${title.replace(/</g, '&lt;')}</title>
96
- </head>
104
+ ${indexHtmlHead(head)} </head>
97
105
  <body>
98
106
  <div id="root"></div>
99
107
  </body>
100
108
  </html>
101
109
  `;
102
110
 
103
- /** The sandbox file tree for a React demo (create-react-app + TypeScript). */
104
- export function reactSandboxFiles(files: ForkFile[], options: ForkTemplateOptions): SandboxFiles {
111
+ export type PlacedFiles = {
112
+ /** Path of a demo file inside the sandbox. */
113
+ inSrc(filePath: string): string;
114
+ /** The entry, as imported from a module in `src/` (extension included). */
115
+ entryImport: string;
116
+ /** Every package the files import, at its pinned version or `latest`. */
117
+ imported: Record<string, string>;
118
+ };
119
+
120
+ export function placeFiles(files: ForkFile[], options: ForkTemplateOptions): PlacedFiles {
105
121
  if (!files.some((file) => file.path === options.entry)) {
106
122
  throw new Error(`fork: the entry "${options.entry}" is not one of the files`);
107
123
  }
108
124
  const root = commonDir(files.map((file) => file.path));
109
125
  const inSrc = (filePath: string) => `src/${root ? filePath.slice(root.length + 1) : filePath}`;
110
- const entryInSrc = inSrc(options.entry);
111
- const entryImport = `./${entryInSrc.slice('src/'.length).replace(/\.[cm]?[jt]sx?$/, '')}`;
112
-
113
126
  const imported: Record<string, string> = {};
114
127
  for (const file of files) {
115
128
  for (const specifier of bareImports(file.content)) {
@@ -117,7 +130,27 @@ export function reactSandboxFiles(files: ForkFile[], options: ForkTemplateOption
117
130
  imported[name] = options.dependencies?.[name] ?? 'latest';
118
131
  }
119
132
  }
133
+ return { inSrc, entryImport: `./${inSrc(options.entry).slice('src/'.length)}`, imported };
134
+ }
120
135
 
136
+ function addDemoFiles(sandbox: SandboxFiles, files: ForkFile[], placed: PlacedFiles, options: ForkTemplateOptions) {
137
+ for (const file of files) {
138
+ const target = placed.inSrc(file.path);
139
+ if (sandbox[target]) throw new Error(`fork: "${target}" clashes with a template file`);
140
+ sandbox[target] = { content: replaceAll(file.content, options.sourceReplacements) };
141
+ }
142
+ return sandbox;
143
+ }
144
+
145
+ /** `src/styles.css`: the page layout, then the site's own rules. */
146
+ export const forkStyles = (options: ForkTemplateOptions) =>
147
+ `${BASE_STYLES}${options.styles ? `\n${options.styles}\n` : ''}`;
148
+
149
+ export const forkPrelude = (options: ForkTemplateOptions) => (options.entryPrelude ? `${options.entryPrelude.trim()}\n` : '');
150
+
151
+ /** The sandbox file tree for a React demo (create-react-app + TypeScript). */
152
+ export function reactSandboxFiles(files: ForkFile[], options: ForkTemplateOptions): SandboxFiles {
153
+ const placed = placeFiles(files, options);
121
154
  const sandbox: SandboxFiles = {
122
155
  'package.json': {
123
156
  content: {
@@ -125,7 +158,7 @@ export function reactSandboxFiles(files: ForkFile[], options: ForkTemplateOption
125
158
  description: options.title,
126
159
  main: 'src/index.tsx',
127
160
  dependencies: {
128
- ...imported,
161
+ ...placed.imported,
129
162
  react: '^19.0.0',
130
163
  'react-dom': '^19.0.0',
131
164
  'react-scripts': '^5.0.1',
@@ -141,15 +174,15 @@ export function reactSandboxFiles(files: ForkFile[], options: ForkTemplateOption
141
174
  browserslist: ['>0.2%', 'not dead'],
142
175
  },
143
176
  },
144
- 'public/index.html': { content: INDEX_HTML(options.title) },
177
+ 'public/index.html': { content: INDEX_HTML(options.title, options.indexHtmlHead) },
145
178
  'sandbox.config.json': { content: { infiniteLoopProtection: true } },
146
- 'src/styles.css': { content: `${BASE_STYLES}${options.styles ? `\n${options.styles}\n` : ''}` },
179
+ 'src/styles.css': { content: forkStyles(options) },
147
180
  'src/index.tsx': {
148
181
  content: `import { StrictMode } from 'react';
149
182
  import { createRoot } from 'react-dom/client';
150
- ${options.entryPrelude ? `${options.entryPrelude.trim()}\n` : ''}
183
+ ${forkPrelude(options)}
151
184
  import './styles.css';
152
- import App from ${JSON.stringify(entryImport)};
185
+ import App from ${JSON.stringify(placed.entryImport.replace(/\.[cm]?[jt]sx?$/, ''))};
153
186
 
154
187
  createRoot(document.getElementById('root')!).render(
155
188
  <StrictMode>
@@ -159,13 +192,7 @@ createRoot(document.getElementById('root')!).render(
159
192
  `,
160
193
  },
161
194
  };
162
-
163
- for (const file of files) {
164
- const target = inSrc(file.path);
165
- if (sandbox[target]) throw new Error(`fork: "${target}" clashes with a template file`);
166
- sandbox[target] = { content: replaceAll(file.content, options.sourceReplacements) };
167
- }
168
- return sandbox;
195
+ return addDemoFiles(sandbox, files, placed, options);
169
196
  }
170
197
 
171
198
  /** lz-string base64, URL-safe — the encoding the define API expects. */
package/src/fork/index.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { codeSandboxForm, type ForkFile, type ForkTemplateOptions } from './codesandbox.ts';
2
+ import { stackBlitzForm } from './stackblitz.ts';
3
+
1
4
  export {
2
5
  CODESANDBOX_DEFINE_URL,
3
6
  codeSandboxForm,
@@ -8,3 +11,56 @@ export {
8
11
  type ForkTemplateOptions,
9
12
  type SandboxFiles,
10
13
  } from './codesandbox.ts';
14
+ export { STACKBLITZ_RUN_URL, stackBlitzForm, vueProjectFiles } from './stackblitz.ts';
15
+
16
+ export type ForkFramework = 'react' | 'vue';
17
+
18
+ type ForkTemplateSettings = Pick<
19
+ ForkTemplateOptions,
20
+ 'dependencies' | 'devDependencies' | 'entryPrelude' | 'styles' | 'sourceReplacements' | 'indexHtmlHead'
21
+ >;
22
+
23
+ /** The fork settings of a site (`fork` in docs-kit.config), with its per-demo variants. */
24
+ export type ForkSettings = ForkTemplateSettings & {
25
+ variants?: (ForkTemplateSettings & { match: string })[];
26
+ };
27
+
28
+ const joinBlocks = (...blocks: (string | undefined)[]) =>
29
+ blocks.filter((block) => block?.trim()).join('\n') || undefined;
30
+
31
+ /**
32
+ * The fork settings for one demo: the site's, with every variant whose
33
+ * `match` matches the entry's path applied on top, in order.
34
+ */
35
+ export function resolveForkSettings(settings: ForkSettings, entry: string): ForkTemplateSettings {
36
+ const { variants = [], ...resolved } = settings;
37
+ for (const { match, ...variant } of variants) {
38
+ if (!new RegExp(match).test(entry)) continue;
39
+ resolved.dependencies = { ...resolved.dependencies, ...variant.dependencies };
40
+ resolved.devDependencies = { ...resolved.devDependencies, ...variant.devDependencies };
41
+ resolved.sourceReplacements = { ...resolved.sourceReplacements, ...variant.sourceReplacements };
42
+ resolved.entryPrelude = joinBlocks(resolved.entryPrelude, variant.entryPrelude);
43
+ resolved.styles = joinBlocks(resolved.styles, variant.styles);
44
+ resolved.indexHtmlHead = joinBlocks(resolved.indexHtmlHead, variant.indexHtmlHead);
45
+ }
46
+ return resolved;
47
+ }
48
+
49
+ /** Where a framework's demos fork to. */
50
+ export const FORK_TARGETS: Record<ForkFramework, { id: 'codesandbox' | 'stackblitz'; name: string }> = {
51
+ react: { id: 'codesandbox', name: 'CodeSandbox' },
52
+ vue: { id: 'stackblitz', name: 'StackBlitz' },
53
+ };
54
+
55
+ /**
56
+ * The form that forks a demo: `action` and hidden `fields` for a POST in a
57
+ * new tab. React demos go to CodeSandbox, Vue demos to StackBlitz.
58
+ */
59
+ export function forkForm(
60
+ files: ForkFile[],
61
+ options: ForkTemplateOptions & { framework?: ForkFramework },
62
+ ): { action: string; fields: Record<string, string> } {
63
+ if (options.framework === 'vue') return stackBlitzForm(files, options);
64
+ const form = codeSandboxForm(files, options);
65
+ return { action: form.action, fields: { parameters: form.parameters, query: form.query } };
66
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * StackBlitz fork payloads, for Vue demos: a Vite + Vue + TypeScript project,
3
+ * posted to StackBlitz's `run` endpoint and started in the browser
4
+ * (WebContainers), with no sign-in.
5
+ *
6
+ * Like the CodeSandbox payload, the demo's files keep their folder structure
7
+ * under `src/`, and `src/main.ts` imports the entry by its relative path.
8
+ */
9
+ import {
10
+ forkPrelude,
11
+ forkStyles,
12
+ indexHtmlHead,
13
+ placeFiles,
14
+ replaceAll,
15
+ type ForkFile,
16
+ type ForkTemplateOptions,
17
+ } from './codesandbox.ts';
18
+
19
+ export const STACKBLITZ_RUN_URL = 'https://stackblitz.com/run';
20
+
21
+ const INDEX_HTML = (title: string, head?: string) => `<!DOCTYPE html>
22
+ <html lang="en">
23
+ <head>
24
+ <meta charset="UTF-8" />
25
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
26
+ <title>${title.replace(/</g, '&lt;')}</title>
27
+ ${indexHtmlHead(head)} </head>
28
+ <body>
29
+ <div id="root"></div>
30
+ <script type="module" src="/src/main.ts"></script>
31
+ </body>
32
+ </html>
33
+ `;
34
+
35
+ const json = (value: unknown) => `${JSON.stringify(value, null, 2)}\n`;
36
+
37
+ /** The project's files (path → contents) for a Vue demo: Vite, `@vitejs/plugin-vue`, TypeScript. */
38
+ export function vueProjectFiles(files: ForkFile[], options: ForkTemplateOptions): Record<string, string> {
39
+ const placed = placeFiles(files, options);
40
+ const project: Record<string, string> = {
41
+ 'package.json': json({
42
+ name: 'docs-demo',
43
+ description: options.title,
44
+ private: true,
45
+ type: 'module',
46
+ scripts: { dev: 'vite', build: 'vite build' },
47
+ dependencies: {
48
+ ...placed.imported,
49
+ vue: '^3.5.0',
50
+ ...options.dependencies,
51
+ },
52
+ devDependencies: {
53
+ '@vitejs/plugin-vue': '^6.0.0',
54
+ typescript: '^5.4.0',
55
+ vite: '^8.0.0',
56
+ ...options.devDependencies,
57
+ },
58
+ }),
59
+ 'index.html': INDEX_HTML(options.title, options.indexHtmlHead),
60
+ 'vite.config.ts': `import { defineConfig } from 'vite';
61
+ import vue from '@vitejs/plugin-vue';
62
+
63
+ export default defineConfig({ plugins: [vue()] });
64
+ `,
65
+ 'tsconfig.json': json({
66
+ compilerOptions: {
67
+ target: 'ESNext',
68
+ module: 'ESNext',
69
+ moduleResolution: 'Bundler',
70
+ strict: true,
71
+ jsx: 'preserve',
72
+ jsxImportSource: 'vue',
73
+ skipLibCheck: true,
74
+ lib: ['ESNext', 'DOM', 'DOM.Iterable'],
75
+ },
76
+ include: ['src'],
77
+ }),
78
+ 'src/vite-env.d.ts': '/// <reference types="vite/client" />\n',
79
+ 'src/styles.css': forkStyles(options),
80
+ 'src/main.ts': `import { createApp } from 'vue';
81
+ ${forkPrelude(options)}
82
+ import './styles.css';
83
+ import App from ${JSON.stringify(placed.entryImport)};
84
+
85
+ createApp(App).mount('#root');
86
+ `,
87
+ };
88
+ for (const file of files) {
89
+ const target = placed.inSrc(file.path);
90
+ if (project[target] != null) throw new Error(`fork: "${target}" clashes with a template file`);
91
+ project[target] = replaceAll(file.content, options.sourceReplacements);
92
+ }
93
+ return project;
94
+ }
95
+
96
+ /** Form action and fields for a POST to StackBlitz; the entry file opens in the editor. */
97
+ export function stackBlitzForm(files: ForkFile[], options: ForkTemplateOptions) {
98
+ const project = vueProjectFiles(files, options);
99
+ const entry = placeFiles(files, options).inSrc(options.entry);
100
+ const fields: Record<string, string> = {
101
+ 'project[title]': options.title,
102
+ 'project[description]': options.title,
103
+ // WebContainers: `npm install`, then the `dev` script
104
+ 'project[template]': 'node',
105
+ };
106
+ for (const [filePath, content] of Object.entries(project)) fields[`project[files][${filePath}]`] = content;
107
+ return { action: `${STACKBLITZ_RUN_URL}?file=${encodeURIComponent(entry)}`, fields };
108
+ }
@@ -0,0 +1,21 @@
1
+ export {
2
+ createHasPage,
3
+ defineFrameworks,
4
+ resolveFrameworkLink,
5
+ resolveNavigation,
6
+ resolveSwitchTarget,
7
+ splitHref,
8
+ type FrameworkDefinition,
9
+ type Frameworks,
10
+ type FrameworksConfig,
11
+ type HasPage,
12
+ type ResolvedLink,
13
+ } from './routing.ts';
14
+ export { mapRouteTree, type MapRouteTreeOptions, type RouteNode } from './routeTree.ts';
15
+ export {
16
+ DEFAULT_FRAMEWORK_STORAGE_KEY,
17
+ FRAMEWORK_CHANGE_EVENT,
18
+ frameworkStorageKey,
19
+ readFrameworkPreference,
20
+ writeFrameworkPreference,
21
+ } from './preference.ts';
@@ -0,0 +1,35 @@
1
+ import type { Frameworks } from './routing.ts';
2
+
3
+ /** Fired on `window` when the stored framework changes in this tab. */
4
+ export const FRAMEWORK_CHANGE_EVENT = 'docs-kit:framework';
5
+
6
+ export const DEFAULT_FRAMEWORK_STORAGE_KEY = 'docs-framework';
7
+
8
+ export const frameworkStorageKey = (frameworks: Frameworks) =>
9
+ frameworks.config.storageKey ?? DEFAULT_FRAMEWORK_STORAGE_KEY;
10
+
11
+ /** The visitor's stored choice, or `null` (none, an unknown value, or storage is blocked). */
12
+ export function readFrameworkPreference<Id extends string>(frameworks: Frameworks<Id>): Id | null {
13
+ try {
14
+ const stored = localStorage.getItem(frameworkStorageKey(frameworks));
15
+ return stored != null && frameworks.ids.includes(stored as Id) ? (stored as Id) : null;
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
20
+
21
+ /** Stores the visitor's choice (`null` clears it) and tells the components on the page. */
22
+ export function writeFrameworkPreference<Id extends string>(frameworks: Frameworks<Id>, framework: Id | null) {
23
+ try {
24
+ const key = frameworkStorageKey(frameworks);
25
+ if (framework == null) localStorage.removeItem(key);
26
+ else localStorage.setItem(key, framework);
27
+ } catch {
28
+ // storage blocked: the choice lasts for this page
29
+ }
30
+ try {
31
+ window.dispatchEvent(new CustomEvent(FRAMEWORK_CHANGE_EVENT, { detail: framework }));
32
+ } catch {
33
+ // not in a browser
34
+ }
35
+ }
@@ -0,0 +1,112 @@
1
+ 'use client';
2
+
3
+ import { useEffect, useState, type MouseEvent, type ReactNode } from 'react';
4
+
5
+ import { splitHref } from '../routing.ts';
6
+ import {
7
+ EXPLICIT_LINK_ATTRIBUTE,
8
+ isPlainClick,
9
+ useFrameworkPreference,
10
+ useFrameworks,
11
+ usePagePath,
12
+ type FrameworkProps,
13
+ } from './useFrameworkPreference.ts';
14
+
15
+ export type FrameworkBannerLabels = {
16
+ /** The page exists in the preferred framework. `{preferred}` and `{page}` are framework labels. */
17
+ available?: string;
18
+ /** The link to it. */
19
+ view?: string;
20
+ /** Keeps the page's framework from now on. */
21
+ keep?: string;
22
+ /** The page doesn't exist in the preferred framework. */
23
+ missing?: string;
24
+ dismiss?: string;
25
+ };
26
+
27
+ const DEFAULT_LABELS: Required<FrameworkBannerLabels> = {
28
+ available: 'You are reading the {page} docs.',
29
+ view: 'View this page for {preferred}',
30
+ keep: 'Stay with {page}',
31
+ missing: '{page} only for now: this page is not available for {preferred} yet.',
32
+ dismiss: 'Dismiss',
33
+ };
34
+
35
+ export type FrameworkBannerProps<Id extends string = string> = FrameworkProps<Id> & {
36
+ /** The page's path, from the site's router. Default: `location.pathname`. */
37
+ pathname?: string | null;
38
+ /** Client-side navigation (`router.push`). Default: a normal link. */
39
+ navigate?: (href: string) => void;
40
+ labels?: FrameworkBannerLabels;
41
+ className?: string;
42
+ };
43
+
44
+ const fill = (text: string, values: Record<string, string>) =>
45
+ text.replace(/\{(\w+)\}/g, (match, name: string) => values[name] ?? match);
46
+
47
+ /**
48
+ * Shown on a docs page whose framework is not the one the visitor chose:
49
+ * a shared link, a search result, or a page their framework doesn't have yet.
50
+ * It never redirects, so links stay stable and crawlers see one page per URL.
51
+ *
52
+ * - The page exists in the preferred framework: a link to it, and a way to
53
+ * keep the page's framework from now on.
54
+ * - It doesn't: a notice ("React only for now").
55
+ *
56
+ * Renders nothing without a stored preference, and until hydration.
57
+ */
58
+ export function FrameworkBanner<Id extends string>(props: FrameworkBannerProps<Id>): ReactNode {
59
+ const { navigate, className } = props;
60
+ const labels = { ...DEFAULT_LABELS, ...props.labels };
61
+ const { frameworks, hasPage } = useFrameworks(props);
62
+ const [preference, setPreference] = useFrameworkPreference(frameworks);
63
+ const pathname = usePagePath(props.pathname);
64
+ const [dismissedFor, setDismissedFor] = useState<string | null>(null);
65
+ // a dismissal lasts until the next page
66
+ useEffect(() => setDismissedFor(null), [pathname]);
67
+
68
+ const pageFramework = pathname ? frameworks.frameworkOf(pathname) : null;
69
+ if (!pathname || !preference || !pageFramework || pageFramework === preference || dismissedFor === pathname) {
70
+ return null;
71
+ }
72
+
73
+ const neutral = frameworks.neutralPath(pathname);
74
+ const available = hasPage(splitHref(neutral)[0], preference);
75
+ const href = frameworks.pathFor(neutral, preference);
76
+ const names = { preferred: frameworks.label(preference), page: frameworks.label(pageFramework) };
77
+ const onView = (event: MouseEvent<HTMLAnchorElement>) => {
78
+ if (!navigate || !isPlainClick(event)) return;
79
+ event.preventDefault();
80
+ navigate(href);
81
+ };
82
+
83
+ return (
84
+ <div
85
+ className={`dk-framework-banner${className ? ` ${className}` : ''}`}
86
+ role="status"
87
+ data-framework={preference}
88
+ data-available={available ? 'true' : 'false'}
89
+ >
90
+ <span className="dk-framework-banner-text">{fill(available ? labels.available : labels.missing, names)}</span>
91
+ {available ? (
92
+ <>
93
+ <a className="dk-framework-banner-link" href={href} onClick={onView} {...{ [EXPLICIT_LINK_ATTRIBUTE]: '' }}>
94
+ {fill(labels.view, names)}
95
+ </a>
96
+ <button type="button" className="dk-framework-banner-action" onClick={() => setPreference(pageFramework)}>
97
+ {fill(labels.keep, names)}
98
+ </button>
99
+ </>
100
+ ) : null}
101
+ <button
102
+ type="button"
103
+ className="dk-framework-banner-dismiss"
104
+ aria-label={labels.dismiss}
105
+ title={labels.dismiss}
106
+ onClick={() => setDismissedFor(pathname)}
107
+ >
108
+ ×
109
+ </button>
110
+ </div>
111
+ );
112
+ }
@@ -0,0 +1,33 @@
1
+ import type { ReactNode } from 'react';
2
+
3
+ export type FrameworkContentProps = {
4
+ /** Shown for this framework, or one of a comma-separated list: `framework="vue"`, `framework="react,vue"`. */
5
+ framework?: string | string[];
6
+ /** Shown for every framework but this one (or these). */
7
+ not?: string | string[];
8
+ children?: ReactNode;
9
+ };
10
+
11
+ const asList = (value: string | string[] | undefined) =>
12
+ (Array.isArray(value) ? value : (value ?? '').split(',')).map((item) => item.trim()).filter(Boolean);
13
+
14
+ /**
15
+ * The MDX component for the parts of a page that differ per framework:
16
+ *
17
+ * <FrameworkContent framework="vue">
18
+ * Bind it with `v-model`.
19
+ * </FrameworkContent>
20
+ *
21
+ * Each framework has its own page, so this is decided when the page is
22
+ * built: the other frameworks' blocks aren't in the HTML at all. Create one
23
+ * per page with the framework it is rendered for.
24
+ */
25
+ export function createFrameworkContent(pageFramework: string) {
26
+ return function FrameworkContent(props: FrameworkContentProps): ReactNode {
27
+ const only = asList(props.framework);
28
+ const except = asList(props.not);
29
+ if (only.length && !only.includes(pageFramework)) return null;
30
+ if (except.includes(pageFramework)) return null;
31
+ return <>{props.children}</>;
32
+ };
33
+ }
@@ -0,0 +1,52 @@
1
+ 'use client';
2
+
3
+ import { useEffect } from 'react';
4
+
5
+ import { readFrameworkPreference } from '../preference.ts';
6
+ import { resolveNavigation } from '../routing.ts';
7
+ import { EXPLICIT_LINK_ATTRIBUTE, isPlainClick, useFrameworks, type FrameworkProps } from './useFrameworkPreference.ts';
8
+
9
+ export type FrameworkLinksProps<Id extends string = string> = FrameworkProps<Id> & {
10
+ /** Client-side navigation (`router.push`). Default: `location.assign`. */
11
+ navigate?: (href: string) => void;
12
+ };
13
+
14
+ /**
15
+ * Makes in-site navigation follow the visitor's framework: a click on a docs
16
+ * link of another framework goes to the same page in theirs, when it exists
17
+ * (see `resolveNavigation`). Mount it once, anywhere in the layout; it
18
+ * renders nothing.
19
+ *
20
+ * Only plain left clicks on same-origin links are taken over. Links marked
21
+ * with `data-framework-explicit` (the switcher, the banner) are left alone.
22
+ */
23
+ export function FrameworkLinks<Id extends string>(props: FrameworkLinksProps<Id>) {
24
+ const { navigate } = props;
25
+ const { frameworks, hasPage } = useFrameworks(props);
26
+
27
+ useEffect(() => {
28
+ const onClick = (event: MouseEvent) => {
29
+ if (event.defaultPrevented || !isPlainClick(event)) return;
30
+ const anchor = (event.target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null;
31
+ if (!anchor || anchor.hasAttribute(EXPLICIT_LINK_ATTRIBUTE) || anchor.hasAttribute('download')) return;
32
+ if (anchor.target && anchor.target !== '_self') return;
33
+ if (anchor.origin !== window.location.origin) return;
34
+ const href = resolveNavigation(frameworks, {
35
+ href: `${anchor.pathname}${anchor.search}${anchor.hash}`,
36
+ pagePath: window.location.pathname,
37
+ preference: readFrameworkPreference(frameworks),
38
+ hasPage,
39
+ });
40
+ if (!href) return;
41
+ // before the site's own link handling (a router's click handler on the same element)
42
+ event.preventDefault();
43
+ event.stopPropagation();
44
+ if (navigate) navigate(href);
45
+ else window.location.assign(href);
46
+ };
47
+ document.addEventListener('click', onClick, true);
48
+ return () => document.removeEventListener('click', onClick, true);
49
+ }, [frameworks, hasPage, navigate]);
50
+
51
+ return null;
52
+ }
@@ -0,0 +1,78 @@
1
+ 'use client';
2
+
3
+ import type { MouseEvent } from 'react';
4
+
5
+ import { resolveSwitchTarget } from '../routing.ts';
6
+ import {
7
+ EXPLICIT_LINK_ATTRIBUTE,
8
+ isPlainClick,
9
+ useFrameworkPreference,
10
+ useFrameworks,
11
+ usePagePath,
12
+ type FrameworkProps,
13
+ } from './useFrameworkPreference.ts';
14
+
15
+ export type FrameworkSwitcherProps<Id extends string = string> = FrameworkProps<Id> & {
16
+ /** The page's path, from the site's router. Default: `location.pathname`, after hydration. */
17
+ pathname?: string | null;
18
+ /** Client-side navigation (`router.push`). Default: a normal link. */
19
+ navigate?: (href: string) => void;
20
+ /**
21
+ * Where a framework's option goes from a page outside the framework roots
22
+ * (blog, pricing), e.g. `{ react: '/docs', vue: '/vue' }`. Without it the
23
+ * option only stores the choice there.
24
+ */
25
+ home?: Partial<Record<Id, string>>;
26
+ /** Accessible name of the group. Default `Framework`. */
27
+ label?: string;
28
+ className?: string;
29
+ };
30
+
31
+ /**
32
+ * Picks the docs framework. Each option is a link to the same page in that
33
+ * framework (or the nearest parent that exists there), so it works without
34
+ * JavaScript and for crawlers; clicking it also stores the choice, which the
35
+ * rest of the site follows (`FrameworkLinks`, `FrameworkBanner`).
36
+ *
37
+ * Self-contained, with a minimal look (`frameworks/styles.css`): restyle
38
+ * `.dk-framework-switcher` / `.dk-framework-option`, or the `--dk-*` variables.
39
+ */
40
+ export function FrameworkSwitcher<Id extends string>(props: FrameworkSwitcherProps<Id>) {
41
+ const { navigate, home, label = 'Framework', className } = props;
42
+ const { frameworks, hasPage } = useFrameworks(props);
43
+ const [preference, setPreference] = useFrameworkPreference(frameworks);
44
+ const pathname = usePagePath(props.pathname);
45
+ // on a docs page the URL says which framework is shown; elsewhere the stored choice does
46
+ const current = (pathname ? frameworks.frameworkOf(pathname) : null) ?? preference ?? frameworks.default;
47
+
48
+ return (
49
+ <div className={`dk-framework-switcher${className ? ` ${className}` : ''}`} role="group" aria-label={label}>
50
+ {frameworks.ids.map((id) => {
51
+ const target = pathname ? resolveSwitchTarget(frameworks, pathname, id, hasPage) : null;
52
+ const href = target?.href ?? (pathname && frameworks.frameworkOf(pathname) == null ? home?.[id] : undefined);
53
+ const active = id === current;
54
+ const onClick = (event: MouseEvent<HTMLElement>) => {
55
+ setPreference(id);
56
+ if (!href || !navigate || !isPlainClick(event)) return;
57
+ event.preventDefault();
58
+ if (!active || pathname !== href) navigate(href);
59
+ };
60
+ const shared = {
61
+ className: `dk-framework-option${active ? ' dk-framework-option--active' : ''}`,
62
+ 'data-framework': id,
63
+ 'aria-current': active ? ('true' as const) : undefined,
64
+ onClick,
65
+ };
66
+ return href ? (
67
+ <a key={id} href={href} {...{ [EXPLICIT_LINK_ATTRIBUTE]: '' }} {...shared}>
68
+ {frameworks.label(id)}
69
+ </a>
70
+ ) : (
71
+ <button key={id} type="button" {...shared}>
72
+ {frameworks.label(id)}
73
+ </button>
74
+ );
75
+ })}
76
+ </div>
77
+ );
78
+ }