diff --git a/lib/api/package.json b/lib/api/package.json index 8f33f673650c..977ee6a0e989 100644 --- a/lib/api/package.json +++ b/lib/api/package.json @@ -28,6 +28,7 @@ }, "dependencies": { "@reach/router": "^1.2.1", + "@storybook/addons": "6.0.0-alpha.20", "@storybook/channels": "6.0.0-alpha.20", "@storybook/client-logger": "6.0.0-alpha.20", "@storybook/core-events": "6.0.0-alpha.20", diff --git a/lib/api/src/index.tsx b/lib/api/src/index.tsx index 62848ab2fb31..15e675ecfae1 100644 --- a/lib/api/src/index.tsx +++ b/lib/api/src/index.tsx @@ -58,6 +58,10 @@ import initVersions, { SubState as VersionsSubState, SubAPI as VersionsAPI, } from './modules/versions'; +import initGlobalArgs, { + SubState as GlobalArgsSubState, + SubAPI as GlobalArgsAPI, +} from './modules/globalArgs'; export { Options as StoreOptions, Listener as ChannelListener }; export { ActiveTabs }; @@ -77,7 +81,8 @@ export type State = Other & NotificationState & VersionsSubState & RouterData & - ShortcutsSubState; + ShortcutsSubState & + GlobalArgsSubState; export type API = AddonsAPI & ChannelAPI & @@ -88,6 +93,7 @@ export type API = AddonsAPI & ShortcutsAPI & VersionsAPI & UrlAPI & + GlobalArgsAPI & OtherAPI; interface OtherAPI { @@ -179,6 +185,7 @@ class ManagerProvider extends Component { initStories, initURL, initVersions, + initGlobalArgs, ].map(initModule => initModule({ ...routeData, ...apiData, state: this.state })); // Create our initial state by combining the initial state of all modules, then overlaying any saved state diff --git a/lib/api/src/modules/globalArgs.ts b/lib/api/src/modules/globalArgs.ts new file mode 100644 index 000000000000..03f2dfaa5864 --- /dev/null +++ b/lib/api/src/modules/globalArgs.ts @@ -0,0 +1,43 @@ +import { Args } from '@storybook/addons'; +import { CHANGE_GLOBAL_ARGS, GLOBAL_ARGS_CHANGED } from '@storybook/core-events'; + +import { Module, API } from '../index'; + +export interface SubState { + globalArgs: Args; +} + +export interface SubAPI { + setGlobalArgs: (newGlobalArgs: Args) => void; +} + +const initGlobalArgsApi = ({ store }: Module) => { + let fullApi: API; + const setGlobalArgs = (newGlobalArgs: Args) => { + if (!fullApi) throw new Error('Cannot set global args until api has been initialized'); + + fullApi.emit(CHANGE_GLOBAL_ARGS, newGlobalArgs); + }; + + const api: SubAPI = { + setGlobalArgs, + }; + + const state: SubState = { + // Currently global args always start empty. TODO -- should this be set on the channel at init time? + globalArgs: {}, + }; + + const init = ({ api: inputApi }: { api: API }) => { + fullApi = inputApi; + fullApi.on(GLOBAL_ARGS_CHANGED, (globalArgs: Args) => store.setState({ globalArgs })); + }; + + return { + api, + state, + init, + }; +}; + +export default initGlobalArgsApi;