@thedatagrid/docs-kit 0.2.2 → 0.4.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 (204) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +206 -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 +27 -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/worker/compile.worker.js +3 -22
  46. package/dist/demos/worker/compile.worker.js.map +1 -1
  47. package/dist/demos/worker/compileVue.worker.d.ts +2 -0
  48. package/dist/demos/worker/compileVue.worker.d.ts.map +1 -0
  49. package/dist/demos/worker/compileVue.worker.js +11 -0
  50. package/dist/demos/worker/compileVue.worker.js.map +1 -0
  51. package/dist/demos/worker/start.d.ts +7 -0
  52. package/dist/demos/worker/start.d.ts.map +1 -0
  53. package/dist/demos/worker/start.js +27 -0
  54. package/dist/demos/worker/start.js.map +1 -0
  55. package/dist/fork/codesandbox.d.ts +15 -1
  56. package/dist/fork/codesandbox.d.ts.map +1 -1
  57. package/dist/fork/codesandbox.js +30 -19
  58. package/dist/fork/codesandbox.js.map +1 -1
  59. package/dist/fork/index.d.ts +18 -0
  60. package/dist/fork/index.d.ts.map +1 -1
  61. package/dist/fork/index.js +18 -0
  62. package/dist/fork/index.js.map +1 -1
  63. package/dist/fork/stackblitz.d.ts +18 -0
  64. package/dist/fork/stackblitz.d.ts.map +1 -0
  65. package/dist/fork/stackblitz.js +98 -0
  66. package/dist/fork/stackblitz.js.map +1 -0
  67. package/dist/frameworks/index.d.ts +4 -0
  68. package/dist/frameworks/index.d.ts.map +1 -0
  69. package/dist/frameworks/index.js +4 -0
  70. package/dist/frameworks/index.js.map +1 -0
  71. package/dist/frameworks/preference.d.ts +10 -0
  72. package/dist/frameworks/preference.d.ts.map +1 -0
  73. package/dist/frameworks/preference.js +34 -0
  74. package/dist/frameworks/preference.js.map +1 -0
  75. package/dist/frameworks/react/FrameworkBanner.d.ts +34 -0
  76. package/dist/frameworks/react/FrameworkBanner.d.ts.map +1 -0
  77. package/dist/frameworks/react/FrameworkBanner.js +50 -0
  78. package/dist/frameworks/react/FrameworkBanner.js.map +1 -0
  79. package/dist/frameworks/react/FrameworkContent.d.ts +21 -0
  80. package/dist/frameworks/react/FrameworkContent.d.ts.map +1 -0
  81. package/dist/frameworks/react/FrameworkContent.js +25 -0
  82. package/dist/frameworks/react/FrameworkContent.js.map +1 -0
  83. package/dist/frameworks/react/FrameworkLinks.d.ts +16 -0
  84. package/dist/frameworks/react/FrameworkLinks.d.ts.map +1 -0
  85. package/dist/frameworks/react/FrameworkLinks.js +50 -0
  86. package/dist/frameworks/react/FrameworkLinks.js.map +1 -0
  87. package/dist/frameworks/react/FrameworkSwitcher.d.ts +27 -0
  88. package/dist/frameworks/react/FrameworkSwitcher.d.ts.map +1 -0
  89. package/dist/frameworks/react/FrameworkSwitcher.js +42 -0
  90. package/dist/frameworks/react/FrameworkSwitcher.js.map +1 -0
  91. package/dist/frameworks/react/index.d.ts +6 -0
  92. package/dist/frameworks/react/index.d.ts.map +1 -0
  93. package/dist/frameworks/react/index.js +6 -0
  94. package/dist/frameworks/react/index.js.map +1 -0
  95. package/dist/frameworks/react/useFrameworkPreference.d.ts +32 -0
  96. package/dist/frameworks/react/useFrameworkPreference.d.ts.map +1 -0
  97. package/dist/frameworks/react/useFrameworkPreference.js +45 -0
  98. package/dist/frameworks/react/useFrameworkPreference.js.map +1 -0
  99. package/dist/frameworks/routeTree.d.ts +24 -0
  100. package/dist/frameworks/routeTree.d.ts.map +1 -0
  101. package/dist/frameworks/routeTree.js +31 -0
  102. package/dist/frameworks/routeTree.js.map +1 -0
  103. package/dist/frameworks/routing.d.ts +105 -0
  104. package/dist/frameworks/routing.d.ts.map +1 -0
  105. package/dist/frameworks/routing.js +142 -0
  106. package/dist/frameworks/routing.js.map +1 -0
  107. package/dist/frameworks/styles.css +104 -0
  108. package/dist/react/Demo.d.ts +12 -0
  109. package/dist/react/Demo.d.ts.map +1 -1
  110. package/dist/react/Demo.js +10 -4
  111. package/dist/react/Demo.js.map +1 -1
  112. package/dist/react/DemoShell.d.ts +5 -1
  113. package/dist/react/DemoShell.d.ts.map +1 -1
  114. package/dist/react/DemoShell.js +9 -6
  115. package/dist/react/DemoShell.js.map +1 -1
  116. package/dist/react/editor.d.ts.map +1 -1
  117. package/dist/react/editor.js +3 -0
  118. package/dist/react/editor.js.map +1 -1
  119. package/dist/react/fork.d.ts +4 -3
  120. package/dist/react/fork.d.ts.map +1 -1
  121. package/dist/react/fork.js +6 -5
  122. package/dist/react/fork.js.map +1 -1
  123. package/dist/react/styles.css +10 -0
  124. package/dist/remark/index.d.ts +2 -0
  125. package/dist/remark/index.d.ts.map +1 -1
  126. package/dist/remark/index.js +2 -0
  127. package/dist/remark/index.js.map +1 -1
  128. package/dist/remark/remarkDemoFences.d.ts +13 -0
  129. package/dist/remark/remarkDemoFences.d.ts.map +1 -1
  130. package/dist/remark/remarkDemoFences.js +48 -4
  131. package/dist/remark/remarkDemoFences.js.map +1 -1
  132. package/dist/remark/remarkFrameworkLinks.d.ts +36 -0
  133. package/dist/remark/remarkFrameworkLinks.d.ts.map +1 -0
  134. package/dist/remark/remarkFrameworkLinks.js +77 -0
  135. package/dist/remark/remarkFrameworkLinks.js.map +1 -0
  136. package/dist/remark/remarkFrameworkText.d.ts +16 -0
  137. package/dist/remark/remarkFrameworkText.d.ts.map +1 -0
  138. package/dist/remark/remarkFrameworkText.js +39 -0
  139. package/dist/remark/remarkFrameworkText.js.map +1 -0
  140. package/dist/showcase/AutomatedDemo.d.ts +46 -0
  141. package/dist/showcase/AutomatedDemo.d.ts.map +1 -0
  142. package/dist/showcase/AutomatedDemo.js +169 -0
  143. package/dist/showcase/AutomatedDemo.js.map +1 -0
  144. package/dist/showcase/LazyShowcase.d.ts +31 -0
  145. package/dist/showcase/LazyShowcase.d.ts.map +1 -0
  146. package/dist/showcase/LazyShowcase.js +51 -0
  147. package/dist/showcase/LazyShowcase.js.map +1 -0
  148. package/dist/showcase/hooks.d.ts +19 -0
  149. package/dist/showcase/hooks.d.ts.map +1 -0
  150. package/dist/showcase/hooks.js +63 -0
  151. package/dist/showcase/hooks.js.map +1 -0
  152. package/dist/showcase/index.d.ts +17 -0
  153. package/dist/showcase/index.d.ts.map +1 -0
  154. package/dist/showcase/index.js +15 -0
  155. package/dist/showcase/index.js.map +1 -0
  156. package/dist/showcase/scripted.d.ts +100 -0
  157. package/dist/showcase/scripted.d.ts.map +1 -0
  158. package/dist/showcase/scripted.js +381 -0
  159. package/dist/showcase/scripted.js.map +1 -0
  160. package/dist/showcase/styles.css +174 -0
  161. package/package.json +34 -4
  162. package/src/code/demoFiles.ts +2 -2
  163. package/src/code/index.ts +1 -0
  164. package/src/code/regions.ts +14 -8
  165. package/src/code/vueBlocks.ts +25 -0
  166. package/src/demos/build.ts +293 -99
  167. package/src/demos/compile/core.ts +27 -7
  168. package/src/demos/compile/vue.ts +259 -0
  169. package/src/demos/config.ts +44 -7
  170. package/src/demos/index.ts +13 -0
  171. package/src/demos/pages.ts +4 -2
  172. package/src/demos/runtime/vue.ts +17 -0
  173. package/src/demos/worker/compile.worker.ts +3 -30
  174. package/src/demos/worker/compileVue.worker.ts +13 -0
  175. package/src/demos/worker/start.ts +35 -0
  176. package/src/fork/codesandbox.ts +43 -21
  177. package/src/fork/index.ts +25 -0
  178. package/src/fork/stackblitz.ts +107 -0
  179. package/src/frameworks/index.ts +21 -0
  180. package/src/frameworks/preference.ts +35 -0
  181. package/src/frameworks/react/FrameworkBanner.tsx +112 -0
  182. package/src/frameworks/react/FrameworkContent.tsx +33 -0
  183. package/src/frameworks/react/FrameworkLinks.tsx +52 -0
  184. package/src/frameworks/react/FrameworkSwitcher.tsx +78 -0
  185. package/src/frameworks/react/index.ts +10 -0
  186. package/src/frameworks/react/useFrameworkPreference.ts +91 -0
  187. package/src/frameworks/routeTree.ts +54 -0
  188. package/src/frameworks/routing.ts +194 -0
  189. package/src/frameworks/styles.css +104 -0
  190. package/src/react/Demo.tsx +21 -2
  191. package/src/react/DemoShell.tsx +15 -7
  192. package/src/react/editor.ts +2 -0
  193. package/src/react/fork.ts +12 -5
  194. package/src/react/styles.css +10 -0
  195. package/src/remark/index.ts +6 -0
  196. package/src/remark/remarkDemoFences.ts +58 -3
  197. package/src/remark/remarkFrameworkLinks.ts +96 -0
  198. package/src/remark/remarkFrameworkText.ts +44 -0
  199. package/src/showcase/AutomatedDemo.tsx +266 -0
  200. package/src/showcase/LazyShowcase.tsx +111 -0
  201. package/src/showcase/hooks.ts +84 -0
  202. package/src/showcase/index.ts +23 -0
  203. package/src/showcase/scripted.ts +533 -0
  204. package/src/showcase/styles.css +174 -0
