Skip to content

Commit

Permalink
Merge pull request #6154 from storybooks/storysource/reuse-currently-…
Browse files Browse the repository at this point in the history
…built-client-api

📜[storysource]  📦 [sandpack] The clientApi must be reused when possible
  • Loading branch information
ndelangen authored Apr 2, 2019
2 parents 3b93015 + cc8f843 commit ff25b5c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
13 changes: 10 additions & 3 deletions lib/core/src/client/preview/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 });

Expand Down
22 changes: 21 additions & 1 deletion lib/core/src/client/preview/start.test.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { document } from 'global';
import { document, window } from 'global';

import start from './start';

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() },
Expand All @@ -19,6 +20,10 @@ jest.mock('global', () => ({
},
}));

afterEach(() => {
window.__STORYBOOK_CLIENT_API__ = undefined;
});

it('returns apis', () => {
const render = jest.fn();

Expand All @@ -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();
Expand Down

0 comments on commit ff25b5c

Please sign in to comment.