import React from 'react';
import { InlineCode } from '~/components/base/code';
import { LI, UL } from '~/components/base/list';
import { P } from '~/components/base/paragraph';
import { H2, H4, H4Code } from '~/components/plugins/Headings';
import {
CommentTagData,
DefaultPropsDefinitionData,
PropData,
PropsDefinitionData,
TypeDefinitionData,
} from '~/components/plugins/api/APIDataTypes';
import {
CommentTextBlock,
resolveTypeName,
STYLES_SECONDARY,
} from '~/components/plugins/api/APISectionUtils';
export type APISectionPropsProps = {
data: PropsDefinitionData[];
defaultProps?: DefaultPropsDefinitionData;
header?: string;
};
const UNKNOWN_VALUE = '...';
const extractDefaultPropValue = (
{ comment, name }: PropData,
defaultProps?: DefaultPropsDefinitionData
): string | undefined => {
const annotationDefault = comment?.tags?.filter((tag: CommentTagData) => tag.tag === 'default');
if (annotationDefault?.length) {
return annotationDefault[0].text;
}
return defaultProps?.type?.declaration?.children?.filter(
(defaultProp: PropData) => defaultProp.name === name
)[0]?.defaultValue;
};
const renderInheritedProp = (ip: TypeDefinitionData) => {
return (
{ip?.typeArguments ? (
{resolveTypeName(ip)}
) : (
{ip.name}
)}
);
};
const renderInheritedProps = (data: TypeDefinitionData[] | undefined): JSX.Element | undefined => {
const inheritedProps = data?.filter((ip: TypeDefinitionData) => ip.type === 'reference') ?? [];
if (inheritedProps.length) {
return (
Inherited Props
{inheritedProps.map(renderInheritedProp)}
);
}
return undefined;
};
const renderProps = (
{ name, type }: PropsDefinitionData,
defaultValues?: DefaultPropsDefinitionData
): JSX.Element => {
const baseTypes = type.types
? type.types?.filter((t: TypeDefinitionData) => t.declaration)
: [type];
const propsDeclarations = baseTypes
.map(def => def?.declaration?.children)
.flat()
.filter((dec, i, arr) => arr.findIndex(t => t?.name === dec?.name) === i);
return (
{propsDeclarations?.map(prop =>
prop ? renderProp(prop, extractDefaultPropValue(prop, defaultValues)) : null
)}
{renderInheritedProps(type.types)}
);
};
const renderProp = ({ comment, name, type, flags }: PropData, defaultValue?: string) => (
{name}
{flags?.isOptional && Optional • }
Type: {resolveTypeName(type)}
{defaultValue && defaultValue !== UNKNOWN_VALUE ? (
• Default:{' '}
{defaultValue}
) : null}
);
const APISectionProps: React.FC = ({
data,
defaultProps,
header = 'Props',
}) =>
data?.length ? (
<>
{header === 'Props' ? (
{header}
) : (
<>
{header}
>
)}
{data.map((propsDefinition: PropsDefinitionData) =>
renderProps(propsDefinition, defaultProps)
)}
>
) : null;
export default APISectionProps;