@pstdio/canvas 0.45.0 → 0.46.0-nightly.20261031030226
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/README.md +2 -2
- package/package.json +1 -1
- package/src/compose.ts +43 -43
- package/src/index.ts +1 -0
- package/src/indexer.ts +3 -2
- package/src/native-preview-runtime.tsx +16 -5
- package/src/project/bundle.ts +27 -4
- package/src/project/index-canvas-file.ts +2 -0
- package/src/project/inputs.ts +26 -11
- package/src/project/manifest.ts +2 -0
- package/src/project/react-base.ts +38 -0
- package/src/runtime/assets.ts +49 -0
- package/src/runtime/frame-runtime.tsx +35 -17
- package/src/runtime/live-frame.tsx +44 -0
- package/src/runtime/protocol.ts +7 -5
package/README.md
CHANGED
|
@@ -74,7 +74,7 @@ import { ThemeProvider } from "../src/theme";
|
|
|
74
74
|
export default {
|
|
75
75
|
decorators: [
|
|
76
76
|
(Frame, { theme }) => (
|
|
77
|
-
<ThemeProvider mode={theme}>
|
|
77
|
+
<ThemeProvider mode={theme.mode}>
|
|
78
78
|
<Frame />
|
|
79
79
|
</ThemeProvider>
|
|
80
80
|
),
|
|
@@ -82,7 +82,7 @@ export default {
|
|
|
82
82
|
};
|
|
83
83
|
```
|
|
84
84
|
|
|
85
|
-
A decorator is `(Frame, context) => element`, where `context` is `{ theme, args }`
|
|
85
|
+
A decorator is `(Frame, context) => element`, where `context` is `{ theme, args }`. `theme` is the theme the host chose for the frame: `{ id, mode, tokens? }`, where `mode` is `"light"` or `"dark"` and `tokens` carries a theme's own values, such as a VS Code theme's. Canvas passes it through unchanged; apply it with your project's theme provider. Decorators run from the outside in: `.canvas/preview.tsx`, then the file's default export, then the frame.
|
|
86
86
|
|
|
87
87
|
## Types
|
|
88
88
|
|
package/package.json
CHANGED
package/src/compose.ts
CHANGED
|
@@ -8,76 +8,76 @@ type Props<T> =
|
|
|
8
8
|
: T extends { args: infer P }
|
|
9
9
|
? P
|
|
10
10
|
: T;
|
|
11
|
-
|
|
11
|
+
/**
|
|
12
|
+
* The theme the host chose for a frame. Canvas passes it through unchanged; each project applies
|
|
13
|
+
* it with its own theme provider. `tokens` carries a theme's own values, such as a VS Code theme's.
|
|
14
|
+
*/
|
|
15
|
+
export interface CanvasTheme {
|
|
16
|
+
id: string;
|
|
17
|
+
mode: "light" | "dark";
|
|
18
|
+
tokens?: Record<string, string>;
|
|
19
|
+
}
|
|
12
20
|
export interface CanvasContext {
|
|
13
21
|
args: Record<string, any>;
|
|
14
|
-
/** The frame's theme switch. Decorators use it to set the project's own theme provider. */
|
|
15
22
|
theme: CanvasTheme;
|
|
16
23
|
}
|
|
17
24
|
/** Provided by the frame runtime; previews outside a frame render light. */
|
|
18
|
-
export const CanvasThemeContext = createContext<CanvasTheme>("light");
|
|
25
|
+
export const CanvasThemeContext = createContext<CanvasTheme>({ id: "light", mode: "light" });
|
|
19
26
|
export type CanvasRender<T = any> = (args: Props<T>, context: CanvasContext) => ReactNode;
|
|
20
27
|
export type CanvasDecorator = (Preview: (props?: any) => ReactNode, context: CanvasContext) => ReactNode;
|
|
21
|
-
|
|
28
|
+
/** An object frame: Canvas renders `render(args)`, or the canvas `component` with `args`. */
|
|
29
|
+
export interface CanvasFrame<T = any> {
|
|
22
30
|
id?: string;
|
|
23
31
|
name?: string;
|
|
24
32
|
args?: Partial<Props<T>>;
|
|
25
33
|
render?: CanvasRender<T>;
|
|
26
34
|
decorators?: CanvasDecorator[];
|
|
27
35
|
description?: string;
|
|
36
|
+
/** The frame's initial theme, before a saved user choice. */
|
|
37
|
+
defaultTheme?: string;
|
|
28
38
|
/** The frame is at least as tall as the Canvas viewport, for full-page previews. */
|
|
29
39
|
fullscreen?: boolean;
|
|
30
|
-
setup?: () =>
|
|
31
|
-
| { args?: Record<string, any>; dispose?: () => void }
|
|
32
|
-
| Promise<{ args?: Record<string, any>; dispose?: () => void }>;
|
|
33
40
|
}
|
|
34
|
-
|
|
41
|
+
/** The default export of a canvas file. */
|
|
42
|
+
export interface CanvasMeta<T = any> extends CanvasFrame<T> {
|
|
35
43
|
title?: string;
|
|
36
44
|
component?: ComponentType<Props<T>>;
|
|
37
45
|
}
|
|
38
|
-
export type CanvasProject = Omit<CanvasVariant, "render">;
|
|
39
|
-
/** One frame: a component with no props, or an object rendering `render(args)` or `component`. */
|
|
40
|
-
export type CanvasFrame<T = any> = CanvasVariant<T> | ComponentType;
|
|
41
46
|
/** The default export of `.canvas/preview.tsx`. */
|
|
42
|
-
export
|
|
47
|
+
export interface CanvasPreview {
|
|
48
|
+
decorators?: CanvasDecorator[];
|
|
49
|
+
}
|
|
43
50
|
|
|
44
|
-
|
|
45
|
-
|
|
51
|
+
// The args and theme of the frame being rendered. Layers read them here, so each layer's component
|
|
52
|
+
// stays the same across renders and React keeps the state inside the frame.
|
|
53
|
+
const FrameContext = createContext<CanvasContext>({ args: {}, theme: { id: "light", mode: "light" } });
|
|
54
|
+
|
|
55
|
+
export const composePreview = (
|
|
56
|
+
frame: CanvasFrame | CanvasRender,
|
|
46
57
|
meta: CanvasMeta = {},
|
|
47
|
-
|
|
58
|
+
preview: CanvasPreview = {},
|
|
48
59
|
) => {
|
|
49
|
-
const example = typeof
|
|
50
|
-
const
|
|
51
|
-
const cleanups: (() => void)[] = [];
|
|
52
|
-
let disposed = false;
|
|
53
|
-
const dispose = () => {
|
|
54
|
-
if (disposed) return;
|
|
55
|
-
disposed = true;
|
|
56
|
-
for (const cleanup of cleanups.reverse()) cleanup();
|
|
57
|
-
};
|
|
58
|
-
try {
|
|
59
|
-
for (const source of [project, meta, example]) {
|
|
60
|
-
const setup = await source.setup?.();
|
|
61
|
-
if (setup?.dispose) cleanups.push(setup.dispose);
|
|
62
|
-
Object.assign(context.args, setup?.args);
|
|
63
|
-
}
|
|
64
|
-
} catch (error) {
|
|
65
|
-
dispose();
|
|
66
|
-
throw error;
|
|
67
|
-
}
|
|
60
|
+
const example = typeof frame === "function" ? { render: frame } : frame;
|
|
61
|
+
const args = { ...meta.args, ...example.args };
|
|
68
62
|
const render = example.render ?? meta.render;
|
|
69
|
-
const decorators = [...(
|
|
70
|
-
const
|
|
71
|
-
const current
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
63
|
+
const decorators = [...(preview.decorators ?? []), ...(meta.decorators ?? []), ...(example.decorators ?? [])];
|
|
64
|
+
const Body = () => {
|
|
65
|
+
const current = useContext(FrameContext);
|
|
66
|
+
return render ? render(current.args, current) : createElement(meta.component ?? (() => null), current.args);
|
|
67
|
+
};
|
|
68
|
+
// Built once per preview: a decorator always receives the same inner component.
|
|
69
|
+
const Decorated = decorators.reduceRight<() => ReactNode>((Inner, decorator) => {
|
|
70
|
+
const Layer = () => decorator(Inner, useContext(FrameContext));
|
|
71
|
+
return Layer;
|
|
72
|
+
}, Body);
|
|
73
|
+
const Component = (props: Record<string, unknown>) => {
|
|
74
|
+
const current: CanvasContext = { args: { ...args, ...props }, theme: useContext(CanvasThemeContext) };
|
|
75
|
+
return createElement(FrameContext.Provider, { value: current }, createElement(Decorated));
|
|
75
76
|
};
|
|
76
77
|
return {
|
|
77
78
|
Component,
|
|
78
|
-
args
|
|
79
|
+
args,
|
|
79
80
|
description: example.description,
|
|
80
|
-
fullscreen: example.fullscreen ?? meta.fullscreen ??
|
|
81
|
-
dispose,
|
|
81
|
+
fullscreen: example.fullscreen ?? meta.fullscreen ?? false,
|
|
82
82
|
};
|
|
83
83
|
};
|
package/src/index.ts
CHANGED
package/src/indexer.ts
CHANGED
|
@@ -39,7 +39,7 @@ export const indexExamples = (path: string, source: string) => {
|
|
|
39
39
|
const defaults = file.statements.find(ts.isExportAssignment);
|
|
40
40
|
const meta = object(defaults?.expression);
|
|
41
41
|
const component = property(meta, "component")?.getText(file);
|
|
42
|
-
const stories: { exportName: string; id: string; name: string }[] = [];
|
|
42
|
+
const stories: { exportName: string; id: string; name: string; defaultTheme?: string }[] = [];
|
|
43
43
|
for (const statement of file.statements) {
|
|
44
44
|
if (
|
|
45
45
|
!ts.isVariableStatement(statement) ||
|
|
@@ -52,7 +52,8 @@ export const indexExamples = (path: string, source: string) => {
|
|
|
52
52
|
if (!id) continue;
|
|
53
53
|
const exportName = declaration.name.getText(file);
|
|
54
54
|
const name = text(property(value, "name")) ?? exportName.replace(/([a-z\d])([A-Z])/g, "$1 $2");
|
|
55
|
-
|
|
55
|
+
const defaultTheme = text(property(value, "defaultTheme")) ?? text(property(meta, "defaultTheme"));
|
|
56
|
+
stories.push({ exportName, id, name, ...(defaultTheme ? { defaultTheme } : {}) });
|
|
56
57
|
}
|
|
57
58
|
}
|
|
58
59
|
return {
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
type CanvasFrame,
|
|
3
|
+
type CanvasMeta,
|
|
4
|
+
type CanvasPreview,
|
|
5
|
+
CanvasThemeContext,
|
|
6
|
+
composePreview,
|
|
7
|
+
} from "@pstdio/canvas";
|
|
2
8
|
|
|
3
9
|
interface PreviewInput {
|
|
4
10
|
kind: string;
|
|
@@ -21,10 +27,15 @@ export const createPreviewLoader =
|
|
|
21
27
|
if (!module[exportName]) throw new Error(`Missing preview: ${input.source}#${exportName}`);
|
|
22
28
|
const importedAt = performance.now();
|
|
23
29
|
imported();
|
|
24
|
-
const preview =
|
|
25
|
-
module[exportName] as
|
|
30
|
+
const preview = composePreview(
|
|
31
|
+
module[exportName] as CanvasFrame,
|
|
26
32
|
module.default as CanvasMeta,
|
|
27
|
-
project as
|
|
33
|
+
project as CanvasPreview,
|
|
28
34
|
);
|
|
29
|
-
|
|
35
|
+
// A preview with decorators themes its frames from this context; the runtime themes the others.
|
|
36
|
+
return {
|
|
37
|
+
...preview,
|
|
38
|
+
ThemeProvider: (project as CanvasPreview).decorators?.length ? CanvasThemeContext.Provider : undefined,
|
|
39
|
+
timings: { importMs: importedAt - started, setupMs: performance.now() - importedAt },
|
|
40
|
+
};
|
|
30
41
|
};
|
package/src/project/bundle.ts
CHANGED
|
@@ -1,17 +1,40 @@
|
|
|
1
1
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
2
|
-
import { join, resolve } from "node:path";
|
|
2
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
3
3
|
import type { CanvasEntry } from "./manifest";
|
|
4
|
+
import { reactBase } from "./react-base";
|
|
4
5
|
|
|
5
6
|
const RUNTIME = resolve(import.meta.dir, "../runtime/frame-runtime.tsx");
|
|
6
7
|
|
|
7
8
|
// The runtime lives in this package, but every frame must share the project's single React.
|
|
8
|
-
const projectReact = (
|
|
9
|
+
const projectReact = (base: string): Bun.BunPlugin => ({
|
|
9
10
|
name: "pstdio-canvas-project-react",
|
|
10
11
|
setup(build) {
|
|
11
|
-
build.onResolve({ filter: /^react(-dom)?($|\/)/ }, (args) => ({ path: Bun.resolveSync(args.path,
|
|
12
|
+
build.onResolve({ filter: /^react(-dom)?($|\/)/ }, (args) => ({ path: Bun.resolveSync(args.path, base) }));
|
|
12
13
|
},
|
|
13
14
|
});
|
|
14
15
|
|
|
16
|
+
// Vite's `?raw` (file text) and `?url` (file address) imports are common in React projects.
|
|
17
|
+
// Frames load from blob URLs, so a `?url` import becomes a data URL.
|
|
18
|
+
const queryImports: Bun.BunPlugin = {
|
|
19
|
+
name: "pstdio-canvas-query-imports",
|
|
20
|
+
setup(build) {
|
|
21
|
+
build.onResolve({ filter: /\?(raw|url)$/ }, (args) => {
|
|
22
|
+
const [specifier, query] = args.path.split("?") as [string, "raw" | "url"];
|
|
23
|
+
return { path: Bun.resolveSync(specifier, dirname(args.importer)), namespace: `canvas-${query}` };
|
|
24
|
+
});
|
|
25
|
+
build.onLoad({ filter: /.*/, namespace: "canvas-raw" }, async (args) => ({
|
|
26
|
+
contents: `export default ${JSON.stringify(await Bun.file(args.path).text())};`,
|
|
27
|
+
loader: "js",
|
|
28
|
+
}));
|
|
29
|
+
build.onLoad({ filter: /.*/, namespace: "canvas-url" }, async (args) => {
|
|
30
|
+
const file = Bun.file(args.path);
|
|
31
|
+
const type = ASSET_TYPES[extname(args.path).slice(1).toLowerCase()] ?? file.type;
|
|
32
|
+
const data = Buffer.from(await file.arrayBuffer()).toString("base64");
|
|
33
|
+
return { contents: `export default ${JSON.stringify(`data:${type};base64,${data}`)};`, loader: "js" };
|
|
34
|
+
});
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
|
|
15
38
|
const ownFiles = (root: string, canvas: CanvasEntry) =>
|
|
16
39
|
new Set([join(root, canvas.id), ...(canvas.preview ? [join(root, canvas.preview)] : [])]);
|
|
17
40
|
|
|
@@ -74,7 +97,7 @@ const bunBuild = (root: string, entry: string, canvases: CanvasEntry[], outdir?:
|
|
|
74
97
|
define: { "process.env.NODE_ENV": '"production"' },
|
|
75
98
|
naming: { entry: "[name]-[hash].[ext]", chunk: "chunk-[hash].[ext]", asset: "[name]-[hash].[ext]" },
|
|
76
99
|
loader,
|
|
77
|
-
plugins: [projectReact(root)],
|
|
100
|
+
plugins: [projectReact(reactBase(root, canvases)), queryImports],
|
|
78
101
|
});
|
|
79
102
|
|
|
80
103
|
type BuildLogs = Bun.BuildOutput["logs"];
|
|
@@ -108,11 +108,13 @@ export const indexCanvasFile = (path: string, source: string) => {
|
|
|
108
108
|
const index = readSource(path, source);
|
|
109
109
|
const meta = resolveValue(index, index.file.statements.find(ts.isExportAssignment)?.expression);
|
|
110
110
|
const metaFullscreen = flag(property(index, meta, "fullscreen"));
|
|
111
|
+
const metaTheme = text(property(index, meta, "defaultTheme"));
|
|
111
112
|
const frames = frameExports(index).map(({ exportName, value }) => ({
|
|
112
113
|
exportName,
|
|
113
114
|
name: text(property(index, value, "name")) ?? sentenceCase(exportName),
|
|
114
115
|
description: text(property(index, value, "description")),
|
|
115
116
|
fullscreen: flag(property(index, value, "fullscreen")) ?? metaFullscreen,
|
|
117
|
+
defaultTheme: text(property(index, value, "defaultTheme")) ?? metaTheme,
|
|
116
118
|
}));
|
|
117
119
|
const fileName = path
|
|
118
120
|
.split("/")
|
package/src/project/inputs.ts
CHANGED
|
@@ -21,24 +21,35 @@ const packageFolder = (file: string) => {
|
|
|
21
21
|
return parts.slice(0, index + (parts[index + 1]?.startsWith("@") ? 3 : 2)).join("/");
|
|
22
22
|
};
|
|
23
23
|
|
|
24
|
-
// Installing a package adds an entry to a `node_modules` folder the project's files resolve from
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
// Installing a package adds an entry to a `node_modules` folder the project's files resolve from,
|
|
25
|
+
// and a `tsconfig.json` between a source and the root can change how its imports resolve.
|
|
26
|
+
const resolutionFiles = (root: string, sources: string[]) => {
|
|
27
|
+
const files = new Set<string>();
|
|
27
28
|
const visited = new Set<string>();
|
|
28
29
|
for (const source of sources) {
|
|
29
30
|
for (let folder = dirname(source); !visited.has(folder); folder = dirname(folder)) {
|
|
30
31
|
visited.add(folder);
|
|
31
|
-
if (existsSync(join(folder, "node_modules")))
|
|
32
|
+
if (existsSync(join(folder, "node_modules"))) files.add(join(folder, "node_modules"));
|
|
33
|
+
// Tracked even when absent: creating one changes how imports resolve.
|
|
34
|
+
files.add(join(folder, "tsconfig.json"));
|
|
32
35
|
if (folder === root || dirname(folder) === folder) break;
|
|
33
36
|
}
|
|
34
37
|
}
|
|
35
|
-
return
|
|
38
|
+
return files;
|
|
36
39
|
};
|
|
37
40
|
|
|
41
|
+
// A new version of this builder can build the same sources differently.
|
|
42
|
+
const BUILDER_ROOT = resolve(import.meta.dir, "..");
|
|
43
|
+
const builderFiles = () =>
|
|
44
|
+
[...new Bun.Glob("**/*.{ts,tsx}").scanSync(BUILDER_ROOT)]
|
|
45
|
+
.filter((file) => !/\.(test|spec)\.tsx?$/.test(file))
|
|
46
|
+
.map((file) => join(BUILDER_ROOT, file));
|
|
47
|
+
|
|
38
48
|
/**
|
|
39
49
|
* Every file whose change can change the build: the sources it read, wherever they live, files that
|
|
40
50
|
* broke it, the project's package manifests and lockfiles, the manifests of the packages it
|
|
41
|
-
* resolved,
|
|
51
|
+
* resolved, the `node_modules` folders new packages are installed into, the `tsconfig.json` files
|
|
52
|
+
* that resolve its imports, and the builder's own source.
|
|
42
53
|
*/
|
|
43
54
|
export const collectInputs = (root: string, read: string[], canvases: CanvasEntry[], failedFiles: Set<string>) => {
|
|
44
55
|
const sources = [
|
|
@@ -49,19 +60,23 @@ export const collectInputs = (root: string, read: string[], canvases: CanvasEntr
|
|
|
49
60
|
const packages = read.filter(inNodeModules).map((file) => join(packageFolder(file), "package.json"));
|
|
50
61
|
const projectFiles = PROJECT_FILES.map((name) => join(root, name)).filter((file) => existsSync(file));
|
|
51
62
|
return new Set(
|
|
52
|
-
[...sources, ...projectFiles, ...packages, ...
|
|
63
|
+
[...sources, ...projectFiles, ...packages, ...resolutionFiles(root, sources), ...builderFiles()].map((file) =>
|
|
64
|
+
resolve(file),
|
|
65
|
+
),
|
|
53
66
|
);
|
|
54
67
|
};
|
|
55
68
|
|
|
56
69
|
/**
|
|
57
|
-
* Modification times keyed by `inputKey
|
|
58
|
-
* before or after the change, so it is recorded as unknown and
|
|
70
|
+
* Modification times keyed by `inputKey`; 0 marks a file that does not exist. A file changed at or
|
|
71
|
+
* after `startedAt` may have been read before or after the change, so it is recorded as unknown and
|
|
72
|
+
* the next check rebuilds.
|
|
59
73
|
*/
|
|
60
74
|
export const readInputs = async (root: string, files: Set<string>, startedAt: number) => {
|
|
61
75
|
const inputs: Record<string, number> = {};
|
|
62
76
|
for (const file of [...files].sort()) {
|
|
63
77
|
const info = await stat(file).catch(() => undefined);
|
|
64
|
-
if (info) inputs[inputKey(root, file)] =
|
|
78
|
+
if (!info) inputs[inputKey(root, file)] = 0;
|
|
79
|
+
else inputs[inputKey(root, file)] = info.mtimeMs >= startedAt ? -1 : info.mtimeMs;
|
|
65
80
|
}
|
|
66
81
|
return inputs;
|
|
67
82
|
};
|
|
@@ -70,7 +85,7 @@ export const readInputs = async (root: string, files: Set<string>, startedAt: nu
|
|
|
70
85
|
export const inputsUnchanged = async (root: string, inputs: Record<string, number>) => {
|
|
71
86
|
for (const [key, modified] of Object.entries(inputs)) {
|
|
72
87
|
const info = await stat(inputPath(root, key)).catch(() => undefined);
|
|
73
|
-
if (info?.mtimeMs !== modified) return false;
|
|
88
|
+
if ((info?.mtimeMs ?? 0) !== modified) return false;
|
|
74
89
|
}
|
|
75
90
|
return true;
|
|
76
91
|
};
|
package/src/project/manifest.ts
CHANGED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import type { CanvasEntry } from "./manifest";
|
|
4
|
+
|
|
5
|
+
// The React a folder resolves, when it resolves both `react` and `react-dom`.
|
|
6
|
+
const reactAt = (folder: string) => {
|
|
7
|
+
try {
|
|
8
|
+
const manifest = Bun.resolveSync("react/package.json", folder);
|
|
9
|
+
Bun.resolveSync("react-dom/package.json", folder);
|
|
10
|
+
return {
|
|
11
|
+
folder,
|
|
12
|
+
path: realpathSync(dirname(manifest)),
|
|
13
|
+
version: JSON.parse(readFileSync(manifest, "utf8")).version,
|
|
14
|
+
};
|
|
15
|
+
} catch {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The folder every frame resolves React from, so a page loads one React: the project root, or in a
|
|
22
|
+
* monorepo without a root install, the folder most canvas files resolve React from.
|
|
23
|
+
*/
|
|
24
|
+
export const reactBase = (root: string, canvases: CanvasEntry[]) => {
|
|
25
|
+
if (reactAt(root)) return root;
|
|
26
|
+
const found = canvases.flatMap((canvas) => reactAt(dirname(join(root, canvas.id))) ?? []);
|
|
27
|
+
// Without any React, each canvas reports the missing package itself.
|
|
28
|
+
if (!found.length) return root;
|
|
29
|
+
const versions = [...new Set(found.map((entry) => entry.version))];
|
|
30
|
+
if (versions.length > 1)
|
|
31
|
+
throw new Error(
|
|
32
|
+
`Canvas files resolve different React versions (${versions.join(", ")}). Frames share one React, so install one React version for every canvas file.`,
|
|
33
|
+
);
|
|
34
|
+
const counts = new Map<string, number>();
|
|
35
|
+
for (const entry of found) counts.set(entry.path, (counts.get(entry.path) ?? 0) + 1);
|
|
36
|
+
const [mostUsed] = [...counts].sort((a, b) => b[1] - a[1])[0]!;
|
|
37
|
+
return found.find((entry) => entry.path === mostUsed)!.folder;
|
|
38
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { FrameRequest } from "./protocol";
|
|
2
|
+
|
|
3
|
+
export interface FrameBootstrap {
|
|
4
|
+
scripts: Record<string, Blob>;
|
|
5
|
+
styles: Blob[];
|
|
6
|
+
entry: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
let load: ((source: string) => Promise<FrameBootstrap>) | undefined;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Code for a Canvas frame rendered inside this frame, such as UI Canvas's own canvases. Only frames
|
|
13
|
+
* whose code calls this function use the bridge: UI Canvas's frame component still uses its own
|
|
14
|
+
* loader, so its canvases show "Preview asset loader is unavailable" in a package build until UI
|
|
15
|
+
* Canvas imports this function from `@pstdio/canvas`.
|
|
16
|
+
*/
|
|
17
|
+
export const frameBootstrap = (source: string) => {
|
|
18
|
+
if (!load) return Promise.reject(new Error("Preview asset loader is unavailable"));
|
|
19
|
+
return load(source);
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// A nested frame asks the frame that hosts it for code; this frame forwards the request to its own
|
|
23
|
+
// host, so sandboxed frames keep their opaque origins.
|
|
24
|
+
export const createFrameAssetBridge = (
|
|
25
|
+
send: (request: { type: "assets"; requestId: string; source: string }) => void,
|
|
26
|
+
) => {
|
|
27
|
+
const pending = new Map<string, { resolve: (value: FrameBootstrap) => void; reject: (error: Error) => void }>();
|
|
28
|
+
const loader = (source: string) =>
|
|
29
|
+
new Promise<FrameBootstrap>((resolve, reject) => {
|
|
30
|
+
const requestId = crypto.randomUUID();
|
|
31
|
+
pending.set(requestId, { resolve, reject });
|
|
32
|
+
send({ type: "assets", requestId, source });
|
|
33
|
+
});
|
|
34
|
+
load = loader;
|
|
35
|
+
return {
|
|
36
|
+
receive: (message: FrameRequest) => {
|
|
37
|
+
const request = pending.get(message.requestId!);
|
|
38
|
+
if (!request) return;
|
|
39
|
+
pending.delete(message.requestId!);
|
|
40
|
+
if (message.error) request.reject(new Error(message.error));
|
|
41
|
+
else if (message.bootstrap) request.resolve(message.bootstrap);
|
|
42
|
+
},
|
|
43
|
+
dispose: () => {
|
|
44
|
+
if (load === loader) load = undefined;
|
|
45
|
+
for (const request of pending.values()) request.reject(new Error("Preview closed"));
|
|
46
|
+
pending.clear();
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
};
|
|
@@ -1,12 +1,8 @@
|
|
|
1
1
|
import { Component, type ReactNode, useLayoutEffect } from "react";
|
|
2
2
|
import { createRoot } from "react-dom/client";
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
CanvasThemeContext,
|
|
7
|
-
type CanvasVariant,
|
|
8
|
-
composePreview,
|
|
9
|
-
} from "../compose";
|
|
3
|
+
import { type CanvasFrame, type CanvasMeta, type CanvasPreview, CanvasThemeContext, composePreview } from "../compose";
|
|
4
|
+
import { createFrameAssetBridge } from "./assets";
|
|
5
|
+
import { LiveFrame } from "./live-frame";
|
|
10
6
|
import { installFrameNavigation } from "./navigation";
|
|
11
7
|
import { type FrameItem, type FrameMessage, type FrameRequest, type FrameTheme, frameProtocol } from "./protocol";
|
|
12
8
|
|
|
@@ -16,6 +12,13 @@ export interface FrameSource {
|
|
|
16
12
|
preview?: () => Promise<{ default?: unknown }>;
|
|
17
13
|
}
|
|
18
14
|
|
|
15
|
+
// Zag and Ark components mark open overlays with `data-state`; plain ARIA dialogs mark themselves modal.
|
|
16
|
+
const MODAL_SELECTOR = [
|
|
17
|
+
...["dialog", "popover", "menu"].map((scope) => `[data-scope="${scope}"][data-state="open"]`),
|
|
18
|
+
'[role="dialog"][aria-modal="true"]',
|
|
19
|
+
'[role="alertdialog"]',
|
|
20
|
+
].join(", ");
|
|
21
|
+
|
|
19
22
|
type LoadedFrame = Awaited<ReturnType<typeof composePreview>> & { timings: Record<string, number> };
|
|
20
23
|
|
|
21
24
|
const inspect = (value: unknown) => {
|
|
@@ -41,6 +44,7 @@ export const mountFrameRuntime = (sources: Record<string, FrameSource>) => {
|
|
|
41
44
|
let nonce = "";
|
|
42
45
|
const send = (message: Omit<FrameMessage, "protocol" | "nonce">) =>
|
|
43
46
|
window.parent.postMessage({ protocol: frameProtocol, nonce, ...message }, "*");
|
|
47
|
+
const assets = createFrameAssetBridge(send);
|
|
44
48
|
|
|
45
49
|
class Boundary extends Component<{ children: ReactNode }, { error?: string }> {
|
|
46
50
|
state: { error?: string } = {};
|
|
@@ -77,13 +81,18 @@ export const mountFrameRuntime = (sources: Record<string, FrameSource>) => {
|
|
|
77
81
|
cancelAnimationFrame(second);
|
|
78
82
|
};
|
|
79
83
|
}, [loaded]);
|
|
80
|
-
const Frame = loaded.Component;
|
|
81
84
|
return (
|
|
82
85
|
<div
|
|
83
86
|
data-preview-content
|
|
84
|
-
|
|
87
|
+
// `alignSelf` keeps the content at its own height when project CSS stretches `#root`.
|
|
88
|
+
style={{
|
|
89
|
+
display: "grid",
|
|
90
|
+
alignSelf: "start",
|
|
91
|
+
width: "100%",
|
|
92
|
+
minHeight: minimumHeight ? `${minimumHeight}px` : undefined,
|
|
93
|
+
}}
|
|
85
94
|
>
|
|
86
|
-
<Frame />
|
|
95
|
+
<LiveFrame Frame={loaded.Component} args={loaded.args} />
|
|
87
96
|
</div>
|
|
88
97
|
);
|
|
89
98
|
};
|
|
@@ -99,10 +108,10 @@ export const mountFrameRuntime = (sources: Record<string, FrameSource>) => {
|
|
|
99
108
|
if (frame === undefined) throw new Error(`Missing preview: ${preview.source}#${preview.exportName}`);
|
|
100
109
|
send({ type: "imports-ready" });
|
|
101
110
|
const importedAt = performance.now();
|
|
102
|
-
const composed =
|
|
103
|
-
frame as
|
|
111
|
+
const composed = composePreview(
|
|
112
|
+
frame as CanvasFrame,
|
|
104
113
|
(module.default ?? {}) as CanvasMeta,
|
|
105
|
-
(project?.default ?? {}) as
|
|
114
|
+
(project?.default ?? {}) as CanvasPreview,
|
|
106
115
|
);
|
|
107
116
|
return { ...composed, timings: { importMs: importedAt - started, setupMs: performance.now() - importedAt } };
|
|
108
117
|
};
|
|
@@ -117,7 +126,7 @@ export const mountFrameRuntime = (sources: Record<string, FrameSource>) => {
|
|
|
117
126
|
if (!active || !loaded || !item) return;
|
|
118
127
|
const minimumHeight = loaded.fullscreen ? (item.preview?.viewportHeight ?? 960) : 0;
|
|
119
128
|
reactRoot.render(
|
|
120
|
-
<CanvasThemeContext.Provider value={theme
|
|
129
|
+
<CanvasThemeContext.Provider value={theme}>
|
|
121
130
|
<Boundary>
|
|
122
131
|
<Ready loaded={loaded} minimumHeight={minimumHeight} />
|
|
123
132
|
</Boundary>
|
|
@@ -130,12 +139,13 @@ export const mountFrameRuntime = (sources: Record<string, FrameSource>) => {
|
|
|
130
139
|
if (nonce && message.nonce !== nonce) return;
|
|
131
140
|
nonce = message.nonce;
|
|
132
141
|
if (message.theme) theme = message.theme;
|
|
142
|
+
if (message.type === "assets") assets.receive(message);
|
|
133
143
|
if (message.type === "theme") render();
|
|
134
144
|
if (message.type !== "render" || !message.item || item) return;
|
|
135
145
|
item = message.item;
|
|
136
146
|
void load(message.item)
|
|
137
147
|
.then((result) => {
|
|
138
|
-
if (!active) return
|
|
148
|
+
if (!active) return;
|
|
139
149
|
loaded = result;
|
|
140
150
|
render();
|
|
141
151
|
})
|
|
@@ -153,7 +163,15 @@ export const mountFrameRuntime = (sources: Record<string, FrameSource>) => {
|
|
|
153
163
|
const measure = () => {
|
|
154
164
|
cancelAnimationFrame(scheduled);
|
|
155
165
|
scheduled = requestAnimationFrame(() => {
|
|
156
|
-
|
|
166
|
+
// An open dialog, popover or menu is positioned outside the content's height, so the frame
|
|
167
|
+
// grows to the viewport while one is open.
|
|
168
|
+
const modal = document.querySelector(MODAL_SELECTOR) ? (item?.preview?.viewportHeight ?? 960) : 1;
|
|
169
|
+
// Measure the frame's content, not `#root`: project CSS often sizes `#root` to the viewport,
|
|
170
|
+
// and a frame as tall as its viewport could never shrink again.
|
|
171
|
+
const content = root.querySelector<HTMLElement>("[data-preview-content]");
|
|
172
|
+
if (content) resizeObserver.observe(content);
|
|
173
|
+
const measured = content ?? root;
|
|
174
|
+
const height = Math.ceil(Math.max(measured.offsetHeight, measured.scrollHeight, modal));
|
|
157
175
|
if (height === previous) return;
|
|
158
176
|
previous = height;
|
|
159
177
|
send({ type: "height", height });
|
|
@@ -171,12 +189,12 @@ export const mountFrameRuntime = (sources: Record<string, FrameSource>) => {
|
|
|
171
189
|
() => {
|
|
172
190
|
active = false;
|
|
173
191
|
window.removeEventListener("message", receive);
|
|
174
|
-
loaded?.dispose();
|
|
175
192
|
cancelAnimationFrame(scheduled);
|
|
176
193
|
resizeObserver.disconnect();
|
|
177
194
|
mutationObserver.disconnect();
|
|
178
195
|
document.fonts.removeEventListener("loadingdone", measure);
|
|
179
196
|
reactRoot.unmount();
|
|
197
|
+
assets.dispose();
|
|
180
198
|
},
|
|
181
199
|
{ once: true },
|
|
182
200
|
);
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type ComponentType, useState } from "react";
|
|
2
|
+
|
|
3
|
+
type Callback = (...values: any[]) => unknown;
|
|
4
|
+
|
|
5
|
+
interface LiveFrameProps {
|
|
6
|
+
Frame: ComponentType<Record<string, unknown>>;
|
|
7
|
+
args: Record<string, unknown>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// Frames keep the state their controls change, using the common React prop conventions, so a
|
|
11
|
+
// person can try an example without each canvas wiring its own state.
|
|
12
|
+
export const LiveFrame = (props: LiveFrameProps) => {
|
|
13
|
+
const { Frame } = props;
|
|
14
|
+
const [args, setArgs] = useState(props.args);
|
|
15
|
+
const [closed, setClosed] = useState(false);
|
|
16
|
+
const update = (change: Record<string, unknown>) => setArgs((current) => ({ ...current, ...change }));
|
|
17
|
+
const callbacks: Record<string, Callback> = {};
|
|
18
|
+
const chain = (name: string, apply: Callback) => {
|
|
19
|
+
callbacks[name] = (...values) => {
|
|
20
|
+
const original = args[name];
|
|
21
|
+
const result = typeof original === "function" ? original(...values) : undefined;
|
|
22
|
+
apply(...values);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
if ("value" in args) {
|
|
27
|
+
chain("onChange", (event) => update({ value: event?.target?.value ?? event }));
|
|
28
|
+
chain("onValueChange", (value) => update({ value: value?.value ?? value }));
|
|
29
|
+
}
|
|
30
|
+
if ("checked" in args) chain("onCheckedChange", (value) => update({ checked: value?.checked ?? value }));
|
|
31
|
+
if ("open" in args) chain("onOpenChange", (value) => update({ open: value?.open ?? value }));
|
|
32
|
+
if ("onClose" in args)
|
|
33
|
+
callbacks.onClose = async (...values: unknown[]) => {
|
|
34
|
+
const original = args.onClose;
|
|
35
|
+
const result = typeof original === "function" ? await original(...values) : undefined;
|
|
36
|
+
// A handler that returns false keeps the example open, as the component would.
|
|
37
|
+
if (result === false) return result;
|
|
38
|
+
if ("open" in args) update({ open: false });
|
|
39
|
+
else setClosed(true);
|
|
40
|
+
return result ?? true;
|
|
41
|
+
};
|
|
42
|
+
if (closed) return <p role="status">Example closed. Reset the frame to try it again.</p>;
|
|
43
|
+
return <Frame {...args} {...callbacks} />;
|
|
44
|
+
};
|
package/src/runtime/protocol.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
+
import type { CanvasTheme } from "../compose";
|
|
2
|
+
import type { FrameBootstrap } from "./assets";
|
|
3
|
+
|
|
1
4
|
// The messages between a UI Canvas frame and its host. They match the protocol the UI Canvas
|
|
2
5
|
// extension speaks; the extension reads these types from this package once it adopts it.
|
|
3
6
|
export const frameProtocol = "pstdio.canvas.preview";
|
|
4
7
|
|
|
5
|
-
export
|
|
6
|
-
id: string;
|
|
7
|
-
mode: "light" | "dark";
|
|
8
|
-
}
|
|
8
|
+
export type { CanvasTheme as FrameTheme } from "../compose";
|
|
9
9
|
|
|
10
10
|
export interface FrameItem {
|
|
11
11
|
preview?: { source: string; exportName: string; viewportHeight?: number };
|
|
@@ -18,7 +18,9 @@ export interface FrameRequest {
|
|
|
18
18
|
requestId?: string;
|
|
19
19
|
error?: string;
|
|
20
20
|
item?: FrameItem;
|
|
21
|
-
theme?:
|
|
21
|
+
theme?: CanvasTheme;
|
|
22
|
+
/** The answer to a nested frame's `assets` request. */
|
|
23
|
+
bootstrap?: FrameBootstrap;
|
|
22
24
|
}
|
|
23
25
|
|
|
24
26
|
export interface FrameMessage {
|