Skip to content

Commit

Permalink
fix: iframed storybook sites fail due to window.top access
Browse files Browse the repository at this point in the history
  • Loading branch information
JeremyRH committed Jun 24, 2024
1 parent 1166b22 commit 02f8255
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 23 deletions.
8 changes: 4 additions & 4 deletions example/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 7 additions & 16 deletions scripts/createChildProcess.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// @ts-check

import { spawn } from "node:child_process";
import { spawn } from 'node:child_process';

// Collect all child processes and kill them when this node process exits.
const childProcesses = new Set();
process.on("exit", () => childProcesses.forEach((child) => child.kill()));
process.on('exit', () => childProcesses.forEach((child) => child.kill()));

export function createChildProcess(command, args, options = {}) {
let resolve;
Expand All @@ -18,30 +18,21 @@ export function createChildProcess(command, args, options = {}) {

childProcesses.add(childP);

const stdoutData = [];

childP.stdout?.on("data", (data) => {
stdoutData.push(data);
});

childP.once("error", (err) => {
childP.once('error', (err) => {
reject(err);
});

childP.once("close", (code) => {
childP.once('close', (code) => {
childProcesses.delete(childP);
if (code !== 0) {
reject(new Error(`Command "${command} ${args.join(" ")}" exited with code ${code}`));
reject(new Error(`Command "${command} ${args.join(' ')}" exited with code ${code}`));
return;
}
resolve({
process: childP,
stdout: stdoutData.join("").trim(),
});
resolve();
});

return {
childProcess: childP,
promise,
}
};
}
9 changes: 8 additions & 1 deletion src/createStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,12 @@ function newKeyStore<T>(): KeyStore<T> {
}

export function createStore<T>(): KeyStore<T> {
return ((window.top as any)._addon_code_editor_store ||= newKeyStore());
try {
return ((window.top as any)._addon_code_editor_store ||= newKeyStore());
} catch {
// Storybook sites can be embedded in iframes. Using window.top will fail in that case.
// Try window.parent as a fallback. This can break if Storybook changes how previews are rendered.
// TODO: Use Storybook Channels to communicate between the manager and preview.
return ((window.parent as any)._addon_code_editor_store ||= newKeyStore());
}
}

0 comments on commit 02f8255

Please sign in to comment.