@@ -7,6 +7,7 @@ import { formatHighlightSpec } from '../code/highlightSpec.ts';
7
7
  import { parseDemoHeight } from '../code/heights.ts';
8
8
  import { formatLineRanges } from '../code/lineRanges.ts';
9
9
  import { applySourceReplacements, extractCodeMarkers, sliceRegion, stripCodeMarkers } from '../code/regions.ts';
10
+ import { vueBlockLang } from '../code/vueBlocks.ts';
10
11
  import { applyFenceDefaults, parseFenceMeta, type FenceDefaults, type FenceProps } from './meta.ts';
11
12
 
12
13
  export type FenceInfo = {
@@ -62,8 +63,30 @@ export type RemarkDemoFencesOptions = {
62
63
  fenceDefaults?: FenceDefaults;
63
64
  /** `height` of a live fence that sets none (and no `fenceDefaults.demos.height`). Default `auto`. */
64
65
  liveHeight?: string;
66
+ /**
67
+ * For a page rendered in another framework than the one its fences name:
68
+ * `foo.demo.tsx` → the sibling `foo.demo.vue`. Maps the suffix a fence
69
+ * names to the sibling suffixes to try, in order, e.g.
70
+ * `{ '.demo.tsx': '.demo.vue', '.snippet.tsx': ['.snippet.vue', '.snippet.vue.ts'] }`.
71
+ *
72
+ * A fence with a sibling shows it (the sibling suffixes of demo entries
73
+ * count as demo suffixes). One without keeps its file and is marked as a
74
+ * fallback: `<Demo fallback="true">`, which shows the page's notice
75
+ * ("React only for now"). A fence whose code is the same for every
76
+ * framework opts out with `neutral`.
77
+ */
78
+ siblings?: Record<string, string | string[]>;
65
79
  };
66
80
 
81
+ const asList = (value: string | string[]) => (Array.isArray(value) ? value : [value]);
82
+
83
+ /** Shiki language of a sibling file; a region of a `.vue` file is highlighted as its block. */
84
+ function siblingLang(file: string, source: string, firstLine: number | undefined): string | null {
85
+ if (/\.vue$/.test(file)) return firstLine == null ? 'vue' : vueBlockLang(source, firstLine);
86
+ const ext = /\.([cm]?[jt]sx?)$/.exec(file)?.[1];
87
+ return ext ? ext.replace(/^[cm]/, '') : null;
88
+ }
89
+
67
90
  const TYPECHECKED_LANGS = new Set(['ts', 'tsx', 'js', 'jsx', 'typescript', 'javascript']);
68
91
 
69
92
  type MdxAttribute = { type: 'mdxJsxAttribute'; name: string; value: string };
@@ -126,7 +149,12 @@ export function remarkDemoFences(options: RemarkDemoFencesOptions) {
126
149
  sourceReplacements,
127
150
  fenceDefaults,
128
151
  liveHeight = 'auto',
152
+ siblings,
129
153
  } = options;
154
+ const liveSuffixes = [...demoSuffixes];
155
+ for (const suffix of demoSuffixes) {
156
+ for (const sibling of asList(siblings?.[suffix] ?? [])) if (!liveSuffixes.includes(sibling)) liveSuffixes.push(sibling);
157
+ }
130
158
  const folder = options.folder.replace(/^\/+|\/+$/g, '');
131
159
  const pageDir = path.join(contentDir, folder);
132
160
  /** `/docs/x.tsx` is relative to the content root, anything else to the page. */
@@ -158,6 +186,27 @@ export function remarkDemoFences(options: RemarkDemoFencesOptions) {
158
186
  );
159
187
  }
