UNPKG

wix-storybook-utils

Version:

Utilities for automated component documentation within Storybook

92 lines (83 loc) 2.27 kB
import * as React from 'react'; import { transformData } from './transformStoryStructure'; import { getCustomQueryParams } from './getCustomQueryParams'; import { Example } from '../../../typings/story'; const baseUrl = 'https://mykolass.wixsite.com/storybook-builder/_functions'; export type StoryData = { demo: string; title?: string; description: string; do: string[]; dont: string[]; featureExamples: Example[]; developerExamples: Example[]; accessibilityExamples: Example[]; commonUseCaseExamples: Example[]; }; const buildEndpoint = ({ library, storyName, previewId, }: { library?: string; storyName: string; previewId?: string; }) => { if (previewId) { return `${baseUrl}/getPreview?id=${previewId}`; } return `${baseUrl}/getStory?storyName=${storyName}&library=${library}`; }; async function fetchStory({ library, storyName, previewId, }: { library?: string; storyName: string; previewId?: string; }): Promise<StoryData> { return fetch(buildEndpoint({ library, storyName, previewId })) .then(res => res.json()) .then(res => { if (res.error) { return null; } return res.story.content; }); } export const useStorybookBuilderApi = ({ library, storyName, }: { library?: string; storyName: string; }) => { const [loading, setLoading] = React.useState(true); const [data, setData] = React.useState<StoryData | null>(null); const { previewId, enabled } = getCustomQueryParams(storyName); React.useEffect(() => { if (enabled) { setLoading(true); fetchStory({ library, storyName, previewId: previewId as string }) .then(res => { setTimeout(() => setLoading(false), 150); setData(res); }) .catch(error => { setTimeout(() => setLoading(false), 100); console.error(error); }); } }, []); if (window.parent.window.STORYBOOK_CMS_DATA && !enabled) { const foundStory = window.parent.window.STORYBOOK_CMS_DATA.find( story => story.storyName === storyName, ); return { loading: false, response: foundStory ? transformData(foundStory.content) : null, }; } return { loading, response: data && transformData(data), enabled }; };