diff --git a/lib/core/src/client/preview/start.js b/lib/core/src/client/preview/start.js index deaa08b67749..ffb269892bdb 100644 --- a/lib/core/src/client/preview/start.js +++ b/lib/core/src/client/preview/start.js @@ -77,9 +77,16 @@ export const getContext = (() => { addons.setChannel(channel); } } - - const storyStore = new StoryStore({ channel }); - const clientApi = new ClientApi({ storyStore, decorateStory }); + let storyStore; + let clientApi; + if (typeof window !== 'undefined' && window.__STORYBOOK_CLIENT_API__) { + clientApi = window.__STORYBOOK_CLIENT_API__; + // eslint-disable-next-line no-underscore-dangle + storyStore = clientApi._storyStore; + } else { + storyStore = new StoryStore({ channel }); + clientApi = new ClientApi({ storyStore, decorateStory }); + } const { clearDecorators } = clientApi; const configApi = new ConfigApi({ clearDecorators, storyStore, channel, clientApi }); diff --git a/lib/core/src/client/preview/start.test.js b/lib/core/src/client/preview/start.test.js index 4b9270593e16..e2444a0313b9 100644 --- a/lib/core/src/client/preview/start.test.js +++ b/lib/core/src/client/preview/start.test.js @@ -1,4 +1,4 @@ -import { document } from 'global'; +import { document, window } from 'global'; import start from './start'; @@ -6,6 +6,7 @@ jest.mock('@storybook/client-logger'); jest.mock('global', () => ({ navigator: { userAgent: 'browser', platform: '' }, window: { + __STORYBOOK_CLIENT_API__: undefined, addEventListener: jest.fn(), location: { search: '' }, history: { replaceState: jest.fn() }, @@ -19,6 +20,10 @@ jest.mock('global', () => ({ }, })); +afterEach(() => { + window.__STORYBOOK_CLIENT_API__ = undefined; +}); + it('returns apis', () => { const render = jest.fn(); @@ -34,6 +39,21 @@ it('returns apis', () => { ); }); +it('reuses the current client api when the lib is reloaded', () => { + jest.useFakeTimers(); + const render = jest.fn(); + + const { clientApi } = start(render); + + const valueOfClientApi = window.__STORYBOOK_CLIENT_API__; + + const { clientApi: newClientApi } = start(render); + jest.runAllTimers(); + + expect(clientApi).toEqual(newClientApi); + expect(clientApi).toEqual(valueOfClientApi); +}); + it('calls render when you add a story', () => { jest.useFakeTimers(); const render = jest.fn();