160
188
 
189
+ // the page's framework: show the sibling file, or mark the fence as a fallback
190
+ let fallback = false;
191
+ let isSibling = false;
192
+ const named = props.file;
193
+ const siblingOf = typeof named === 'string' && siblings && !props.neutral
194
+ ? Object.keys(siblings).find((suffix) => named.endsWith(suffix))
195
+ : undefined;
196
+ if (typeof named === 'string' && siblingOf) {
197
+ const stem = named.slice(0, -siblingOf.length);
198
+ const found = asList(siblings![siblingOf]).find((suffix) => {
199
+ const candidate = resolveFile(stem + suffix);
200
+ return fs.existsSync(candidate) && fs.statSync(candidate).isFile();
201
+ });
202
+ if (found) {
203
+ props.file = stem + found;
204
+ isSibling = true;
205
+ } else {
206
+ fallback = true;
207
+ }
208
+ }
209
+
161
210
  const file = props.file;
162
211
  if (props.live && !('height' in props)) props.height = liveHeight;
163
212
  if ('range' in props) {
@@ -196,12 +245,16 @@ export function remarkDemoFences(options: RemarkDemoFencesOptions) {
196
245
  }
197
246
 
198
247
  let originalLines: number[] | undefined;
248
+ const fullSource = source;
199
249
  if (typeof props.region === 'string') {
200
250
  if (typeof file !== 'string') throw new Error(`${context}: \`region\` requires \`file="..."\``);
201
251
  const sliced = sliceRegion(source, props.region, context);
202
252
  source = sliced.source;
203
253
  originalLines = sliced.originalLines;
204
254
  }
255
+ if (isSibling && typeof file === 'string') {
256
+ node.lang = siblingLang(file, fullSource, originalLines?.[0]) ?? node.lang;
257
+ }
205
258
 
206
259
  // Live demos strip markers per file in <Demo>.
207
260
  let highlight: string | null = null;
@@ -224,11 +277,11 @@ export function remarkDemoFences(options: RemarkDemoFencesOptions) {
224
277
  `\`live=off\` (preview available, code shown first)`,
225
278
  );
226
279
  }
