@thedatagrid/docs-kit 0.0.0-stage → 0.2.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 +20 -0
- package/README.md +224 -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 +102 -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/editor/install.d.ts +15 -0
- package/dist/editor/install.d.ts.map +1 -0
- package/dist/editor/install.js +71 -0
- package/dist/editor/install.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 +17 -0
- package/dist/react/editor.d.ts.map +1 -0
- package/dist/react/editor.js +158 -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 +471 -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/editor-extension/README.md +23 -0
- package/editor-extension/extension.js +40 -0
- package/editor-extension/links.js +137 -0
- package/editor-extension/package.json +19 -0
- package/package.json +107 -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 +97 -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/editor/install.ts +85 -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 +178 -0
- package/src/react/fork.ts +31 -0
- package/src/react/index.ts +10 -0
- package/src/react/styles.css +471 -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,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs inside every demo iframe (bundled by the builder together with the
|
|
3
|
+
* framework adapter and the site's bootstrap module).
|
|
4
|
+
*
|
|
5
|
+
* Parent → iframe messages:
|
|
6
|
+
* { type: 'set-theme', theme } docs light/dark changed
|
|
7
|
+
* { type: 'demo-reset' } unmount + clear persisted keys
|
|
8
|
+
* { type: 'demo-update', js, css } run an edited build in place
|
|
9
|
+
* { type: 'demo-compile-error', message } show compile errors
|
|
10
|
+
* Iframe → parent:
|
|
11
|
+
* demo-ready, demo-error { message }, demo-escape, demo-reset-done
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export type DocsTheme = 'light' | 'dark';
|
|
15
|
+
|
|
16
|
+
export type MountedDemo = { unmount(): void };
|
|
17
|
+
|
|
18
|
+
/** Framework glue: renders a demo module's default export into an element. */
|
|
19
|
+
export type DemoAdapter = {
|
|
20
|
+
render(target: HTMLElement, component: unknown, onError: (error: unknown) => void): MountedDemo;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** The site's bootstrap module (`bootstrap` in docs-kit.config). All hooks are optional. */
|
|
24
|
+
export type SiteBootstrap = {
|
|
25
|
+
/** Called once, before the first mount. */
|
|
26
|
+
setup?(context: { theme: DocsTheme }): void | Promise<void>;
|
|
27
|
+
/** Called on load and whenever the docs theme changes. */
|
|
28
|
+
applyTheme?(theme: DocsTheme): void;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export type RuntimeOptions = {
|
|
32
|
+
adapter: DemoAdapter;
|
|
33
|
+
site: SiteBootstrap;
|
|
34
|
+
/** localStorage key the docs site keeps its theme under. */
|
|
35
|
+
themeStorageKey?: string;
|
|
36
|
+
defaultTheme?: DocsTheme;
|
|
37
|
+
/** Classes on `<html>` per theme. */
|
|
38
|
+
themeClasses?: { light?: string[]; dark?: string[] };
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const post = (message: Record<string, unknown>) => {
|
|
42
|
+
try {
|
|
43
|
+
parent.postMessage(message, '*');
|
|
44
|
+
} catch {
|
|
45
|
+
// standalone page without a parent - nothing to tell
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export function resolveTheme(storageKey: string | undefined, fallback: DocsTheme): DocsTheme {
|
|
50
|
+
try {
|
|
51
|
+
const fromQuery = new URLSearchParams(location.search).get('theme');
|
|
52
|
+
if (fromQuery === 'dark' || fromQuery === 'light') return fromQuery;
|
|
53
|
+
const stored = storageKey ? localStorage.getItem(storageKey) : null;
|
|
54
|
+
if (stored === 'dark' || stored === 'light') return stored;
|
|
55
|
+
if (window.matchMedia?.('(prefers-color-scheme: dark)').matches) return 'dark';
|
|
56
|
+
} catch {
|
|
57
|
+
// storage blocked
|
|
58
|
+
}
|
|
59
|
+
return fallback;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
let overlay: HTMLDivElement | null = null;
|
|
63
|
+
|
|
64
|
+
function showOverlay(title: string, message: string) {
|
|
65
|
+
if (!overlay) {
|
|
66
|
+
overlay = document.createElement('div');
|
|
67
|
+
overlay.id = 'dk-error-overlay';
|
|
68
|
+
overlay.setAttribute('role', 'alert');
|
|
69
|
+
document.body.appendChild(overlay);
|
|
70
|
+
}
|
|
71
|
+
overlay.replaceChildren();
|
|
72
|
+
const heading = document.createElement('div');
|
|
73
|
+
heading.className = 'dk-error-title';
|
|
74
|
+
heading.textContent = title;
|
|
75
|
+
const close = document.createElement('button');
|
|
76
|
+
close.type = 'button';
|
|
77
|
+
close.textContent = '×';
|
|
78
|
+
close.title = 'Dismiss';
|
|
79
|
+
close.addEventListener('click', hideOverlay);
|
|
80
|
+
heading.appendChild(close);
|
|
81
|
+
const body = document.createElement('pre');
|
|
82
|
+
body.textContent = message;
|
|
83
|
+
overlay.append(heading, body);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function hideOverlay() {
|
|
87
|
+
overlay?.remove();
|
|
88
|
+
overlay = null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function errorText(error: unknown): string {
|
|
92
|
+
if (error instanceof Error) return error.stack || `${error.name}: ${error.message}`;
|
|
93
|
+
return String(error);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function createRuntime(options: RuntimeOptions) {
|
|
97
|
+
const { adapter, site, themeStorageKey, defaultTheme = 'light', themeClasses = {} } = options;
|
|
98
|
+
const root = () => document.getElementById('root')!;
|
|
99
|
+
|
|
100
|
+
const applyTheme = (theme: DocsTheme) => {
|
|
101
|
+
const html = document.documentElement;
|
|
102
|
+
html.setAttribute('data-theme', theme);
|
|
103
|
+
html.style.colorScheme = theme;
|
|
104
|
+
html.classList.remove(...(themeClasses.light ?? []), ...(themeClasses.dark ?? []));
|
|
105
|
+
html.classList.add(...(themeClasses[theme] ?? []));
|
|
106
|
+
site.applyTheme?.(theme);
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
// Every localStorage key the demo writes, so "reset" can clear them. Patched
|
|
110
|
+
// on the prototype: assigning localStorage.setItem would store an item
|
|
111
|
+
// named "setItem".
|
|
112
|
+
const writtenKeys = new Set<string>();
|
|
113
|
+
let resetting = false;
|
|
114
|
+
try {
|
|
115
|
+
const setItem = Storage.prototype.setItem;
|
|
116
|
+
Storage.prototype.setItem = function (this: Storage, key: string, value: string) {
|
|
117
|
+
if (this === localStorage) {
|
|
118
|
+
if (resetting) return;
|
|
119
|
+
writtenKeys.add(String(key));
|
|
120
|
+
}
|
|
121
|
+
return setItem.call(this, key, value);
|
|
122
|
+
};
|
|
123
|
+
} catch {
|
|
124
|
+
// storage unavailable
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
window.addEventListener('error', (event) => {
|
|
128
|
+
const message = errorText(event.error ?? event.message);
|
|
129
|
+
showOverlay('Runtime error', message);
|
|
130
|
+
post({ type: 'demo-error', message });
|
|
131
|
+
});
|
|
132
|
+
window.addEventListener('unhandledrejection', (event) => {
|
|
133
|
+
const message = errorText(event.reason);
|
|
134
|
+
showOverlay('Unhandled promise rejection', message);
|
|
135
|
+
post({ type: 'demo-error', message });
|
|
136
|
+
});
|
|
137
|
+
window.addEventListener(
|
|
138
|
+
'keydown',
|
|
139
|
+
(event) => {
|
|
140
|
+
if (event.key === 'Escape') post({ type: 'demo-escape' });
|
|
141
|
+
},
|
|
142
|
+
true,
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
let mounted: MountedDemo | null = null;
|
|
146
|
+
let editedStyle: HTMLStyleElement | null = null;
|
|
147
|
+
let editedUrl: string | null = null;
|
|
148
|
+
let generation = 0;
|
|
149
|
+
|
|
150
|
+
const render = (component: unknown) => {
|
|
151
|
+
try {
|
|
152
|
+
mounted?.unmount();
|
|
153
|
+
} catch {
|
|
154
|
+
// a broken demo can throw on unmount; the next render replaces it anyway
|
|
155
|
+
}
|
|
156
|
+
mounted = null;
|
|
157
|
+
root().replaceChildren();
|
|
158
|
+
mounted = adapter.render(root(), component, (error) => {
|
|
159
|
+
const message = errorText(error);
|
|
160
|
+
showOverlay('Render error', message);
|
|
161
|
+
post({ type: 'demo-error', message });
|
|
162
|
+
});
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const runEdited = async (js: string, css: string) => {
|
|
166
|
+
const current = ++generation;
|
|
167
|
+
const url = URL.createObjectURL(new Blob([js], { type: 'text/javascript' }));
|
|
168
|
+
try {
|
|
169
|
+
// Bare imports in the edited module resolve through this document's import map.
|
|
170
|
+
const mod = (await import(/* @vite-ignore */ url)) as { default?: unknown };
|
|
171
|
+
if (current !== generation) return;
|
|
172
|
+
if (!mod.default) throw new Error('The demo entry file has no default export');
|
|
173
|
+
if (editedStyle) editedStyle.remove();
|
|
174
|
+
editedStyle = null;
|
|
175
|
+
// The prebuilt demo's own stylesheet no longer matches the edited code.
|
|
176
|
+
document.querySelectorAll('link[data-demo-css]').forEach((link) => link.remove());
|
|
177
|
+
if (css) {
|
|
178
|
+
editedStyle = document.createElement('style');
|
|
179
|
+
editedStyle.dataset.demoEdited = '';
|
|
180
|
+
editedStyle.textContent = css;
|
|
181
|
+
document.head.appendChild(editedStyle);
|
|
182
|
+
}
|
|
183
|
+
hideOverlay();
|
|
184
|
+
render(mod.default);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (current !== generation) return;
|
|
187
|
+
const message = errorText(error);
|
|
188
|
+
showOverlay('Runtime error', message);
|
|
189
|
+
post({ type: 'demo-error', message });
|
|
190
|
+
} finally {
|
|
191
|
+
if (editedUrl) URL.revokeObjectURL(editedUrl);
|
|
192
|
+
editedUrl = url;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
window.addEventListener('message', (event) => {
|
|
197
|
+
const data = event.data as { type?: string; [key: string]: unknown } | null;
|
|
198
|
+
if (!data || typeof data.type !== 'string') return;
|
|
199
|
+
switch (data.type) {
|
|
200
|
+
case 'set-theme':
|
|
201
|
+
applyTheme(data.theme === 'dark' ? 'dark' : 'light');
|
|
202
|
+
break;
|
|
203
|
+
case 'demo-reset':
|
|
204
|
+
resetting = true;
|
|
205
|
+
try {
|
|
206
|
+
mounted?.unmount();
|
|
207
|
+
} catch {
|
|
208
|
+
// ignore
|
|
209
|
+
}
|
|
210
|
+
mounted = null;
|
|
211
|
+
for (const key of writtenKeys) {
|
|
212
|
+
try {
|
|
213
|
+
localStorage.removeItem(key);
|
|
214
|
+
} catch {
|
|
215
|
+
// ignore
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
post({ type: 'demo-reset-done' });
|
|
219
|
+
break;
|
|
220
|
+
case 'demo-update':
|
|
221
|
+
void runEdited(String(data.js ?? ''), String(data.css ?? ''));
|
|
222
|
+
break;
|
|
223
|
+
case 'demo-compile-error':
|
|
224
|
+
showOverlay('Compile error', String(data.message ?? 'Unknown error'));
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
return {
|
|
230
|
+
/** The demo module failed to load (syntax/runtime error at import). */
|
|
231
|
+
fail(error: unknown) {
|
|
232
|
+
const message = errorText(error);
|
|
233
|
+
showOverlay('The demo failed to load', message);
|
|
234
|
+
post({ type: 'demo-error', message });
|
|
235
|
+
post({ type: 'demo-ready' });
|
|
236
|
+
},
|
|
237
|
+
async mount(component: unknown) {
|
|
238
|
+
const theme = resolveTheme(themeStorageKey, defaultTheme);
|
|
239
|
+
applyTheme(theme);
|
|
240
|
+
try {
|
|
241
|
+
await site.setup?.({ theme });
|
|
242
|
+
render(component);
|
|
243
|
+
} catch (error) {
|
|
244
|
+
const message = errorText(error);
|
|
245
|
+
showOverlay('Runtime error', message);
|
|
246
|
+
post({ type: 'demo-error', message });
|
|
247
|
+
}
|
|
248
|
+
requestAnimationFrame(() => requestAnimationFrame(() => post({ type: 'demo-ready' })));
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Styles for the error overlay (inlined into every demo page). */
|
|
254
|
+
export const OVERLAY_CSS = `
|
|
255
|
+
#dk-error-overlay { position: fixed; inset: 8px; z-index: 2147483600; display: flex; flex-direction: column;
|
|
256
|
+
background: rgba(20, 20, 24, 0.94); color: #ffd7d7; border: 1px solid #ff6b6b; border-radius: 8px;
|
|
257
|
+
font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; overflow: hidden; }
|
|
258
|
+
#dk-error-overlay .dk-error-title { display: flex; justify-content: space-between; align-items: center;
|
|
259
|
+
padding: 8px 12px; font-weight: 600; color: #ff8b8b; border-bottom: 1px solid rgba(255, 107, 107, 0.35); }
|
|
260
|
+
#dk-error-overlay button { all: unset; cursor: pointer; font-size: 18px; line-height: 1; padding: 0 4px; color: #ffd7d7; }
|
|
261
|
+
#dk-error-overlay pre { margin: 0; padding: 12px; overflow: auto; white-space: pre-wrap; flex: 1; }
|
|
262
|
+
`;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React adapter for the iframe runtime. `react` and `react-dom/client` stay
|
|
3
|
+
* bare imports: the builder externalizes them, so the iframe's import map
|
|
4
|
+
* hands the runtime and the demo the same React instance.
|
|
5
|
+
*/
|
|
6
|
+
import { createElement, type ComponentType } from 'react';
|
|
7
|
+
import { createRoot } from 'react-dom/client';
|
|
8
|
+
|
|
9
|
+
import type { DemoAdapter } from './iframe.ts';
|
|
10
|
+
|
|
11
|
+
export const reactAdapter: DemoAdapter = {
|
|
12
|
+
render(target, component, onError) {
|
|
13
|
+
const root = createRoot(target, {
|
|
14
|
+
onUncaughtError: (error: unknown) => onError(error),
|
|
15
|
+
} as Parameters<typeof createRoot>[1]);
|
|
16
|
+
root.render(createElement(component as ComponentType));
|
|
17
|
+
return { unmount: () => root.unmount() };
|
|
18
|
+
},
|
|
19
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** URL hash slug of a demo card: "Your first grid" → `your-first-grid`, `basic.demo.tsx` → `basic-demo`. */
|
|
2
|
+
export function slugifyDemoTitle(text: string): string {
|
|
3
|
+
return text
|
|
4
|
+
.trim()
|
|
5
|
+
.replace(/\.[jt]sx?$/i, '')
|
|
6
|
+
.toLowerCase()
|
|
7
|
+
.replace(/['’]/g, '')
|
|
8
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
9
|
+
.replace(/^-+|-+$/g, '');
|
|
10
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The import-map side of the demo build: every package the demos (and the
|
|
3
|
+
* iframe runtime) import becomes one ESM entry under `<outDir>/_lib/`, built
|
|
4
|
+
* in a single esbuild pass with code splitting, so React and friends exist
|
|
5
|
+
* once and are shared by every entry, demo and edited rebuild.
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import { createRequire } from 'node:module';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { pathToFileURL } from 'node:url';
|
|
11
|
+
import type { Plugin } from 'esbuild';
|
|
12
|
+
|
|
13
|
+
import { matchesStub } from './compile/core.ts';
|
|
14
|
+
import type { LibrarySource } from './config.ts';
|
|
15
|
+
|
|
16
|
+
const VALID_IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
17
|
+
const RESERVED = new Set(
|
|
18
|
+
'break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await'.split(
|
|
19
|
+
' ',
|
|
20
|
+
),
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
/** `@scope/pkg/sub` → `scope__pkg__sub`, safe as an output file name. */
|
|
24
|
+
export function entryNameFor(specifier: string): string {
|
|
25
|
+
return specifier.replace(/^@/, '').replace(/\//g, '__').replace(/[^\w.-]/g, '_');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type ExportShape = { names: string[]; hasDefault: boolean } | null;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Export names of an npm package, read by loading it in Node. CommonJS
|
|
32
|
+
* packages (React…) have no static ESM names, so the wrapper entry lists them.
|
|
33
|
+
*/
|
|
34
|
+
async function readExportShape(specifier: string, root: string, nodePaths: string[]): Promise<ExportShape> {
|
|
35
|
+
const require = createRequire(path.join(root, 'package.json'));
|
|
36
|
+
let resolved: string;
|
|
37
|
+
try {
|
|
38
|
+
resolved = require.resolve(specifier, { paths: [root, ...nodePaths.map((p) => path.dirname(p))] });
|
|
39
|
+
} catch {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
let mod: unknown;
|
|
43
|
+
try {
|
|
44
|
+
mod = require(resolved);
|
|
45
|
+
} catch {
|
|
46
|
+
try {
|
|
47
|
+
mod = await import(pathToFileURL(resolved).href);
|
|
48
|
+
} catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (mod == null || (typeof mod !== 'object' && typeof mod !== 'function')) {
|
|
53
|
+
return { names: [], hasDefault: true };
|
|
54
|
+
}
|
|
55
|
+
const isNamespace = (mod as { [Symbol.toStringTag]?: string })[Symbol.toStringTag] === 'Module';
|
|
56
|
+
const names = Object.keys(mod).filter(
|
|
57
|
+
(name) => name !== 'default' && name !== '__esModule' && VALID_IDENTIFIER.test(name) && !RESERVED.has(name),
|
|
58
|
+
);
|
|
59
|
+
return { names, hasDefault: isNamespace ? 'default' in (mod as object) : true };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type VendorEntries = {
|
|
63
|
+
/** esbuild entry name → wrapper file. */
|
|
64
|
+
entryPoints: Record<string, string>;
|
|
65
|
+
/** esbuild entry name → specifier. */
|
|
66
|
+
specifierByEntry: Record<string, string>;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** Writes one wrapper module per specifier into `workDir`. */
|
|
70
|
+
export async function writeVendorEntries(options: {
|
|
71
|
+
specifiers: string[];
|
|
72
|
+
libraries: Record<string, LibrarySource>;
|
|
73
|
+
root: string;
|
|
74
|
+
nodePaths: string[];
|
|
75
|
+
workDir: string;
|
|
76
|
+
warn: (message: string) => void;
|
|
77
|
+
}): Promise<VendorEntries> {
|
|
78
|
+
const { specifiers, libraries, root, nodePaths, workDir, warn } = options;
|
|
79
|
+
fs.mkdirSync(workDir, { recursive: true });
|
|
80
|
+
const entryPoints: Record<string, string> = {};
|
|
81
|
+
const specifierByEntry: Record<string, string> = {};
|
|
82
|
+
|
|
83
|
+
for (const specifier of [...specifiers].sort()) {
|
|
84
|
+
const name = entryNameFor(specifier);
|
|
85
|
+
const file = path.join(workDir, `${name}.mjs`);
|
|
86
|
+
let contents: string;
|
|
87
|
+
const library = libraries[specifier];
|
|
88
|
+
if (library) {
|
|
89
|
+
contents = `export * from ${JSON.stringify(path.resolve(root, library.entry))};\n`;
|
|
90
|
+
} else {
|
|
91
|
+
const shape = await readExportShape(specifier, root, nodePaths);
|
|
92
|
+
if (!shape) {
|
|
93
|
+
warn(`could not load "${specifier}" in Node to list its exports; re-exporting with \`export *\``);
|
|
94
|
+
contents = `export * from ${JSON.stringify(specifier)};\n`;
|
|
95
|
+
} else {
|
|
96
|
+
const lines = [`import * as __dk from ${JSON.stringify(specifier)};`];
|
|
97
|
+
if (shape.names.length) lines.push(`export const { ${shape.names.join(', ')} } = __dk;`);
|
|
98
|
+
if (shape.hasDefault) lines.push('export default __dk.default;');
|
|
99
|
+
contents = `${lines.join('\n')}\n`;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
fs.writeFileSync(file, contents);
|
|
103
|
+
entryPoints[name] = file;
|
|
104
|
+
specifierByEntry[name] = specifier;
|
|
105
|
+
}
|
|
106
|
+
return { entryPoints, specifierByEntry };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Resolves libraries to their source entries, stubs `stubImports`, and pins
|
|
111
|
+
* every import-map package to the copy resolved from the site root — a
|
|
112
|
+
* library built from another folder (e.g. `../source/src`) would otherwise
|
|
113
|
+
* bundle its own React.
|
|
114
|
+
*/
|
|
115
|
+
export function vendorResolvePlugin(options: {
|
|
116
|
+
libraries: Record<string, LibrarySource>;
|
|
117
|
+
canonical: Set<string>;
|
|
118
|
+
stubImports: string[];
|
|
119
|
+
root: string;
|
|
120
|
+
}): Plugin {
|
|
121
|
+
const { libraries, canonical, stubImports, root } = options;
|
|
122
|
+
return {
|
|
123
|
+
name: 'docs-kit:vendor-resolve',
|
|
124
|
+
setup(build) {
|
|
125
|
+
build.onResolve({ filter: /^[^./]/ }, async (args) => {
|
|
126
|
+
if (args.pluginData?.docsKitCanonical) return undefined;
|
|
127
|
+
const library = libraries[args.path];
|
|
128
|
+
if (library) return { path: path.resolve(root, library.entry) };
|
|
129
|
+
if (matchesStub(args.path, stubImports)) return { path: args.path, namespace: 'docs-kit-stub' };
|
|
130
|
+
if (!canonical.has(args.path)) return undefined;
|
|
131
|
+
const result = await build.resolve(args.path, {
|
|
132
|
+
kind: args.kind,
|
|
133
|
+
resolveDir: root,
|
|
134
|
+
pluginData: { docsKitCanonical: true },
|
|
135
|
+
});
|
|
136
|
+
if (result.errors.length) return { errors: result.errors };
|
|
137
|
+
return { path: result.path, namespace: result.namespace, sideEffects: result.sideEffects };
|
|
138
|
+
});
|
|
139
|
+
build.onLoad({ filter: /.*/, namespace: 'docs-kit-stub' }, () => ({ contents: '', loader: 'js' }));
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/// <reference lib="webworker" />
|
|
2
|
+
/**
|
|
3
|
+
* Module worker that rebuilds edited demo files with esbuild-wasm. Bundled by
|
|
4
|
+
* the demo builder into `<outDir>/_editor/compile-worker-[hash].js`; the
|
|
5
|
+
* wasm binary is passed in with the first request, so it's only downloaded
|
|
6
|
+
* when someone edits a demo.
|
|
7
|
+
*/
|
|
8
|
+
import * as esbuild from 'esbuild-wasm';
|
|
9
|
+
|
|
10
|
+
import { compileDemo, type CompileOptions, type CompileRequest } from '../compile/core.ts';
|
|
11
|
+
|
|
12
|
+
type WorkerRequest = {
|
|
13
|
+
id: number;
|
|
14
|
+
wasmURL: string;
|
|
15
|
+
request: CompileRequest;
|
|
16
|
+
options: CompileOptions;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
let ready: Promise<void> | null = null;
|
|
20
|
+
|
|
21
|
+
self.addEventListener('message', async (event: MessageEvent<WorkerRequest>) => {
|
|
22
|
+
const { id, wasmURL, request, options } = event.data;
|
|
23
|
+
try {
|
|
24
|
+
ready ??= esbuild.initialize({ wasmURL, worker: false });
|
|
25
|
+
await ready;
|
|
26
|
+
const result = await compileDemo(esbuild, request, options);
|
|
27
|
+
self.postMessage({ id, result });
|
|
28
|
+
} catch (error) {
|
|
29
|
+
ready = null;
|
|
30
|
+
self.postMessage({
|
|
31
|
+
id,
|
|
32
|
+
result: { ok: false, errors: [{ text: `The editor's compiler failed to start: ${String(error)}` }] },
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `docs-kit editor install|package`: packages the docs-kit links extension
|
|
3
|
+
* (`editor-extension/` in this package) into a .vsix with @vscode/vsce and
|
|
4
|
+
* installs it into VS Code and/or Cursor.
|
|
5
|
+
*/
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
|
|
12
|
+
/** Same folder from `src/editor/` (local mode) and `dist/editor/` (the package). */
|
|
13
|
+
const packageRoot = fileURLToPath(new URL('../../', import.meta.url));
|
|
14
|
+
export const EXTENSION_DIR = path.join(packageRoot, 'editor-extension');
|
|
15
|
+
const VSCE = '@vscode/vsce@4.1.0';
|
|
16
|
+
const FILES = ['package.json', 'extension.js', 'links.js', 'README.md'];
|
|
17
|
+
|
|
18
|
+
export type Editor = 'code' | 'cursor';
|
|
19
|
+
|
|
20
|
+
const APP_BINARIES: Record<Editor, string[]> = {
|
|
21
|
+
code: ['/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code'],
|
|
22
|
+
cursor: ['/Applications/Cursor.app/Contents/Resources/app/bin/cursor'],
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
function onPath(command: string): string | null {
|
|
26
|
+
const result = spawnSync(process.platform === 'win32' ? 'where' : 'which', [command], { encoding: 'utf8' });
|
|
27
|
+
return result.status === 0 ? result.stdout.split(/\r?\n/)[0].trim() || null : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The CLI of each editor that is installed (`code`, `cursor`). */
|
|
31
|
+
export function findEditors(only?: Editor[]): { editor: Editor; bin: string }[] {
|
|
32
|
+
return (Object.keys(APP_BINARIES) as Editor[])
|
|
33
|
+
.filter((editor) => !only?.length || only.includes(editor))
|
|
34
|
+
.flatMap((editor) => {
|
|
35
|
+
const bin = onPath(editor) ?? APP_BINARIES[editor].find((file) => fs.existsSync(file));
|
|
36
|
+
return bin ? [{ editor, bin }] : [];
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Packages the extension, versioned like this docs-kit, into `outFile` (default: a temp file). */
|
|
41
|
+
export function packageExtension(outFile?: string): string {
|
|
42
|
+
const { version } = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8')) as {
|
|
43
|
+
version: string;
|
|
44
|
+
};
|
|
45
|
+
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'docs-kit-editor-'));
|
|
46
|
+
for (const file of FILES) fs.copyFileSync(path.join(EXTENSION_DIR, file), path.join(work, file));
|
|
47
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(work, 'package.json'), 'utf8')) as { version: string };
|
|
48
|
+
manifest.version = version;
|
|
49
|
+
fs.writeFileSync(path.join(work, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
50
|
+
|
|
51
|
+
const out = path.resolve(outFile ?? path.join(work, `docs-kit-links-${version}.vsix`));
|
|
52
|
+
const result = spawnSync(
|
|
53
|
+
'npx',
|
|
54
|
+
['--yes', VSCE, 'package', '--no-dependencies', '--skip-license', '--allow-missing-repository', '-o', out],
|
|
55
|
+
{ cwd: work, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', shell: process.platform === 'win32' },
|
|
56
|
+
);
|
|
57
|
+
if (result.status !== 0 || !fs.existsSync(out)) {
|
|
58
|
+
throw new Error(`[docs-kit] packaging the editor extension failed:\n${result.stdout}${result.stderr}`);
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Packages the extension and installs it into each editor found (or the ones in `only`). */
|
|
64
|
+
export function installExtension(only?: Editor[], log: (message: string) => void = console.log) {
|
|
65
|
+
const editors = findEditors(only);
|
|
66
|
+
const vsix = packageExtension();
|
|
67
|
+
if (!editors.length) {
|
|
68
|
+
log(
|
|
69
|
+
`[docs-kit] no VS Code or Cursor CLI found. Install ${vsix} from the editor ` +
|
|
70
|
+
'(Extensions → … → Install from VSIX).',
|
|
71
|
+
);
|
|
72
|
+
return { vsix, installed: [] as Editor[] };
|
|
73
|
+
}
|
|
74
|
+
const installed: Editor[] = [];
|
|
75
|
+
for (const { editor, bin } of editors) {
|
|
76
|
+
const result = spawnSync(bin, ['--install-extension', vsix, '--force'], { encoding: 'utf8' });
|
|
77
|
+
if (result.status === 0) {
|
|
78
|
+
installed.push(editor);
|
|
79
|
+
log(`[docs-kit] installed the docs-kit links extension in ${editor}. Reload its windows to use it.`);
|
|
80
|
+
} else {
|
|
81
|
+
log(`[docs-kit] installing in ${editor} failed:\n${result.stdout}${result.stderr}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return { vsix, installed };
|
|
85
|
+
}
|