|
| 1 | +// @flow |
| 2 | +import React, { ComponentType, ReactNode, FunctionComponent } from 'react'; |
| 3 | + |
| 4 | +import { CommonProps } from '../types'; |
| 5 | + |
| 6 | +import getPropTypes from '../getPropTypes'; |
| 7 | +import { renderProp, extract } from '../PropType'; |
| 8 | + |
| 9 | +import { type RawProps } from '../types'; |
| 10 | + |
| 11 | +import DefaultLayout from '../layouts/DefaultLayout'; |
| 12 | + |
| 13 | +type Components = {}; |
| 14 | + |
| 15 | +type LayoutProps = { |
| 16 | + components: Components |
| 17 | +}; |
| 18 | + |
| 19 | +type Obj = { |
| 20 | + kind: 'object', |
| 21 | + members: Array<any> |
| 22 | +}; |
| 23 | + |
| 24 | +type Gen = { |
| 25 | + kind: 'generic', |
| 26 | + value: any |
| 27 | +}; |
| 28 | + |
| 29 | +type Inter = { |
| 30 | + kind: 'intersection', |
| 31 | + types: Array<Obj | Gen> |
| 32 | +}; |
| 33 | + |
| 34 | +type DynamicPropsProps = { |
| 35 | + components?: Components, |
| 36 | + heading?: string, |
| 37 | + shouldCollapseProps?: boolean, |
| 38 | + overrides?: { |
| 39 | + [key: string]: ComponentType<CommonProps> |
| 40 | + }, |
| 41 | + props?: { |
| 42 | + component?: Obj | Inter |
| 43 | + }, |
| 44 | + component?: ComponentType<any> |
| 45 | +}; |
| 46 | + |
| 47 | +// TODO: figure out a better name |
| 48 | +export type IPrettyProps = { |
| 49 | + Layout: LayoutProps => ReactNode, |
| 50 | + props?: RawProps, |
| 51 | + component?: ComponentType<any> |
| 52 | +}; |
| 53 | + |
| 54 | +const getProps = (props: RawProps) => { |
| 55 | + if (props && props.component) { |
| 56 | + return getPropTypes(props.component); |
| 57 | + } |
| 58 | + return null; |
| 59 | +}; |
| 60 | + |
| 61 | +const PrettyProps: FunctionComponent<IPrettyProps> = ({ |
| 62 | + layout: Layout = DefaultLayout, |
| 63 | + props, |
| 64 | + component |
| 65 | +}) => { |
| 66 | + let propTypes; |
| 67 | + |
| 68 | + if (component) { |
| 69 | + /* $FlowFixMe the component prop is typed as a component because |
| 70 | + that's what people pass to Props and the ___types property shouldn't |
| 71 | + exist in the components types so we're just going to ignore this error */ |
| 72 | + if (component.___types) { |
| 73 | + propTypes = getProps({ type: 'program', component: component.___types }); |
| 74 | + } else { |
| 75 | + /* eslint-disable-next-line no-console */ |
| 76 | + console.error( |
| 77 | + 'A component was passed to <Props> but it does not have types attached.\n' + |
| 78 | + 'babel-plugin-extract-react-types may not be correctly installed.\n' + |
| 79 | + '<Props> will fallback to the props prop to display types.' |
| 80 | + ); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + propTypes = propTypes || getProps(props); |
| 85 | + |
| 86 | + if (!propTypes) return null; |
| 87 | + |
| 88 | + return propTypes.map(renderProp(Layout)); |
| 89 | +}; |
| 90 | + |
| 91 | +export default PrettyProps; |
0 commit comments