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