@thedatagrid/docs-kit 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +7 -0
- package/README.md +123 -2
- package/dist/code/demoFiles.d.ts +14 -0
- package/dist/code/demoFiles.d.ts.map +1 -0
- package/dist/code/demoFiles.js +46 -0
- package/dist/code/demoFiles.js.map +1 -0
- package/dist/code/heights.d.ts +17 -0
- package/dist/code/heights.d.ts.map +1 -0
- package/dist/code/heights.js +40 -0
- package/dist/code/heights.js.map +1 -0
- package/dist/code/highlightSpec.d.ts +34 -0
- package/dist/code/highlightSpec.d.ts.map +1 -0
- package/dist/code/highlightSpec.js +119 -0
- package/dist/code/highlightSpec.js.map +1 -0
- package/dist/code/imports.d.ts +5 -0
- package/dist/code/imports.d.ts.map +1 -0
- package/dist/code/imports.js +17 -0
- package/dist/code/imports.js.map +1 -0
- package/dist/code/index.d.ts +8 -0
- package/dist/code/index.d.ts.map +1 -0
- package/dist/code/index.js +8 -0
- package/dist/code/index.js.map +1 -0
- package/dist/code/lineRanges.d.ts +5 -0
- package/dist/code/lineRanges.d.ts.map +1 -0
- package/dist/code/lineRanges.js +35 -0
- package/dist/code/lineRanges.js.map +1 -0
- package/dist/code/regions.d.ts +53 -0
- package/dist/code/regions.d.ts.map +1 -0
- package/dist/code/regions.js +237 -0
- package/dist/code/regions.js.map +1 -0
- package/dist/code/shiki.d.ts +58 -0
- package/dist/code/shiki.d.ts.map +1 -0
- package/dist/code/shiki.js +244 -0
- package/dist/code/shiki.js.map +1 -0
- package/dist/demos/build.d.ts +17 -0
- package/dist/demos/build.d.ts.map +1 -0
- package/dist/demos/build.js +426 -0
- package/dist/demos/build.js.map +1 -0
- package/dist/demos/cli.d.ts +3 -0
- package/dist/demos/cli.d.ts.map +1 -0
- package/dist/demos/cli.js +68 -0
- package/dist/demos/cli.js.map +1 -0
- package/dist/demos/client.d.ts +27 -0
- package/dist/demos/client.d.ts.map +1 -0
- package/dist/demos/client.js +61 -0
- package/dist/demos/client.js.map +1 -0
- package/dist/demos/compile/core.d.ts +64 -0
- package/dist/demos/compile/core.d.ts.map +1 -0
- package/dist/demos/compile/core.js +174 -0
- package/dist/demos/compile/core.js.map +1 -0
- package/dist/demos/config.d.ts +108 -0
- package/dist/demos/config.d.ts.map +1 -0
- package/dist/demos/config.js +4 -0
- package/dist/demos/config.js.map +1 -0
- package/dist/demos/devEvents.d.ts +13 -0
- package/dist/demos/devEvents.d.ts.map +1 -0
- package/dist/demos/devEvents.js +45 -0
- package/dist/demos/devEvents.js.map +1 -0
- package/dist/demos/html.d.ts +21 -0
- package/dist/demos/html.d.ts.map +1 -0
- package/dist/demos/html.js +57 -0
- package/dist/demos/html.js.map +1 -0
- package/dist/demos/index.d.ts +8 -0
- package/dist/demos/index.d.ts.map +1 -0
- package/dist/demos/index.js +6 -0
- package/dist/demos/index.js.map +1 -0
- package/dist/demos/pages.d.ts +15 -0
- package/dist/demos/pages.d.ts.map +1 -0
- package/dist/demos/pages.js +71 -0
- package/dist/demos/pages.js.map +1 -0
- package/dist/demos/runtime/iframe.d.ts +50 -0
- package/dist/demos/runtime/iframe.d.ts.map +1 -0
- package/dist/demos/runtime/iframe.js +245 -0
- package/dist/demos/runtime/iframe.js.map +1 -0
- package/dist/demos/runtime/react.d.ts +3 -0
- package/dist/demos/runtime/react.d.ts.map +1 -0
- package/dist/demos/runtime/react.js +17 -0
- package/dist/demos/runtime/react.js.map +1 -0
- package/dist/demos/slug.d.ts +3 -0
- package/dist/demos/slug.d.ts.map +1 -0
- package/dist/demos/slug.js +11 -0
- package/dist/demos/slug.js.map +1 -0
- package/dist/demos/vendor.d.ts +32 -0
- package/dist/demos/vendor.d.ts.map +1 -0
- package/dist/demos/vendor.js +127 -0
- package/dist/demos/vendor.js.map +1 -0
- package/dist/demos/worker/compile.worker.d.ts +2 -0
- package/dist/demos/worker/compile.worker.d.ts.map +1 -0
- package/dist/demos/worker/compile.worker.js +27 -0
- package/dist/demos/worker/compile.worker.js.map +1 -0
- package/dist/fork/codesandbox.d.ts +39 -0
- package/dist/fork/codesandbox.d.ts.map +1 -0
- package/dist/fork/codesandbox.js +156 -0
- package/dist/fork/codesandbox.js.map +1 -0
- package/dist/fork/index.d.ts +2 -0
- package/dist/fork/index.d.ts.map +1 -0
- package/dist/fork/index.js +2 -0
- package/dist/fork/index.js.map +1 -0
- package/dist/react/Demo.d.ts +80 -0
- package/dist/react/Demo.d.ts.map +1 -0
- package/dist/react/Demo.js +156 -0
- package/dist/react/Demo.js.map +1 -0
- package/dist/react/DemoIframe.d.ts +22 -0
- package/dist/react/DemoIframe.d.ts.map +1 -0
- package/dist/react/DemoIframe.js +123 -0
- package/dist/react/DemoIframe.js.map +1 -0
- package/dist/react/DemoShell.d.ts +47 -0
- package/dist/react/DemoShell.d.ts.map +1 -0
- package/dist/react/DemoShell.js +341 -0
- package/dist/react/DemoShell.js.map +1 -0
- package/dist/react/devEvents.d.ts +17 -0
- package/dist/react/devEvents.d.ts.map +1 -0
- package/dist/react/devEvents.js +30 -0
- package/dist/react/devEvents.js.map +1 -0
- package/dist/react/editor.d.ts +8 -0
- package/dist/react/editor.d.ts.map +1 -0
- package/dist/react/editor.js +52 -0
- package/dist/react/editor.js.map +1 -0
- package/dist/react/fork.d.ts +10 -0
- package/dist/react/fork.d.ts.map +1 -0
- package/dist/react/fork.js +30 -0
- package/dist/react/fork.js.map +1 -0
- package/dist/react/index.d.ts +4 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +4 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/styles.css +493 -0
- package/dist/remark/index.d.ts +3 -0
- package/dist/remark/index.d.ts.map +1 -0
- package/dist/remark/index.js +3 -0
- package/dist/remark/index.js.map +1 -0
- package/dist/remark/meta.d.ts +7 -0
- package/dist/remark/meta.d.ts.map +1 -0
- package/dist/remark/meta.js +20 -0
- package/dist/remark/meta.js.map +1 -0
- package/dist/remark/remarkDemoFences.d.ts +77 -0
- package/dist/remark/remarkDemoFences.d.ts.map +1 -0
- package/dist/remark/remarkDemoFences.js +259 -0
- package/dist/remark/remarkDemoFences.js.map +1 -0
- package/package.json +106 -4
- package/src/code/demoFiles.ts +54 -0
- package/src/code/heights.ts +47 -0
- package/src/code/highlightSpec.ts +139 -0
- package/src/code/imports.ts +18 -0
- package/src/code/index.ts +46 -0
- package/src/code/lineRanges.ts +31 -0
- package/src/code/regions.ts +270 -0
- package/src/code/shiki.ts +271 -0
- package/src/demos/build.ts +477 -0
- package/src/demos/cli.ts +64 -0
- package/src/demos/client.ts +82 -0
- package/src/demos/compile/core.ts +228 -0
- package/src/demos/config.ts +106 -0
- package/src/demos/devEvents.ts +45 -0
- package/src/demos/html.ts +74 -0
- package/src/demos/index.ts +25 -0
- package/src/demos/pages.ts +79 -0
- package/src/demos/runtime/iframe.ts +262 -0
- package/src/demos/runtime/react.ts +19 -0
- package/src/demos/slug.ts +10 -0
- package/src/demos/vendor.ts +142 -0
- package/src/demos/worker/compile.worker.ts +35 -0
- package/src/fork/codesandbox.ts +189 -0
- package/src/fork/index.ts +10 -0
- package/src/react/Demo.tsx +250 -0
- package/src/react/DemoIframe.tsx +165 -0
- package/src/react/DemoShell.tsx +592 -0
- package/src/react/devEvents.ts +34 -0
- package/src/react/editor.ts +61 -0
- package/src/react/fork.ts +31 -0
- package/src/react/index.ts +10 -0
- package/src/react/styles.css +493 -0
- package/src/remark/index.ts +2 -0
- package/src/remark/meta.ts +20 -0
- package/src/remark/remarkDemoFences.ts +330 -0
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import type { ReactNode } from 'react';
|
|
4
|
+
|
|
5
|
+
import { collectDemoFiles } from '../code/demoFiles.ts';
|
|
6
|
+
import { parseHighlightSpec } from '../code/highlightSpec.ts';
|
|
7
|
+
import { DEMO_HEIGHTS, parseDemoHeight, type DemoHeights } from '../code/heights.ts';
|
|
8
|
+
import { parseLineRanges } from '../code/lineRanges.ts';
|
|
9
|
+
import { applySourceReplacements, extractCodeMarkers, sliceRegion, stripCodeMarkers } from '../code/regions.ts';
|
|
10
|
+
import { highlightCode, langForFile, type CodeThemes } from '../code/shiki.ts';
|
|
11
|
+
import type { DemoManifest } from '../demos/config.ts';
|
|
12
|
+
import { slugifyDemoTitle } from '../demos/slug.ts';
|
|
13
|
+
import { DemoShell, type DemoShellFile } from './DemoShell.tsx';
|
|
14
|
+
|
|
15
|
+
export type DemoContext = {
|
|
16
|
+
/** Absolute path of the content root. */
|
|
17
|
+
contentDir: string;
|
|
18
|
+
/** Content-relative folder of the page (slashes are trimmed). */
|
|
19
|
+
folder: string;
|
|
20
|
+
/** Path of the builder's `manifest.json`, or the manifest itself. */
|
|
21
|
+
manifest: string | DemoManifest;
|
|
22
|
+
themes?: CodeThemes;
|
|
23
|
+
heights?: DemoHeights;
|
|
24
|
+
/** Allow editing live demos. Default `true`. */
|
|
25
|
+
editable?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Prefix of the card anchors (`#<prefix><slug>`), so they can't collide
|
|
28
|
+
* with heading ids. Must match the builder's `anchorPrefix`. Default `''`.
|
|
29
|
+
*/
|
|
30
|
+
anchorPrefix?: string;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export type DemoProps = {
|
|
34
|
+
/**
|
|
35
|
+
* Demo entry without the demo suffix (set by the remark plugin): relative to
|
|
36
|
+
* the page's folder, or to the content root when it starts with `/`.
|
|
37
|
+
*/
|
|
38
|
+
name?: string;
|
|
39
|
+
height?: string;
|
|
40
|
+
/** `code`: the code tab shows first (`live=off`). */
|
|
41
|
+
startTab?: string;
|
|
42
|
+
/** The entry's code tab shows only this `#region`. */
|
|
43
|
+
region?: string;
|
|
44
|
+
/** `files=off`: no file names or tabs. */
|
|
45
|
+
hideFiles?: string;
|
|
46
|
+
/** `edit=off` on the fence. */
|
|
47
|
+
editable?: string;
|
|
48
|
+
title?: string;
|
|
49
|
+
/** Code-only card: the snippet (set by the remark plugin). */
|
|
50
|
+
code?: string;
|
|
51
|
+
lang?: string;
|
|
52
|
+
codeTitle?: string;
|
|
53
|
+
/** Serialized `#highlight` lines of `code`. */
|
|
54
|
+
highlight?: string;
|
|
55
|
+
/** `code` without the label rows of `#highlight label` markers (what copy copies). */
|
|
56
|
+
copyCode?: string;
|
|
57
|
+
lines?: string | boolean;
|
|
58
|
+
/** Original file line numbers (`"12-14,16"`) of a `region` snippet. */
|
|
59
|
+
originalLines?: string;
|
|
60
|
+
/** `<DemoTitle>` / `<DemoDescription>`. */
|
|
61
|
+
children?: ReactNode;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** Card-header title, used inside `<Demo>`. */
|
|
65
|
+
export function DemoTitle({ children }: { children?: ReactNode }) {
|
|
66
|
+
return <div className="dk-demo-title">{children}</div>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Card-header description, used inside `<Demo>`. */
|
|
70
|
+
export function DemoDescription({ children }: { children?: ReactNode }) {
|
|
71
|
+
return <div className="dk-demo-description">{children}</div>;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function nodeText(node: ReactNode): string {
|
|
75
|
+
if (node == null || typeof node === 'boolean') return '';
|
|
76
|
+
if (typeof node === 'string' || typeof node === 'number') return String(node);
|
|
77
|
+
if (Array.isArray(node)) return node.map(nodeText).join('');
|
|
78
|
+
if (typeof node === 'object' && 'props' in node) {
|
|
79
|
+
return nodeText((node as { props: { children?: ReactNode } }).props.children);
|
|
80
|
+
}
|
|
81
|
+
return '';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function isDemoTitleElement(node: unknown): boolean {
|
|
85
|
+
if (!node || typeof node !== 'object' || !('type' in node)) return false;
|
|
86
|
+
const type = (node as { type: unknown }).type;
|
|
87
|
+
if (type === DemoTitle || type === 'DemoTitle') return true;
|
|
88
|
+
return typeof type === 'function' && (type as { name?: string }).name === 'DemoTitle';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function extractDemoTitle(children: ReactNode): string | null {
|
|
92
|
+
const list = Array.isArray(children) ? children : children != null ? [children] : [];
|
|
93
|
+
for (const child of list) {
|
|
94
|
+
if (!isDemoTitleElement(child)) continue;
|
|
95
|
+
const text = nodeText((child as { props: { children?: ReactNode } }).props.children).trim();
|
|
96
|
+
if (text) return text;
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function resolveHeader(children: ReactNode, fallbackTitle?: string): ReactNode {
|
|
102
|
+
if (extractDemoTitle(children) || !fallbackTitle) return children;
|
|
103
|
+
return (
|
|
104
|
+
<>
|
|
105
|
+
<DemoTitle>{fallbackTitle}</DemoTitle>
|
|
106
|
+
{children}
|
|
107
|
+
</>
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const toPosix = (p: string) => p.split(path.sep).join('/');
|
|
112
|
+
|
|
113
|
+
function readManifest(manifest: string | DemoManifest): DemoManifest {
|
|
114
|
+
if (typeof manifest !== 'string') return manifest;
|
|
115
|
+
if (!fs.existsSync(manifest)) {
|
|
116
|
+
throw new Error(
|
|
117
|
+
`docs-kit: demo manifest not found at ${manifest} — run \`docs-kit demos build\` (or the watcher) first`,
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
return JSON.parse(fs.readFileSync(manifest, 'utf8')) as DemoManifest;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Server component: reads the demo entry (following its relative imports),
|
|
125
|
+
* highlights every file with shiki (dual themes) and renders the client shell
|
|
126
|
+
* around the prebuilt iframe. Without `name` it renders a code-only card.
|
|
127
|
+
*
|
|
128
|
+
* Missing files, regions or prebuilt bundles throw, so a bad reference fails
|
|
129
|
+
* a static build instead of shipping a broken page.
|
|
130
|
+
*/
|
|
131
|
+
export async function Demo(props: DemoProps & { context: DemoContext }) {
|
|
132
|
+
const { context, children } = props;
|
|
133
|
+
const heights = context.heights ?? DEMO_HEIGHTS;
|
|
134
|
+
const heightPx = props.height == null ? null : parseDemoHeight(props.height, heights);
|
|
135
|
+
const folder = context.folder.replace(/^\/+|\/+$/g, '');
|
|
136
|
+
const highlightSpec = props.highlight ? parseHighlightSpec(props.highlight) : null;
|
|
137
|
+
const showLines = props.lines != null && props.lines !== false && props.lines !== 'false';
|
|
138
|
+
const parsedLines = typeof props.originalLines === 'string' ? parseLineRanges(props.originalLines) : [];
|
|
139
|
+
const originalLines = parsedLines.length ? parsedLines : undefined;
|
|
140
|
+
const themes = context.themes;
|
|
141
|
+
|
|
142
|
+
if (!props.name) {
|
|
143
|
+
if (typeof props.code !== 'string') {
|
|
144
|
+
throw new Error(
|
|
145
|
+
`<Demo> in "${folder}": needs a live fence (\`\`\`tsx file="..." live) or a code fence inside`,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
const shownCode = props.code.trimEnd();
|
|
149
|
+
const rawCode = (props.copyCode ?? props.code).trimEnd();
|
|
150
|
+
const html = await highlightCode(shownCode, {
|
|
151
|
+
lang: props.lang || 'tsx',
|
|
152
|
+
themes,
|
|
153
|
+
highlight: highlightSpec,
|
|
154
|
+
lineNumbers: showLines ? (originalLines ?? true) : null,
|
|
155
|
+
});
|
|
156
|
+
// untitled snippets get no anchor: many of them on one page would share it
|
|
157
|
+
const explicitTitle = extractDemoTitle(children) || props.title || props.codeTitle;
|
|
158
|
+
return (
|
|
159
|
+
<DemoShell
|
|
160
|
+
height={heightPx}
|
|
161
|
+
heights={heights}
|
|
162
|
+
title={explicitTitle || 'Code'}
|
|
163
|
+
slug={explicitTitle ? `${context.anchorPrefix ?? ''}${slugifyDemoTitle(explicitTitle)}` : ''}
|
|
164
|
+
files={[{ name: props.codeTitle || '', path: '', rawCode, html }]}
|
|
165
|
+
header={props.title || extractDemoTitle(children) ? resolveHeader(children, props.title) : children}
|
|
166
|
+
/>
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const manifest = readManifest(context.manifest);
|
|
171
|
+
// `name` is relative to the page, or to the content root when it starts with `/`
|
|
172
|
+
const demoId = path.posix.normalize(
|
|
173
|
+
props.name.startsWith('/') ? props.name.slice(1) : folder ? `${folder}/${props.name}` : props.name,
|
|
174
|
+
);
|
|
175
|
+
if (demoId.startsWith('..')) {
|
|
176
|
+
throw new Error(`<Demo name="${props.name}"> in "${folder}": the demo must be inside the content folder`);
|
|
177
|
+
}
|
|
178
|
+
const entryFile = path.join(context.contentDir, `${demoId}${manifest.demoSuffix}`);
|
|
179
|
+
const context_ = `<Demo name="${props.name}"> in "${folder}"`;
|
|
180
|
+
if (!fs.existsSync(entryFile)) {
|
|
181
|
+
throw new Error(`${context_}: demo file not found: ${path.relative(context.contentDir, entryFile)}`);
|
|
182
|
+
}
|
|
183
|
+
const built = manifest.demos[demoId];
|
|
184
|
+
if (!built) {
|
|
185
|
+
throw new Error(`${context_}: "${demoId}" isn't in the demo manifest — is the demo builder running?`);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const sources = collectDemoFiles(entryFile);
|
|
189
|
+
const entryDir = path.dirname(entryFile);
|
|
190
|
+
const filesHidden = props.hideFiles === 'true';
|
|
191
|
+
const names = sources.map(({ filePath }) => toPosix(path.relative(entryDir, filePath)));
|
|
192
|
+
|
|
193
|
+
const files: DemoShellFile[] = await Promise.all(
|
|
194
|
+
sources.map(async ({ filePath, source }, index) => {
|
|
195
|
+
const name = names[index];
|
|
196
|
+
const fileContext = `${context_} (${name})`;
|
|
197
|
+
const fullSource = applySourceReplacements(source.trimEnd(), manifest.sourceReplacements);
|
|
198
|
+
const sliced = index === 0 && props.region ? sliceRegion(fullSource, props.region, fileContext) : null;
|
|
199
|
+
const marked = sliced
|
|
200
|
+
? extractCodeMarkers(sliced.source, fileContext, sliced.originalLines)
|
|
201
|
+
: extractCodeMarkers(fullSource, fileContext);
|
|
202
|
+
// copy / edit / fork: no marker comments and no label rows
|
|
203
|
+
const fullCode = stripCodeMarkers(fullSource);
|
|
204
|
+
const copyCode = sliced ? stripCodeMarkers(sliced.source) : fullCode;
|
|
205
|
+
const html = await highlightCode(marked.source, {
|
|
206
|
+
lang: langForFile(filePath),
|
|
207
|
+
themes,
|
|
208
|
+
highlight: marked.highlight,
|
|
209
|
+
lineNumbers: showLines ? (sliced ? marked.originalLines : true) : null,
|
|
210
|
+
importLinks: filesHidden ? null : { fromFile: name, fileNames: names },
|
|
211
|
+
});
|
|
212
|
+
return {
|
|
213
|
+
name,
|
|
214
|
+
path: toPosix(path.relative(context.contentDir, filePath)),
|
|
215
|
+
rawCode: copyCode,
|
|
216
|
+
fullCode,
|
|
217
|
+
html,
|
|
218
|
+
};
|
|
219
|
+
}),
|
|
220
|
+
);
|
|
221
|
+
|
|
222
|
+
const displayTitle = extractDemoTitle(children) || props.title || `${path.basename(props.name)}${manifest.demoSuffix}`;
|
|
223
|
+
const editable = (context.editable ?? true) && props.editable !== 'false';
|
|
224
|
+
|
|
225
|
+
return (
|
|
226
|
+
<DemoShell
|
|
227
|
+
demoUrl={built.html}
|
|
228
|
+
height={heightPx}
|
|
229
|
+
heights={heights}
|
|
230
|
+
initialTab={props.startTab === 'code' ? 'code' : undefined}
|
|
231
|
+
title={displayTitle}
|
|
232
|
+
slug={`${context.anchorPrefix ?? ''}${slugifyDemoTitle(displayTitle)}`}
|
|
233
|
+
files={files}
|
|
234
|
+
hideFiles={filesHidden}
|
|
235
|
+
header={resolveHeader(children, props.title)}
|
|
236
|
+
editor={editable ? manifest.editor : undefined}
|
|
237
|
+
fork={manifest.fork}
|
|
238
|
+
devEvents={manifest.devEvents}
|
|
239
|
+
/>
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* MDX components bound to one page: `Demo`, `DemoTitle`, `DemoDescription`.
|
|
245
|
+
* Register them in the page's MDX `components`.
|
|
246
|
+
*/
|
|
247
|
+
export function createDemoComponents(context: DemoContext) {
|
|
248
|
+
const BoundDemo = (props: DemoProps) => <Demo {...props} context={context} />;
|
|
249
|
+
return { Demo: BoundDemo, DemoTitle, DemoDescription };
|
|
250
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
|
|
4
|
+
|
|
5
|
+
import { subscribeDevEvents } from './devEvents.ts';
|
|
6
|
+
|
|
7
|
+
export type DemoIframeHandle = {
|
|
8
|
+
/** postMessage into the demo (queued until the iframe has loaded). */
|
|
9
|
+
post(message: Record<string, unknown>): void;
|
|
10
|
+
/** Reload the prebuilt page. */
|
|
11
|
+
reload(): void;
|
|
12
|
+
/** Clear the demo's persisted state, then reload. */
|
|
13
|
+
reset(): void;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
type DemoIframeProps = {
|
|
17
|
+
demoUrl: string;
|
|
18
|
+
/** Pixels; omitted → fill the parent. */
|
|
19
|
+
height?: number;
|
|
20
|
+
title: string;
|
|
21
|
+
/** Dev-only SSE endpoint (`:port/path`) reporting rebuilt demo pages. */
|
|
22
|
+
devEvents?: string;
|
|
23
|
+
onReady?: () => void;
|
|
24
|
+
onEscape?: () => void;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const currentTheme = () =>
|
|
28
|
+
typeof document === 'undefined' ? 'light' : document.documentElement.getAttribute('data-theme') || 'light';
|
|
29
|
+
|
|
30
|
+
/** Lazy prebuilt-demo iframe with the docs ↔ demo message bridge. */
|
|
31
|
+
export const DemoIframe = forwardRef<DemoIframeHandle, DemoIframeProps>(function DemoIframe(props, ref) {
|
|
32
|
+
const { demoUrl, height, title, devEvents } = props;
|
|
33
|
+
const containerRef = useRef<HTMLDivElement | null>(null);
|
|
34
|
+
const iframeRef = useRef<HTMLIFrameElement | null>(null);
|
|
35
|
+
const [shouldLoad, setShouldLoad] = useState(false);
|
|
36
|
+
const [ready, setReady] = useState(false);
|
|
37
|
+
const readyRef = useRef(false);
|
|
38
|
+
readyRef.current = ready;
|
|
39
|
+
const [reloadTick, setReloadTick] = useState(0);
|
|
40
|
+
const queue = useRef<Record<string, unknown>[]>([]);
|
|
41
|
+
const onReadyRef = useRef(props.onReady);
|
|
42
|
+
onReadyRef.current = props.onReady;
|
|
43
|
+
const onEscapeRef = useRef(props.onEscape);
|
|
44
|
+
onEscapeRef.current = props.onEscape;
|
|
45
|
+
|
|
46
|
+
const reload = () => {
|
|
47
|
+
readyRef.current = false;
|
|
48
|
+
setReady(false);
|
|
49
|
+
setReloadTick((tick) => tick + 1);
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
useImperativeHandle(ref, () => ({
|
|
53
|
+
post(message) {
|
|
54
|
+
const win = iframeRef.current?.contentWindow;
|
|
55
|
+
if (win && readyRef.current) win.postMessage(message, '*');
|
|
56
|
+
else {
|
|
57
|
+
queue.current.push(message);
|
|
58
|
+
setShouldLoad(true);
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
reload,
|
|
62
|
+
reset() {
|
|
63
|
+
const win = iframeRef.current?.contentWindow;
|
|
64
|
+
if (!win) return reload();
|
|
65
|
+
let timer = 0;
|
|
66
|
+
const finish = () => {
|
|
67
|
+
window.removeEventListener('message', onMessage);
|
|
68
|
+
window.clearTimeout(timer);
|
|
69
|
+
reload();
|
|
70
|
+
};
|
|
71
|
+
function onMessage(event: MessageEvent) {
|
|
72
|
+
if (event.source === win && event.data?.type === 'demo-reset-done') finish();
|
|
73
|
+
}
|
|
74
|
+
window.addEventListener('message', onMessage);
|
|
75
|
+
timer = window.setTimeout(finish, 1000);
|
|
76
|
+
win.postMessage({ type: 'demo-reset' }, '*');
|
|
77
|
+
},
|
|
78
|
+
}));
|
|
79
|
+
|
|
80
|
+
// Lazy-load when scrolled near the viewport.
|
|
81
|
+
useEffect(() => {
|
|
82
|
+
if (shouldLoad) return;
|
|
83
|
+
const el = containerRef.current;
|
|
84
|
+
if (!el || typeof IntersectionObserver === 'undefined') {
|
|
85
|
+
setShouldLoad(true);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const observer = new IntersectionObserver(
|
|
89
|
+
(entries) => {
|
|
90
|
+
if (entries.some((entry) => entry.isIntersecting)) {
|
|
91
|
+
setShouldLoad(true);
|
|
92
|
+
observer.disconnect();
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
{ rootMargin: '400px' },
|
|
96
|
+
);
|
|
97
|
+
observer.observe(el);
|
|
98
|
+
return () => observer.disconnect();
|
|
99
|
+
}, [shouldLoad]);
|
|
100
|
+
|
|
101
|
+
// Messages from the demo: ready (reveal + flush the queue + theme), escape.
|
|
102
|
+
useEffect(() => {
|
|
103
|
+
if (!shouldLoad) return;
|
|
104
|
+
const sendTheme = () =>
|
|
105
|
+
iframeRef.current?.contentWindow?.postMessage({ type: 'set-theme', theme: currentTheme() }, '*');
|
|
106
|
+
function onMessage(event: MessageEvent) {
|
|
107
|
+
if (event.source !== iframeRef.current?.contentWindow) return;
|
|
108
|
+
const type = event.data?.type;
|
|
109
|
+
if (type === 'demo-ready') {
|
|
110
|
+
readyRef.current = true;
|
|
111
|
+
setReady(true);
|
|
112
|
+
sendTheme();
|
|
113
|
+
const win = iframeRef.current?.contentWindow;
|
|
114
|
+
for (const message of queue.current.splice(0)) win?.postMessage(message, '*');
|
|
115
|
+
onReadyRef.current?.();
|
|
116
|
+
} else if (type === 'demo-error') {
|
|
117
|
+
setReady(true);
|
|
118
|
+
} else if (type === 'demo-escape') {
|
|
119
|
+
onEscapeRef.current?.();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
window.addEventListener('message', onMessage);
|
|
123
|
+
const observer = new MutationObserver(sendTheme);
|
|
124
|
+
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
|
125
|
+
const fallback = window.setTimeout(() => setReady(true), 8000);
|
|
126
|
+
return () => {
|
|
127
|
+
window.removeEventListener('message', onMessage);
|
|
128
|
+
observer.disconnect();
|
|
129
|
+
window.clearTimeout(fallback);
|
|
130
|
+
};
|
|
131
|
+
}, [shouldLoad, reloadTick]);
|
|
132
|
+
|
|
133
|
+
// Dev only: reload when the watcher rebuilt this demo's page.
|
|
134
|
+
useEffect(() => {
|
|
135
|
+
if (!devEvents || !shouldLoad) return;
|
|
136
|
+
return subscribeDevEvents(devEvents, (event) => {
|
|
137
|
+
if (event.type === 'demo' && event.url === demoUrl) reload();
|
|
138
|
+
});
|
|
139
|
+
}, [devEvents, shouldLoad, demoUrl]);
|
|
140
|
+
|
|
141
|
+
const src = shouldLoad
|
|
142
|
+
? `${demoUrl}?theme=${encodeURIComponent(currentTheme())}${reloadTick ? `&v=${reloadTick}` : ''}`
|
|
143
|
+
: undefined;
|
|
144
|
+
|
|
145
|
+
return (
|
|
146
|
+
<div
|
|
147
|
+
ref={containerRef}
|
|
148
|
+
className={`dk-demo-frame${height == null ? ' dk-demo-frame--fill' : ''}`}
|
|
149
|
+
style={height == null ? undefined : { height }}
|
|
150
|
+
>
|
|
151
|
+
{src ? (
|
|
152
|
+
<iframe
|
|
153
|
+
key={src}
|
|
154
|
+
ref={iframeRef}
|
|
155
|
+
src={src}
|
|
156
|
+
title={`${title} demo`}
|
|
157
|
+
loading="lazy"
|
|
158
|
+
style={{ opacity: ready ? 1 : 0 }}
|
|
159
|
+
sandbox="allow-forms allow-modals allow-popups allow-same-origin allow-scripts"
|
|
160
|
+
/>
|
|
161
|
+
) : null}
|
|
162
|
+
{!ready ? <div className="dk-demo-loading">loading demo…</div> : null}
|
|
163
|
+
</div>
|
|
164
|
+
);
|
|
165
|
+
});
|