227
- const suffix = typeof file === 'string' ? demoSuffixes.find((s) => file.endsWith(s)) : undefined;
280
+ const suffix = typeof file === 'string' ? liveSuffixes.find((s) => file.endsWith(s)) : undefined;
228
281
  const fromRoot = typeof file === 'string' ? path.relative(contentDir, resolveFile(file)) : '..';
229
282
  if (typeof file !== 'string' || !suffix || fromRoot.startsWith('..') || path.isAbsolute(fromRoot)) {
230
283
  throw new Error(
231
- `${context}: live demos must reference a ${demoSuffixes.map((s) => `*${s}`).join(' / ')} ` +
284
+ `${context}: live demos must reference a ${liveSuffixes.map((s) => `*${s}`).join(' / ')} ` +
232
285
  `file inside the content folder (it has to match a prebuilt demo bundle)`,
233
286
  );
234
287
  }
@@ -243,6 +296,7 @@ export function remarkDemoFences(options: RemarkDemoFencesOptions) {
243
296
  else if (typeof props.title === 'string') attrs.title = props.title;
244
297
  if (props.lines) attrs.lines = 'true';
245
298
  if (props.edit === 'off') attrs.editable = 'false';
299
+ if (fallback) attrs.fallback = 'true';
246
300
 
247
301
  if (inDemo) {
248
302
  assertSingleSnippet(parent, context);
@@ -263,6 +317,7 @@ export function remarkDemoFences(options: RemarkDemoFencesOptions) {
263
317
  if (highlight) attrs.highlight = highlight;
264
318
  if (props.lines) attrs.lines = 'true';
265
319
  if (originalLinesAttr) attrs.originalLines = originalLinesAttr;
320
+ if (fallback) attrs.fallback = 'true';
266
321
  return attrs;
267
322
  };
268
323
 
@@ -300,7 +355,7 @@ export function remarkDemoFences(options: RemarkDemoFencesOptions) {
300
355
  ]
301
356
  .filter(Boolean)
302
357
  .join(' ') || null;
303
- node.data = { ...node.data, docsKit: true };
358
+ node.data = { ...node.data, docsKit: true, ...(fallback ? { docsKitFallback: true } : null) };
304
359
  });
305
360
  };
306
361
  }
