UNPKG

1.39 kBJavaScriptView Raw
1import { SHARED_STATE_CHANGED, SHARED_STATE_SET } from '@storybook/core-events';
2import { addons, HooksContext, applyHooks, useMemo, useCallback, useRef, useState, useReducer, useEffect, useChannel, useStoryContext, useParameter, useArgs, useGlobals } from '@storybook/addons';
3export { HooksContext, applyHooks, useMemo, useCallback, useRef, useState, useReducer, useEffect, useChannel, useStoryContext, useParameter, useArgs, useGlobals };
4export function useSharedState(sharedId, defaultState) {
5 const channel = addons.getChannel();
6 const [lastValue] = channel.last(`${SHARED_STATE_CHANGED}-manager-${sharedId}`) || channel.last(`${SHARED_STATE_SET}-manager-${sharedId}`) || [];
7 const [state, setState] = useState(lastValue || defaultState);
8 const allListeners = useMemo(() => ({
9 [`${SHARED_STATE_CHANGED}-manager-${sharedId}`]: s => setState(s),
10 [`${SHARED_STATE_SET}-manager-${sharedId}`]: s => setState(s)
11 }), [sharedId]);
12 const emit = useChannel(allListeners, [sharedId]);
13 useEffect(() => {
14 // init
15 if (defaultState !== undefined && !lastValue) {
16 emit(`${SHARED_STATE_SET}-client-${sharedId}`, defaultState);
17 }
18 }, [sharedId]);
19 return [state, s => {
20 setState(s);
21 emit(`${SHARED_STATE_CHANGED}-client-${sharedId}`, s);
22 }];
23}
24export function useAddonState(addonId, defaultState) {
25 return useSharedState(addonId, defaultState);
26}
\No newline at end of file