diff --git a/addons/docs/src/blocks/Source.tsx b/addons/docs/src/blocks/Source.tsx index 1c521af3426..e3c6da541c5 100644 --- a/addons/docs/src/blocks/Source.tsx +++ b/addons/docs/src/blocks/Source.tsx @@ -13,6 +13,7 @@ import { CURRENT_SELECTION } from './types'; import { SourceType } from '../shared'; import { enhanceSource } from './enhanceSource'; +import { useStories } from './useStory'; export enum SourceState { OPEN = 'open', @@ -46,14 +47,8 @@ const getStory = (storyId: StoryId, docsContext: DocsContextProps): Story | null return docsContext.storyById(storyId); }; -const getSourceState = (storyIds: string[], docsContext: DocsContextProps) => { - const states = storyIds - .map((storyId) => { - const story = getStory(storyId, docsContext); - return story?.parameters.docs?.source?.state; - }) - .filter(Boolean); - +const getSourceState = (stories: Story[]) => { + const states = stories.map((story) => story.parameters.docs?.source?.state).filter(Boolean); if (states.length === 0) return SourceState.CLOSED; // FIXME: handling multiple stories is a pain return states[0]; @@ -117,17 +112,22 @@ export const getSourceProps = ( singleProps.id === CURRENT_SELECTION || !singleProps.id ? currentId : singleProps.id; const targetIds = multiProps.ids || [targetId]; + const stories = useStories(targetIds, docsContext); + if (!stories) { + return { error: SourceError.SOURCE_UNAVAILABLE, state: SourceState.NONE }; + } + if (!source) { source = targetIds - .map((storyId) => { + .map((storyId, idx) => { const storySource = getStorySource(storyId, sourceContext); - const story = getStory(storyId, docsContext); - return getSnippet(storySource, story); + const storyObj = stories[idx]; + return getSnippet(storySource, storyObj); }) .join('\n\n'); } - const state = getSourceState(targetIds, docsContext); + const state = getSourceState(stories); const { docs: docsParameters = {} } = parameters; const { source: sourceParameters = {} } = docsParameters; diff --git a/addons/docs/src/blocks/useStory.ts b/addons/docs/src/blocks/useStory.ts index 6c785247fe9..6d11636eeb6 100644 --- a/addons/docs/src/blocks/useStory.ts +++ b/addons/docs/src/blocks/useStory.ts @@ -8,11 +8,23 @@ export function useStory( storyId: StoryId, context: DocsContextProps ): Story | void { - const [story, setStory] = useState(null); + const stories = useStories([storyId], context); + return stories && stories[0]; +} + +export function useStories( + storyIds: StoryId[], + context: DocsContextProps +): Story[] | void { + const [stories, setStories] = useState(null); useEffect(() => { - context.loadStory(storyId).then((s) => setStory(s)); + Promise.all(storyIds.map((storyId) => context.loadStory(storyId))).then((loadedStories) => { + if (!stories) { + setStories(loadedStories); + } + }); }); - return story; + return stories; }