@@ -0,0 +1,96 @@
1
+ import { visit } from 'unist-util-visit';
2
+
3
+ import { resolveFrameworkLink, splitHref, type Frameworks, type HasPage } from '../frameworks/routing.ts';
4
+
5
+ export type RemarkFrameworkLinksOptions<Id extends string = string> = {
6
+ frameworks: Frameworks<Id>;
7
+ /** The framework the page is rendered for. */
8
+ framework: Id;
9
+ hasPage: HasPage<Id>;
10
+ /**
11
+ * Internal links outside the framework roots (`/pricing`, `/blog/x`,
12
+ * `/logo.svg`): return `false` to fail the build. Default: accepted.
13
+ */
14
+ isValidSharedLink?: (pathname: string) => boolean;
15
+ /**
16
+ * JSX attributes that hold links, by component: `{ Card: ['path'] }`. A
17
+ * fallback sets `frameworkFallback="<framework>"` on the element.
18
+ */
19
+ jsxAttributes?: Record<string, string[]>;
20
+ /** The page's file, for error messages. */
21
+ file?: string;
22
+ };
23
+
24
+ /** The attribute a fallback link carries: the framework it goes to instead. */
25
+ export const FALLBACK_LINK_ATTRIBUTE = 'data-framework-fallback';
26
+
27
+ /**
28
+ * Links in the docs are written once, in the default framework's form
29
+ * (`/docs/learn/sorting`). This plugin points them at the page's framework:
30
+ *
31
+ * - the page exists there: `/vue/docs/learn/sorting`;
32
+ * - it doesn't: the link goes to a framework that has it and is marked with
33
+ * `data-framework-fallback="react"`, so the site can show a badge
34
+ * ("React only for now");
35
+ * - no framework has it: the build fails.
36
+ *
37
+ * Covers markdown links, link definitions and the configured JSX attributes.
38
+ * External links and `#hash` links are left alone.
39
+ */
40
+ export function remarkFrameworkLinks<Id extends string>(options: RemarkFrameworkLinksOptions<Id>) {
41
+ const { frameworks, framework, hasPage, isValidSharedLink, jsxAttributes = {}, file } = options;
42
+ const where = file ? `, found in ${file}` : '';
43
+
44
+ /** The rewritten URL and, for a fallback, its framework. `null`: not an internal link. */
45
+ const resolve = (url: unknown): { url: string; fallback: Id | null } | null => {
46
+ if (typeof url !== 'string' || !url.startsWith('/') || url.startsWith('//')) return null;
47
+ const link = resolveFrameworkLink(frameworks, url, framework, hasPage);
48
+ switch (link.kind) {
49
+ case 'shared':
50
+ if (isValidSharedLink && !isValidSharedLink(splitHref(url)[0])) {
51
+ throw new Error(`Link not valid: "${url}"${where}.`);
52
+ }
53
+ return null;
54
+ case 'page':
55
+ return { url: link.href, fallback: null };
56
+ case 'fallback':
57
+ return { url: link.href, fallback: link.framework };
58
+ case 'missing':
59
+ throw new Error(
60
+ `Link not valid: "${url}"${where}: no page at "${link.neutralPath}" in any framework ` +
61
+ `(${frameworks.ids.join(', ')}).`,
62
+ );
63
+ }
64
+ };
65
+
66
+ return () => (tree: any) => {
67
+ visit(tree, (node: any) => {
68
+ if (node.type === 'link' || node.type === 'definition') {
69
+ const resolved = resolve(node.url);
70
+ if (!resolved) return;
71
+ node.url = resolved.url;
72
+ if (resolved.fallback && node.type === 'link') {
73
+ node.data = {
74
+ ...node.data,
75
+ hProperties: { ...node.data?.hProperties, [FALLBACK_LINK_ATTRIBUTE]: resolved.fallback },
76
+ };
77
+ }
78
+ return;
79
+ }
80
+ if (node.type !== 'mdxJsxFlowElement' && node.type !== 'mdxJsxTextElement') return;
81
+ const names = node.name ? jsxAttributes[node.name] : undefined;
82
+ if (!names) return;
83
+ let fallback: Id | null = null;
84
+ for (const attribute of node.attributes ?? []) {
85
+ if (attribute.type !== 'mdxJsxAttribute' || !names.includes(attribute.name)) continue;
86
+ const resolved = resolve(attribute.value);
87
+ if (!resolved) continue;
88
+ attribute.value = resolved.url;
89
+ fallback ??= resolved.fallback;
90
+ }
91
+ if (fallback && !node.attributes.some((attribute: any) => attribute.name === 'frameworkFallback')) {
92
+ node.attributes.push({ type: 'mdxJsxAttribute', name: 'frameworkFallback', value: fallback });
93
+ }
94
+ });
95
+ };
96
+ }
@@ -0,0 +1,44 @@
1
+ import { visit } from 'unist-util-visit';
2
+
3
+ export type RemarkFrameworkTextOptions = {
4
+ /**
5
+ * Literal replacements for a page rendered in another framework than it
6
+ * was written for, e.g. `{ '@acme/grid-react': '@acme/grid-vue' }`.
7
+ */
8
+ replacements: Record<string, string>;
9
+ };
10
+
11
+ /**
12
+ * Applies literal replacements to a page's prose: text, inline code, fenced
13
+ * code written in the page, and link URLs. The package name in
14
+ * `npm i @acme/grid-react` is right on the Vue page without a second copy of
15
+ * the sentence. Fences that show a file (`file="…"`) are left alone: their
16
+ * code comes from that file, or its sibling.
17
+ */
18
+ export function remarkFrameworkText(options: RemarkFrameworkTextOptions) {
19
+ const pairs = Object.entries(options.replacements).filter(([search]) => search);
20
+ const replace = (value: string) => {
21
+ let result = value;
22
+ for (const [search, replacement] of pairs) result = result.split(search).join(replacement);
23
+ return result;
24
+ };
25
+
26
+ return () => (tree: any) => {
27
+ if (!pairs.length) return;
28
+ visit(tree, (node: any) => {
29
+ switch (node.type) {
30
+ case 'text':
31
+ case 'inlineCode':
32
+ node.value = replace(node.value);
33
+ break;
34
+ case 'code':
35
+ if (!/\bfile=/.test(node.meta ?? '')) node.value = replace(node.value);
36
+ break;
37
+ case 'link':
38
+ case 'definition':
39
+ if (typeof node.url === 'string') node.url = replace(node.url);
40
+ break;
41
+ }
42
+ });
43
+ };
44
+ }
@@ -0,0 +1,266 @@
1
+ 'use client';
2
+
3
+ import {
4
+ useCallback,
5
+ useEffect,
6
+ useRef,
7
+ useState,
8
+ type CSSProperties,
9
+ type ReactNode,
10
+ } from 'react';
11
+
12
+ import { canRunScriptedShow } from './hooks.ts';
13
+ import {
14
+ createScriptedCursor,
15
+ ScriptCancelled,
16
+ sleep,
17
+ waitFor,
18
+ type ScriptedCursor,
19
+ } from './scripted.ts';
20
+
21
+ export type AutomatedDemoStatus =
22
+ /** Not animating: offscreen, before ready, or unsupported device. */
23
+ | 'idle'
24
+ /** The show is running (fake cursor visible). */
25
+ | 'running'
26
+ /** The user interacted — the demo is theirs until they hit replay. */
27
+ | 'user';
28
+
29
+ export type ShowcaseScriptContext = {
30
+ /** Wrapper element containing the live demo (and its in-demo portals). */
31
+ root: HTMLElement;
32
+ cursor: ScriptedCursor;
33
+ signal: AbortSignal;
34
+ };
35
+
36
+ export type AutomatedDemoProps = {
37
+ children: ReactNode;
38
+ /** The product demo is mounted and can be driven. */
39
+ ready: boolean;
40
+ /** One full pass of the show. Must honour `signal` (use the toolkit helpers). */
41
+ run: (context: ShowcaseScriptContext) => Promise<void>;
42
+ /** Put the demo back to its initial state; called before every pass. */
43
+ reset?: (context: ShowcaseScriptContext) => void | Promise<void>;
44
+ /** Wait for this selector inside the root before the first pass. */
45
+ waitForSelector?: string;
46
+ /** Pause between passes, in ms. */
47
+ loopPause?: number;
48
+ /** No show below this viewport width (and never on touch / reduced motion). */
49
+ minViewportWidth?: number;
50
+ /** IntersectionObserver threshold for "in view". */
51
+ threshold?: number;
52
+ runningLabel?: ReactNode;
53
+ userLabel?: ReactNode;
54
+ className?: string;
55
+ style?: CSSProperties;
56
+ onStatusChange?: (status: AutomatedDemoStatus) => void;
57
+ };
58
+
59
+ /**
60
+ * Wraps a live demo in an automated show: a scripted cursor drives the LIVE
61
+ * component while it's in view, and the first real interaction (click /
62
+ * wheel / touch / key) hands control to the user instantly, leaving the demo
63
+ * where the script left it. A broken script ends quietly — it must never
64
+ * break the page.
65
+ */
66
+ export function AutomatedDemo({
67
+ children,
68
+ ready,
69
+ run,
70
+ reset,
71
+ waitForSelector,
72
+ loopPause = 2600,
73
+ minViewportWidth = 768,
74
+ threshold = 0.35,
75
+ runningLabel = 'live demo — click anywhere to take over',
76
+ userLabel = 'you’re in control — replay demo ↻',
77
+ className,
78
+ style,
79
+ onStatusChange,
80
+ }: AutomatedDemoProps) {
81
+ const wrapperRef = useRef<HTMLDivElement | null>(null);
82
+ const overlayRef = useRef<HTMLDivElement | null>(null);
83
+ const cursorRef = useRef<ScriptedCursor | null>(null);
84
+ const abortRef = useRef<AbortController | null>(null);
85
+ const intersectingRef = useRef(false);
86
+ const readyRef = useRef(ready);
87
+ const statusRef = useRef<AutomatedDemoStatus>('idle');
88
+ const [status, setStatusState] = useState<AutomatedDemoStatus>('idle');
89
+
90
+ // latest callbacks without restarting the observers
91
+ const runRef = useRef(run);
92
+ const resetRef = useRef(reset);
93
+ const onStatusChangeRef = useRef(onStatusChange);
94
+ runRef.current = run;
95
+ resetRef.current = reset;
96
+ onStatusChangeRef.current = onStatusChange;
97
+
98
+ const setStatus = useCallback((next: AutomatedDemoStatus) => {
99
+ statusRef.current = next;
100
+ setStatusState(next);
101
+ onStatusChangeRef.current?.(next);
102
+ }, []);
103
+
104
+ const stop = useCallback(
105
+ (next: AutomatedDemoStatus) => {
106
+ abortRef.current?.abort();
107
+ abortRef.current = null;
108
+ cursorRef.current?.hide();
109
+ setStatus(next);
110
+ },
111
+ [setStatus],
112
+ );
113
+
114
+ const tryStart = useCallback(() => {
115
+ if (statusRef.current !== 'idle') return;
116
+ if (!intersectingRef.current || !readyRef.current) return;
117
+ if (document.visibilityState === 'hidden') return;
118
+ const root = wrapperRef.current;
119
+ const overlay = overlayRef.current;
120
+ if (!root || !overlay) return;
121
+ // the show is pointless (and annoying) on touch / small / reduced-motion
122
+ if (!canRunScriptedShow(minViewportWidth)) return;
123
+
124
+ if (!cursorRef.current) cursorRef.current = createScriptedCursor(overlay);
125
+ const cursor = cursorRef.current;
126
+ const controller = new AbortController();
127
+ abortRef.current = controller;
128
+ setStatus('running');
129
+
130
+ void (async () => {
131
+ const { signal } = controller;
132
+ const context: ShowcaseScriptContext = { root, cursor, signal };
133
+ try {
134
+ if (waitForSelector) {
135
+ const found = await waitFor(
136
+ () => root.querySelector(waitForSelector),
137
+ signal,
138
+ {
139
+ timeout: 20000,
140
+ },
141
+ );
142
+ if (!found) throw new ScriptCancelled();
143
+ }
144
+ for (;;) {
145
+ await resetRef.current?.(context);
146
+ await sleep(700, signal);
147
+ await runRef.current(context);
148
+ cursor.hide();
149
+ await sleep(loopPause, signal);
150
+ }
151
+ } catch (error) {
152
+ cursor.hide();
153
+ if (!(error instanceof ScriptCancelled)) {
154
+ // a broken show must never break the page — just end it quietly
155
+ console.warn('[automated-demo]', error);
156
+ if (statusRef.current === 'running') stop('user');
157
+ }
158
+ }
159
+ })();
160
+ }, [loopPause, minViewportWidth, setStatus, stop, waitForSelector]);
161
+
162
+ useEffect(() => {
163
+ readyRef.current = ready;
164
+ if (ready) tryStart();
165
+ else if (statusRef.current === 'running') stop('idle');
166
+ }, [ready, tryStart, stop]);
167
+
168
+ // start/pause with viewport visibility
169
+ useEffect(() => {
170
+ const root = wrapperRef.current;
171
+ if (!root) return;
172
+ const observer = new IntersectionObserver(
173
+ (entries) => {
174
+ const isIntersecting = entries.some((entry) => entry.isIntersecting);
175
+ intersectingRef.current = isIntersecting;
176
+ if (isIntersecting) tryStart();
177
+ else if (statusRef.current === 'running') stop('idle');
178
+ },
179
+ { threshold },
180
+ );
181
+ observer.observe(root);
182
+ return () => observer.disconnect();
183
+ }, [threshold, tryStart, stop]);
184
+
185
+ // a hidden tab is as good as off-screen
186
+ useEffect(() => {
187
+ const onVisibility = () => {
188
+ if (document.visibilityState === 'hidden') {
189
+ if (statusRef.current === 'running') stop('idle');
190
+ } else {
191
+ tryStart();
192
+ }
193
+ };
194
+ document.addEventListener('visibilitychange', onVisibility);
195
+ return () => document.removeEventListener('visibilitychange', onVisibility);
196
+ }, [tryStart, stop]);
197
+
198
+ // first REAL interaction anywhere on the demo = takeover. The script's own
199
+ // dispatched events are untrusted, which is how we tell them apart.
200
+ useEffect(() => {
201
+ const root = wrapperRef.current;
202
+ if (!root) return;
203
+ const onInteract = (event: Event) => {
204
+ if (!event.isTrusted) return;
205
+ if (statusRef.current === 'running') stop('user');
206
+ // touched before the show got going: don't start it under the user
207
+ else if (
208
+ statusRef.current === 'idle' &&
209
+ canRunScriptedShow(minViewportWidth)
210
+ ) {
211
+ stop('user');
212
+ }
213
+ };
214
+ const events = ['pointerdown', 'wheel', 'touchstart', 'keydown'] as const;
215
+ for (const type of events) {
216
+ root.addEventListener(type, onInteract, { capture: true, passive: true });
217
+ }
218
+ return () => {
219
+ for (const type of events)
220
+ root.removeEventListener(type, onInteract, { capture: true });
221
+ };
222
+ }, [stop, minViewportWidth]);
223
+
224
+ useEffect(() => {
225
+ return () => {
226
+ abortRef.current?.abort();
227
+ cursorRef.current?.destroy();
228
+ cursorRef.current = null;
229
+ };
230
+ }, []);
231
+
232
+ const replay = useCallback(() => {
233
+ if (statusRef.current === 'running') return;
234
+ setStatus('idle');
235
+ // let the status flip settle before the loop re-checks it
236
+ requestAnimationFrame(() => tryStart());
237
+ }, [setStatus, tryStart]);
238
+
239
+ return (
240
+ <div
241
+ ref={wrapperRef}
242
+ className={['showcase-demo', className].filter(Boolean).join(' ')}
243
+ data-showcase-status={status}
244
+ style={style}
245
+ >
246
+ {children}
247
+ {/* cursor layer: above the demo AND its in-demo popups, but transparent to input */}
248
+ <div ref={overlayRef} aria-hidden className="showcase-demo__overlay" />
249
+ {status === 'running' ? (
250
+ <div className="showcase-pill showcase-pill--running" role="status">
251
+ <span className="showcase-pill__dot" />
252
+ {runningLabel}
253
+ </div>
254
+ ) : null}
255
+ {status === 'user' ? (
256
+ <button
257
+ type="button"
258
+ onClick={replay}
259
+ className="showcase-pill showcase-pill--user"
260
+ >
261
+ {userLabel}
262
+ </button>
263
+ ) : null}
264
+ </div>
265
+ );
266
+ }
@@ -0,0 +1,111 @@
1
+ 'use client';
2
+
3
+ import {
4
+ useEffect,
5
+ useRef,
6
+ useState,
7
+ type ComponentType,
8
+ type CSSProperties,
9
+ type ReactNode,
10
+ } from 'react';
11
+
12
+ import { whenIdle } from './hooks.ts';
13
+
14
+ export type LazyShowcaseLoadedProps = {
15
+ /** Call once the live demo has painted its real content. */
16
+ onReady?: () => void;
17
+ };
18
+
19
+ export type LazyShowcaseProps<P extends object> = {
20
+ /** Dynamic import of the live demo, e.g. `() => import('./HeroDemo')`. */
21
+ load: () => Promise<{ default: ComponentType<P & LazyShowcaseLoadedProps> }>;
22
+ props: P;
23
+ /** Static first paint (an <img> screenshot, a skeleton…). Fades out once live. */
24
+ poster: ReactNode;
25
+ /**
26
+ * Fixed height, so swapping poster → live never shifts layout. Omit it when
27
+ * `className` sets a (responsive) height instead.
28
+ */
29
+ height?: number | string;
30
+ /** Start loading this far before the container scrolls into view. */
31
+ rootMargin?: string;
32
+ className?: string;
33
+ style?: CSSProperties;
34
+ };
35
+
36
+ /**
37
+ * Poster first, live demo later: the import starts when the container is
38
+ * near the viewport AND the main thread is idle, and the live demo cross-fades
39
+ * in over the poster once it reports `onReady`. Height is fixed up front, so
40
+ * there is no layout shift.
41
+ */
42
+ export function LazyShowcase<P extends object>({
43
+ load,
44
+ props,
45
+ poster,
46
+ height,
47
+ rootMargin = '200px',
48
+ className,
49
+ style,
50
+ }: LazyShowcaseProps<P>) {
51
+ const ref = useRef<HTMLDivElement | null>(null);
52
+ const loadRef = useRef(load);
53
+ loadRef.current = load;
54
+ const [Live, setLive] = useState<ComponentType<
55
+ P & LazyShowcaseLoadedProps
56
+ > | null>(null);
57
+ const [ready, setReady] = useState(false);
58
+ const [failed, setFailed] = useState(false);
59
+
60
+ useEffect(() => {
61
+ const node = ref.current;
62
+ if (!node) return;
63
+ let cancelIdle: (() => void) | undefined;
64
+ let disposed = false;
65
+ const observer = new IntersectionObserver(
66
+ (entries) => {
67
+ if (!entries.some((entry) => entry.isIntersecting)) return;
68
+ observer.disconnect();
69
+ cancelIdle = whenIdle(() => {
70
+ loadRef
71
+ .current()
72
+ .then((mod) => {
73
+ if (!disposed) setLive(() => mod.default);
74
+ })
75
+ .catch((error) => {
76
+ console.warn(
77
+ '[lazy-showcase] failed to load the live demo',
78
+ error,
79
+ );
80
+ if (!disposed) setFailed(true);
81
+ });
82
+ });
83
+ },
84
+ { rootMargin },
85
+ );
86
+ observer.observe(node);
87
+ return () => {
88
+ disposed = true;
89
+ observer.disconnect();
90
+ cancelIdle?.();
91
+ };
92
+ }, [rootMargin]);
93
+
94
+ return (
95
+ <div
96
+ ref={ref}
97
+ className={['showcase-lazy', className].filter(Boolean).join(' ')}
98
+ style={{ height, ...style }}
99
+ data-showcase-ready={ready ? 'true' : 'false'}
100
+ >
101
+ <div className="showcase-lazy__poster" aria-hidden={ready}>
102
+ {poster}
103
+ </div>
104
+ {Live && !failed ? (
105
+ <div className="showcase-lazy__live">
106
+ <Live {...props} onReady={() => setReady(true)} />
107
+ </div>
108
+ ) : null}
109
+ </div>
110
+ );
111
+ }