UNPKG

2.65 kBJavaScriptView Raw
1import "core-js/modules/es.object.keys.js";
2import { SET_GLOBALS, UPDATE_GLOBALS, GLOBALS_UPDATED } from '@storybook/core-events';
3import { logger } from '@storybook/client-logger';
4import deepEqual from 'fast-deep-equal';
5import { getEventMetadata } from '../lib/events';
6export var init = function init(_ref) {
7 var store = _ref.store,
8 fullAPI = _ref.fullAPI;
9 var api = {
10 getGlobals: function getGlobals() {
11 return store.getState().globals;
12 },
13 getGlobalTypes: function getGlobalTypes() {
14 return store.getState().globalTypes;
15 },
16 updateGlobals: function updateGlobals(newGlobals) {
17 // Only emit the message to the local ref
18 fullAPI.emit(UPDATE_GLOBALS, {
19 globals: newGlobals,
20 options: {
21 target: 'storybook-preview-iframe'
22 }
23 });
24 }
25 };
26 var state = {
27 globals: {},
28 globalTypes: {}
29 };
30
31 var updateGlobals = function updateGlobals(globals) {
32 var _store$getState;
33
34 var currentGlobals = (_store$getState = store.getState()) === null || _store$getState === void 0 ? void 0 : _store$getState.globals;
35
36 if (!deepEqual(globals, currentGlobals)) {
37 store.setState({
38 globals: globals
39 });
40 }
41 };
42
43 var initModule = function initModule() {
44 fullAPI.on(GLOBALS_UPDATED, function handleGlobalsUpdated(_ref2) {
45 var globals = _ref2.globals;
46
47 var _getEventMetadata = getEventMetadata(this, fullAPI),
48 ref = _getEventMetadata.ref;
49
50 if (!ref) {
51 updateGlobals(globals);
52 } else {
53 logger.warn('received a GLOBALS_UPDATED from a non-local ref. This is not currently supported.');
54 }
55 }); // Emitted by the preview on initialization
56
57 fullAPI.on(SET_GLOBALS, function handleSetStories(_ref3) {
58 var _store$getState2;
59
60 var globals = _ref3.globals,
61 globalTypes = _ref3.globalTypes;
62
63 var _getEventMetadata2 = getEventMetadata(this, fullAPI),
64 ref = _getEventMetadata2.ref;
65
66 var currentGlobals = (_store$getState2 = store.getState()) === null || _store$getState2 === void 0 ? void 0 : _store$getState2.globals;
67
68 if (!ref) {
69 store.setState({
70 globals: globals,
71 globalTypes: globalTypes
72 });
73 } else if (Object.keys(globals).length > 0) {
74 logger.warn('received globals from a non-local ref. This is not currently supported.');
75 }
76
77 if (currentGlobals && Object.keys(currentGlobals).length !== 0 && !deepEqual(globals, currentGlobals)) {
78 api.updateGlobals(currentGlobals);
79 }
80 });
81 };
82
83 return {
84 api: api,
85 state: state,
86 init: initModule
87 };
88};
\No newline at end of file