/
Preview.tsx
55 lines (51 loc) · 1.66 KB
/
Preview.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import React, { FunctionComponent, ReactElement, ReactNode, ReactNodeArray } from 'react';
import { Preview as PurePreview, PreviewProps as PurePreviewProps } from '@storybook/components';
import { getSourceProps } from './Source';
import { DocsContext, DocsContextProps } from './DocsContext';
export enum SourceState {
OPEN = 'open',
CLOSED = 'closed',
NONE = 'none',
}
type PreviewProps = PurePreviewProps & {
withSource?: SourceState;
mdxSource?: string;
};
const getPreviewProps = (
{
withSource = SourceState.CLOSED,
mdxSource,
children,
...props
}: PreviewProps & { children?: ReactNode },
{ mdxStoryNameToId, storyStore }: DocsContextProps
): PurePreviewProps => {
if (withSource === SourceState.NONE) {
return props;
}
if (mdxSource) {
return {
...props,
withSource: getSourceProps({ code: decodeURI(mdxSource) }, { storyStore }),
};
}
const childArray: ReactNodeArray = Array.isArray(children) ? children : [children];
const stories = childArray.filter(
(c: ReactElement) => c.props && (c.props.id || c.props.name)
) as ReactElement[];
const targetIds = stories.map(s => s.props.id || mdxStoryNameToId[s.props.name]);
const sourceProps = getSourceProps({ ids: targetIds }, { storyStore });
return {
...props, // pass through columns etc.
withSource: sourceProps,
isExpanded: withSource === SourceState.OPEN,
};
};
export const Preview: FunctionComponent<PreviewProps> = props => (
<DocsContext.Consumer>
{context => {
const previewProps = getPreviewProps(props, context);
return <PurePreview {...previewProps}>{props.children}</PurePreview>;
}}
</DocsContext.Consumer>
);