Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions docs/docs/plugins/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,10 +218,10 @@ Each page renders in its own error boundary and posts `appkit:design-ready` once

A builder can show a draft while it's still being written, instead of only once it's finished:

- Append the page's source, as it arrives, to `client/src/design/.staging/<name>.tsx` (and the shared mock's to `.staging/mock.ts`).
- Append the page's source, as it arrives, to `client/src/design/.staging/<name>.tsx`.
- Show `/design/__stream/<name>`. The dev server keeps the latest renderable version of the staging file under the page's real module (`pages/<name>.tsx`): it closes whatever is still open at the cut (JSX tags, brackets, template literals) and stubs what the page uses that hasn't arrived yet. Components not written yet show a `DraftPlaceholder` skeleton of the right shape. Each version reaches the page as a hot update, so it fills in in place, with no reload and with its state kept.
- Until `mock.ts` exists, the page's `../mock` import is what `.staging/mock.ts` has so far, plus stubs for whatever the page imports from it that isn't there yet.
- When the page type-checks, write it to `pages/<name>.tsx` (and `mock.ts`): the same module then loads from disk. Deleting the staging file starts that draft over.
- A version that imports `../mock` is published only once `mock.ts` exists, so it never shows without its data. What counts is the version as Vite compiles it, under the app's tsconfig. An `import type` compiles away. So does an inline `import { type T }`, unless `verbatimModuleSyntax` is set (as in the AppKit template), which keeps it as an import. So does an early cut that doesn't use the values it imports yet, which is published as usual. Until `mock.ts` exists, the page keeps its last version (or stays pending); the moment it lands, the latest version (or the finished page) is published. So write `mock.ts` first, as soon as it's complete.
- When the page type-checks, write it to `pages/<name>.tsx`: the same module then loads from disk. Deleting the staging file starts that draft over.

