diff --git a/example/package-lock.json b/example/package-lock.json index c0497dc..cecd31b 100644 --- a/example/package-lock.json +++ b/example/package-lock.json @@ -9011,7 +9011,7 @@ "node_modules/storybook-addon-code-editor": { "version": "0.0.0", "resolved": "file:../storybook-addon-code-editor-0.0.0.tgz", - "integrity": "sha512-QGSIgOJGxB9fWC2FSgCKOqBrCrHzEKYCQHHb0xj5lEtIEBYFx76Byw3WthDC87f5AgwvI2DdXWAHigXN6w6llw==", + "integrity": "sha512-XUnoUScriQp5hqHBUpUX6nTvFLfo+0CZNiX6D8tG+b5zQKSHWU9dB3cw1IV0E/M9k6QtthFzYf7MdR6V5c6JyQ==", "dev": true, "dependencies": { "@babel/standalone": "^7.24.5", diff --git a/src/createStore.ts b/src/createStore.ts index b8137d4..96f065f 100644 --- a/src/createStore.ts +++ b/src/createStore.ts @@ -1,3 +1,8 @@ +// This provides shared state and the ability to subscribe to changes +// between the manager and preview iframes. +// Attempted to use Storybook's `addons.getChannel()` but it doesn't emit +// across iframes. + type Callback = (newValue: T) => any; interface Store { @@ -48,12 +53,12 @@ function newKeyStore(): KeyStore { } export function createStore(): KeyStore { + const getStore = (managerWindow: any) => + (managerWindow._addon_code_editor_store ||= newKeyStore()); try { - return ((window.top as any)._addon_code_editor_store ||= newKeyStore()); + // This will throw in the manager if the storybook site is in an iframe. + return getStore(window.parent); } 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()); + return getStore(window); } }