xref: /expo/docs/components/plugins/APISection.tsx (revision 1d47c8ea)
1import React from 'react';
2
3import { P } from '~/components/base/paragraph';
4import { ClassDefinitionData, GeneratedData } from '~/components/plugins/api/APIDataTypes';
5import APISectionClasses from '~/components/plugins/api/APISectionClasses';
6import APISectionComponents from '~/components/plugins/api/APISectionComponents';
7import APISectionConstants from '~/components/plugins/api/APISectionConstants';
8import APISectionEnums from '~/components/plugins/api/APISectionEnums';
9import APISectionInterfaces from '~/components/plugins/api/APISectionInterfaces';
10import APISectionMethods from '~/components/plugins/api/APISectionMethods';
11import APISectionProps from '~/components/plugins/api/APISectionProps';
12import APISectionTypes from '~/components/plugins/api/APISectionTypes';
13import { TypeDocKind, getComponentName } from '~/components/plugins/api/APISectionUtils';
14import { usePageApiVersion } from '~/providers/page-api-version';
15
16const LATEST_VERSION = `v${require('~/package.json').version}`;
17
18type Props = {
19  packageName: string;
20  apiName?: string;
21  forceVersion?: string;
22  strictTypes?: boolean;
23};
24
25const filterDataByKind = (
26  entries: GeneratedData[] = [],
27  kind: TypeDocKind | TypeDocKind[],
28  additionalCondition: (entry: GeneratedData) => boolean = () => true
29) =>
30  entries.filter(
31    (entry: GeneratedData) =>
32      (Array.isArray(kind) ? kind.includes(entry.kind) : entry.kind === kind) &&
33      additionalCondition(entry)
34  );
35
36const isHook = ({ name }: GeneratedData) =>
37  name.startsWith('use') &&
38  // note(simek): hardcode this exception until the method will be renamed
39  name !== 'useSystemBrightnessAsync';
40
41const isListener = ({ name }: GeneratedData) =>
42  name.endsWith('Listener') || name.endsWith('Listeners');
43
44const isProp = ({ name }: GeneratedData) => name.includes('Props') && name !== 'ErrorRecoveryProps';
45
46const isComponent = ({ type, extendedTypes, signatures }: GeneratedData) => {
47  if (type?.name && ['React.FC', 'ForwardRefExoticComponent'].includes(type?.name)) {
48    return true;
49  } else if (extendedTypes && extendedTypes.length) {
50    return extendedTypes[0].name === 'Component';
51  } else if (signatures && signatures.length) {
52    if (
53      signatures[0].type.name === 'Element' ||
54      (signatures[0].parameters && signatures[0].parameters[0].name === 'props')
55    ) {
56      return true;
57    }
58  }
59  return false;
60};
61
62const isConstant = ({ name, type }: GeneratedData) =>
63  !['default', 'Constants', 'EventEmitter'].includes(name) &&
64  !(type?.name && ['React.FC', 'ForwardRefExoticComponent'].includes(type?.name));
65
66const renderAPI = (
67  packageName: string,
68  version: string = 'unversioned',
69  apiName?: string,
70  strictTypes: boolean = false,
71  isTestMode: boolean = false
72): JSX.Element => {
73  try {
74    // note(simek): When the path prefix is interpolated Next or Webpack fails to locate the file
75    const { children: data } = isTestMode
76      ? require(`../../public/static/data/${version}/${packageName}.json`)
77      : require(`~/public/static/data/${version}/${packageName}.json`);
78
79    const methods = filterDataByKind(
80      data,
81      TypeDocKind.Function,
82      entry => !isListener(entry) && !isHook(entry) && !isComponent(entry)
83    );
84    const hooks = filterDataByKind(data, TypeDocKind.Function, isHook);
85    const eventSubscriptions = filterDataByKind(data, TypeDocKind.Function, isListener);
86
87    const types = filterDataByKind(
88      data,
89      TypeDocKind.TypeAlias,
90      entry =>
91        !isProp(entry) &&
92        !!(
93          entry.type.declaration ||
94          entry.type.types ||
95          entry.type.type ||
96          entry.type.typeArguments
97        ) &&
98        (strictTypes && apiName ? entry.name.startsWith(apiName) : true)
99    );
100
101    const props = filterDataByKind(
102      data,
103      TypeDocKind.TypeAlias,
104      entry => isProp(entry) && !!(entry.type.types || entry.type.declaration?.children)
105    );
106    const defaultProps = filterDataByKind(
107      data
108        .filter((entry: GeneratedData) => entry.kind === TypeDocKind.Class)
109        .map((entry: GeneratedData) => entry.children)
110        .flat(),
111      TypeDocKind.Property,
112      entry => entry.name === 'defaultProps'
113    )[0];
114
115    const enums = filterDataByKind(
116      data,
117      [TypeDocKind.Enum, TypeDocKind.LegacyEnum],
118      entry => entry.name !== 'default'
119    );
120    const interfaces = filterDataByKind(data, TypeDocKind.Interface);
121    const constants = filterDataByKind(data, TypeDocKind.Variable, entry => isConstant(entry));
122
123    const components = filterDataByKind(
124      data,
125      [TypeDocKind.Variable, TypeDocKind.Class, TypeDocKind.Function],
126      entry => isComponent(entry)
127    );
128    const componentsPropNames = components.map(
129      ({ name, children }) => `${getComponentName(name, children)}Props`
130    );
131    const componentsProps = filterDataByKind(props, TypeDocKind.TypeAlias, entry =>
132      componentsPropNames.includes(entry.name)
133    );
134
135    const classes = filterDataByKind(
136      data,
137      TypeDocKind.Class,
138      entry => !isComponent(entry) && (apiName ? !entry.name.includes(apiName) : true)
139    );
140
141    const componentsChildren = components
142      .map((cls: ClassDefinitionData) =>
143        cls.children?.filter(
144          child =>
145            child.kind === TypeDocKind.Method &&
146            child?.flags?.isExternal !== true &&
147            child.name !== 'render' &&
148            // note(simek): hide unannotated "private" methods
149            !child.name.startsWith('_')
150        )
151      )
152      .flat();
153
154    const methodsNames = methods.map(method => method.name);
155    const staticMethods = componentsChildren.filter(
156      // note(simek): hide duplicate exports for Camera API
157      method => method?.flags?.isStatic === true && !methodsNames.includes(method.name)
158    );
159    const componentMethods = componentsChildren
160      .filter(method => method?.flags?.isStatic !== true && !method?.overwrites)
161      .filter(Boolean);
162
163    return (
164      <>
165        <APISectionComponents data={components} componentsProps={componentsProps} />
166        <APISectionMethods data={staticMethods} header="Static Methods" />
167        <APISectionMethods data={componentMethods} header="Component Methods" />
168        <APISectionConstants data={constants} apiName={apiName} />
169        <APISectionMethods data={hooks} header="Hooks" />
170        <APISectionClasses data={classes} />
171        {props && !componentsProps.length ? (
172          <APISectionProps data={props} defaultProps={defaultProps} />
173        ) : null}
174        <APISectionMethods data={methods} apiName={apiName} />
175        <APISectionMethods
176          data={eventSubscriptions}
177          apiName={apiName}
178          header="Event Subscriptions"
179        />
180        <APISectionTypes data={types} />
181        <APISectionInterfaces data={interfaces} />
182        <APISectionEnums data={enums} />
183      </>
184    );
185  } catch (error) {
186    return <P>No API data file found, sorry!</P>;
187  }
188};
189
190const APISection = ({ packageName, apiName, forceVersion, strictTypes = false }: Props) => {
191  const { version } = usePageApiVersion();
192  const resolvedVersion =
193    forceVersion ||
194    (version === 'unversioned' ? version : version === 'latest' ? LATEST_VERSION : version);
195  return renderAPI(packageName, resolvedVersion, apiName, strictTypes, !!forceVersion);
196};
197
198export default APISection;
199