Every design page, streamed or not, renders through `DesignPage` (from `@databricks/appkit-ui/react/beta`; the plugin adds it, pages don't). It applies the app's theme before the first paint (`?theme=dark` or `?theme=light` on the URL, else the system setting), so a dark page never flashes light. If a render fails mid-stream, it keeps the last good frame on screen instead of a broken page, and holds readiness back until a render succeeds.

Expand All @@ -231,7 +231,7 @@ A builder showing a page in a frame can read what happened from markers on the p

| State | Marker | When |
| --- | --- | --- |
| pending | no `[data-design-page]` shell yet, or a shell with none of the markers below | The page hasn't loaded, or it suspended (lazy code, data) and a `Suspense` fallback shows. For `/design/__stream/<name>`: no version is published yet. |
| pending | no `[data-design-page]` shell yet, or a shell with none of the markers below | The page hasn't loaded, or it suspended (lazy code, data) and a `Suspense` fallback shows. For `/design/__stream/<name>`: no version is published yet (a version that imports `../mock` waits for `mock.ts`). |
| rendered | `[data-design-page][data-design-rendered]` | The page committed a render without an error (set in an effect after mount). A page that renders an empty element counts: that's its own output. |
| last-good | `[data-design-last-good]` inside the shell | A render error once the page has shown: a copy of it as it was on screen when the error came (or, if a `Suspense` fallback had replaced it, as it last showed). No `data-design-rendered`. |
| error | `[data-design-error]` inside the shell, with the message | A render error before any good render, or, on a stream page, a published version that fails to load or evaluate (shown at once). No `data-design-rendered`. |
Expand All @@ -245,6 +245,7 @@ What moves a page between them:
| pending | The page renders (an empty page too) | rendered |
| pending | It throws while rendering, or (stream) the published version fails to load or evaluate | error |
| pending | It suspends | pending, the fallback on screen |
| pending or rendered | (stream) A version imports `../mock` before `mock.ts` exists | unchanged (pending, or the last version); once `mock.ts` lands, the latest version (or the finished page) is published |
| pending | (stream) An import fails before any version is out | pending (the server is asked again, in case a publish came before the page listened) |
| pending, the fallback on screen | It shows, or throws | rendered, or error (the fallback is never copied) |
| rendered (from its first commit) | It or an update throws, at once or later (a timer, data), also in the task it committed in | last-good: the frame on screen, that update's included |
Expand Down
89 changes: 33 additions & 56 deletions packages/appkit/src/plugins/design/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
* `.staging/<name>.tsx` is served as `pages/<name>.tsx` and hot-swapped in place.
*/

import path from "node:path";

type Frame =
| { k: "brace" | "paren" | "bracket" | "tpl" | "tplExpr" | "jsxExpr" }
| { k: "tag" | "el"; name: string };
Expand Down Expand Up @@ -279,13 +281,7 @@ const MAX_CUTS = 60;
export async function renderablePartial(
source: string,
isValid: IsValid,
{
page = true,
complete = false,
}: {
page?: boolean;
complete?: boolean;
} = {},
{ complete = false }: { complete?: boolean } = {},
): Promise<string | null> {
const src = stripFence(source);
if (complete && (await isValid(src))) return src;
Expand All @@ -294,67 +290,48 @@ export async function renderablePartial(
let end = lines.length - 1;
for (let tries = 0; end > 0 && tries < MAX_CUTS; end--, tries++) {
const cut = lines.slice(0, end).join("\n");
if (page && !/export\s+default\b/.test(cut)) return null;
if (!/export\s+default\b/.test(cut)) return null;
const closed = closeOpen(cut);
if (closed === null) continue;
const code = page ? stubComponents(closed) : closed;
const code = stubComponents(closed);
if (await isValid(code)) return code;
}
return null;
}

/** Value names a page imports from `../<mock>` (type-only imports excluded). */
export function mockImports(page: string, mock = "mock"): string[] {
const names: string[] = [];
for (const m of page.matchAll(
/import\s*\{([^}]*)\}\s*from\s*["']\.\.\/([\w-]+?)(?:\.ts)?["']/g,
)) {
if (m[2] !== mock) continue;
for (const spec of m[1].split(",")) {
const s = spec.trim();
if (!s || s.startsWith("type ")) continue;
names.push(s.split(/\s+as\s+/)[0]);
}
}
return names;
}

/** Stands in for mock values not written yet: never throws, renders as nothing. */
const DRAFT_VALUE = `const __draftValue: any = (() => {
const target: any = function () {};
const value: any = new Proxy(target, {
get: (_t, key) =>
key === Symbol.toPrimitive
? (hint: string) => (hint === "number" ? 0 : "")
: key === Symbol.iterator
? function* () {}
: key === "then"
? undefined
: value,
apply: () => value,
construct: () => value,
});
return value;
})();`;
const MODULE_NODES = new Set([
"ImportDeclaration",
"ExportNamedDeclaration",
"ExportAllDeclaration",
"ImportExpression",
]);

/**
* The partial mock plus a placeholder for each value a page imports from it that
* isn't defined yet (a missing named export would be a SyntaxError).
* Whether a compiled page (the ESTree program of the JS Vite serves for
* `pages/<name>.tsx`, types already stripped) imports `src/design/mock`.
*
* @internal
*/
export function stubMock(mock: string, imported: Iterable<string>): string {
const exported = new Set(
[
...mock
.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, "")
.matchAll(/export\s+(?:const|let|var|function|class|enum)\s+([\w$]+)/g),
].map((m) => m[1]),
);
const stubs = [...new Set(imported)].filter((name) => !exported.has(name));
return stubs.length === 0
? mock
: `${mock}\n${DRAFT_VALUE}\n${stubs.map((name) => `export const ${name}: any = __draftValue;`).join("\n")}\n`;
export function importsMock(program: unknown): boolean {
const walk = (node: unknown): boolean => {
if (!node || typeof node !== "object") return false;
if (Array.isArray(node)) return node.some(walk);
const { type, source } = node as {
type?: string;
source?: { value?: unknown };
};
if (
MODULE_NODES.has(type as string) &&
typeof source?.value === "string" &&
/^\/src\/design\/mock(?:\.[jt]sx?)?$/.test(
path.posix.resolve("/src/design/pages", source.value),
)
) {
return true;
}
return Object.values(node).some(walk);
};
return walk(program);
}

/**
Expand Down
197 changes: 193 additions & 4 deletions packages/appkit/src/plugins/design/tests/stream-watch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,25 @@ const cwd = process.cwd();
afterEach(() => process.chdir(cwd));

/** The plugin on a fake dev server whose watcher the test drives. */
function start() {
function start(compilerOptions = {}) {
const app = fs.mkdtempSync(path.join(os.tmpdir(), "design-stream-"));
const root = path.join(app, "client");
fs.mkdirSync(path.join(root, "src/design/.staging"), { recursive: true });
fs.mkdirSync(path.join(root, "src/design/pages"), { recursive: true });
// The app's own tsconfig decides what a page imports once compiled.
fs.writeFileSync(
path.join(root, "tsconfig.json"),
JSON.stringify({ compilerOptions }),
);
process.chdir(app);
const plugin = designVitePlugin();
(plugin.configResolved as (c: { root: string }) => void)({ root });
const watcher = new EventEmitter();
const sent: { event: string; data: { name: string; done?: boolean } }[] = [];
const warn = vi.fn();
// Modules the browser has loaded, by file, and the ones hot-updated since.
const modules = new Map<string, object[]>();
const reloaded: object[] = [];
let handler: Handler | undefined;
(plugin.configureServer as (s: unknown) => void)({
config: { root, logger: { warn } },
Expand All @@ -30,10 +38,12 @@ function start() {
middlewares: { use: (h: Handler) => (handler = h) },
transformIndexHtml: async (_url: string, html: string) => html,
moduleGraph: {
getModulesByFile: () => [],
getModulesByFile: (file: string) => modules.get(file) ?? [],
getModuleById: async () => undefined,
},
reloadModule: async () => {},
reloadModule: async (mod: object) => {
reloaded.push(mod);
},
});
/** The HTML of `/design/__stream/<name>`. */
const streamHtml = async (name: string) => {
Expand All @@ -45,7 +55,34 @@ function start() {
);
return html;
};
return { root, watcher, sent, warn, streamHtml };
/** What the plugin's hotUpdate leaves of Vite's update of `file`. */
const hotUpdate = (file: string, mods: object[]) =>
(
plugin.hotUpdate as (o: {
type: string;
file: string;
modules: object[];
read: () => string;
}) => Promise<object[] | undefined>
).call(
{},
{
type: "create",
file,
modules: mods,
read: () => fs.readFileSync(file, "utf-8"),
},
);
return {
root,
watcher,
sent,
warn,
streamHtml,
modules,
reloaded,
hotUpdate,
};
}

type Handler = (
Expand Down Expand Up @@ -96,3 +133,155 @@ test("the stream page says whether a version is out, so a failed import isn't ta
'<div id="root" data-published></div>',
);
});

const TYPES_PAGE =
'import { type Trip } from "../mock";\n\nexport default function Page() {\n const trip: Trip | null = null;\n return <h1>Trips {String(trip)}</h1>;\n}\n';
const MOCK_PAGE =
'import { trips } from "../mock";\n\nexport default function Page() {\n return <h1>{trips.length} trips</h1>;\n}\n';
const published = (
sent: { data: { name: string; done?: boolean } }[],
name = "dash",
) => sent.filter((m) => m.data?.name === name);

test("a page that imports ../mock is published only once mock.ts exists", async () => {
const { root, watcher, sent, streamHtml } = start();
const staging = path.join(root, "src/design/.staging/dash.tsx");
fs.writeFileSync(staging, MOCK_PAGE);
watcher.emit("change", staging);
// Type-only imports compile away: it doesn't wait, it's published as before.
const types = path.join(root, "src/design/.staging/types.tsx");
fs.writeFileSync(types, TYPES_PAGE);
watcher.emit("change", types);
await until(() => sent.some((m) => m.data?.name === "types"));
expect(sent.some((m) => m.data?.name === "types")).toBe(true);
await new Promise((r) => setTimeout(r, 200));
expect(published(sent)).toEqual([]);
expect(await streamHtml("dash")).toContain('<div id="root"></div>');

const mock = path.join(root, "src/design/mock.ts");
fs.writeFileSync(mock, "export const trips = [{ id: 1 }];\n");
watcher.emit("add", mock);
await until(() => published(sent).length > 0);
expect(published(sent)).toMatchObject([
{ event: "appkit:stream", data: { name: "dash" } },
]);
expect(await streamHtml("dash")).toContain(
'<div id="root" data-published></div>',
);
});

test("a finished page waits for mock.ts too, also when its draft was moved in", async () => {
const { root, watcher, sent, streamHtml } = start();
const staging = path.join(root, "src/design/.staging/dash.tsx");
fs.writeFileSync(staging, MOCK_PAGE);
watcher.emit("change", staging);
await new Promise((r) => setTimeout(r, 200));
// Moved in: the staging file goes, the finished page lands.
fs.rmSync(staging);
watcher.emit("unlink", staging);
const page = path.join(root, "src/design/pages/dash.tsx");
fs.writeFileSync(page, MOCK_PAGE);
watcher.emit("add", page);
await new Promise((r) => setTimeout(r, 200));
expect(published(sent)).toEqual([]);
expect(await streamHtml("dash")).toContain('<div id="root"></div>');

const mock = path.join(root, "src/design/mock.ts");
fs.writeFileSync(mock, "export const trips = [{ id: 1 }];\n");
watcher.emit("add", mock);
await until(() => published(sent).length > 0);
expect(published(sent)).toMatchObject([
{ data: { name: "dash", done: true } },
]);
expect(await streamHtml("dash")).toContain(
'<div id="root" data-published></div>',
);
});

test("with verbatimModuleSyntax, an inline type import keeps ../mock, so the page waits", async () => {
const { root, watcher, sent } = start({ verbatimModuleSyntax: true });
const staging = path.join(root, "src/design/.staging/dash.tsx");
fs.writeFileSync(staging, TYPES_PAGE);
watcher.emit("change", staging);
await new Promise((r) => setTimeout(r, 300));
expect(published(sent)).toEqual([]);

const mock = path.join(root, "src/design/mock.ts");
fs.writeFileSync(mock, "export type Trip = { id: number };\n");
watcher.emit("add", mock);
await until(() => published(sent).length > 0);
expect(published(sent)).toMatchObject([{ data: { name: "dash" } }]);
});

test("a finished page shown in an earlier version gets its hot update once mock.ts lands", async () => {
const { root, watcher, sent, modules, reloaded, hotUpdate } = start();
// An early cut doesn't use the mock yet: its import compiles away, it's published.
const staging = path.join(root, "src/design/.staging/dash.tsx");
fs.writeFileSync(
staging,
'import { trips } from "../mock";\n\nexport default function Page() {\n return <h1>Trips</h1>;\n}\n',
);
watcher.emit("change", staging);
await until(() => published(sent).length > 0);
expect(published(sent)).toHaveLength(1);

// The browser has that version; the finished page, which uses the mock, lands.
const page = path.join(root, "src/design/pages/dash.tsx");
const mod = { importers: new Set(), isSelfAccepting: true };
modules.set(page, [mod]);
fs.writeFileSync(page, MOCK_PAGE);
// Vite's update would fail without mock.ts: it's held, and so is done.
expect(await hotUpdate(page, [mod])).toEqual([]);
watcher.emit("add", page);
await new Promise((r) => setTimeout(r, 200));
expect(published(sent)).toHaveLength(1);
expect(reloaded).toEqual([]);

const mock = path.join(root, "src/design/mock.ts");
fs.writeFileSync(mock, "export const trips = [{ id: 1 }];\n");
watcher.emit("add", mock);
await until(() => published(sent).length > 1);
expect(reloaded).toEqual([mod]);
expect(published(sent)[1]).toMatchObject({
data: { name: "dash", done: true },
});
// With mock.ts there, Vite's own update of the page goes through.
expect(await hotUpdate(page, [mod])).toBeUndefined();
});

test("a finished page never streamed, first seen by its stream page, is published when mock.ts lands", async () => {
const { root, watcher, sent, streamHtml } = start();
// No staging draft and no watcher event: only the stream page is opened.
fs.writeFileSync(path.join(root, "src/design/pages/dash.tsx"), MOCK_PAGE);
expect(await streamHtml("dash")).toContain('<div id="root"></div>');

const mock = path.join(root, "src/design/mock.ts");
fs.writeFileSync(mock, "export const trips = [{ id: 1 }];\n");
watcher.emit("add", mock);
await until(() => published(sent).length > 0);
expect(published(sent)).toMatchObject([
{ data: { name: "dash", done: true } },
]);
expect(await streamHtml("dash")).toContain(
'<div id="root" data-published></div>',
);
});

test("a finished page first seen as a hot update is updated when mock.ts lands", async () => {
const { root, watcher, sent, modules, reloaded, hotUpdate } = start();
// A page shown at /design/kpis (never streamed) starts using the mock.
const page = path.join(root, "src/design/pages/kpis.tsx");
const mod = { importers: new Set([{}]), isSelfAccepting: true };
modules.set(page, [mod]);
fs.writeFileSync(page, MOCK_PAGE);
expect(await hotUpdate(page, [mod])).toEqual([]);

const mock = path.join(root, "src/design/mock.ts");
fs.writeFileSync(mock, "export const trips = [{ id: 1 }];\n");
watcher.emit("add", mock);
await until(() => published(sent, "kpis").length > 0);
expect(reloaded).toEqual([mod]);
expect(published(sent, "kpis")).toMatchObject([
{ data: { name: "kpis", done: true } },
]);
});
Loading
Loading