1import { css } from '@emotion/react';
2import { theme } from '@expo/styleguide';
3import React from 'react';
4import ReactMarkdown from 'react-markdown';
5import remarkGfm from 'remark-gfm';
6
7import { Code, InlineCode } from '~/components/base/code';
8import { H4 } from '~/components/base/headings';
9import Link from '~/components/base/link';
10import { LI, UL } from '~/components/base/list';
11import { B, P, Quote } from '~/components/base/paragraph';
12import {
13  CommentData,
14  MethodParamData,
15  MethodSignatureData,
16  PropData,
17  TypeDefinitionData,
18  TypePropertyDataFlags,
19} from '~/components/plugins/api/APIDataTypes';
20
21export enum TypeDocKind {
22  LegacyEnum = 4,
23  Enum = 8,
24  Variable = 32,
25  Function = 64,
26  Class = 128,
27  Interface = 256,
28  Property = 1024,
29  TypeAlias = 4194304,
30}
31
32export type MDComponents = React.ComponentProps<typeof ReactMarkdown>['components'];
33
34export const mdComponents: MDComponents = {
35  blockquote: ({ children }) => (
36    <Quote>
37      {/* @ts-ignore - current implementation produce type issues, this would be fixed in docs redesign */}
38      {children.map(child => (child?.props?.node?.tagName === 'p' ? child?.props.children : child))}
39    </Quote>
40  ),
41  code: ({ children, className }) =>
42    className ? <Code className={className}>{children}</Code> : <InlineCode>{children}</InlineCode>,
43  h1: ({ children }) => <H4>{children}</H4>,
44  ul: ({ children }) => <UL>{children}</UL>,
45  li: ({ children }) => <LI>{children}</LI>,
46  a: ({ href, children }) => <Link href={href}>{children}</Link>,
47  p: ({ children }) => (children ? <P>{children}</P> : null),
48  strong: ({ children }) => <B>{children}</B>,
49  span: ({ children }) => (children ? <span>{children}</span> : null),
50};
51
52export const mdInlineComponents: MDComponents = {
53  ...mdComponents,
54  p: ({ children }) => (children ? <span>{children}</span> : null),
55};
56
57const nonLinkableTypes = [
58  'ColorValue',
59  'Component',
60  'E',
61  'EventSubscription',
62  'File',
63  'FileList',
64  'Manifest',
65  'NativeSyntheticEvent',
66  'React.FC',
67  'ServiceActionResult',
68  'StyleProp',
69  'T',
70  'TaskOptions',
71  'Uint8Array',
72  // Cross-package permissions management
73  'RequestPermissionMethod',
74  'GetPermissionMethod',
75  'Options',
76  'PermissionHookBehavior',
77];
78
79const hardcodedTypeLinks: Record<string, string> = {
80  Date: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date',
81  Error: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error',
82  Omit: 'https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys',
83  Pick: 'https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys',
84  Partial: 'https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype',
85  Promise:
86    'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise',
87  View: '../../react-native/view',
88  ViewProps: '../../react-native/view#props',
89  ViewStyle: '../../react-native/view-style-props/',
90};
91
92const renderWithLink = (name: string, type?: string) =>
93  nonLinkableTypes.includes(name) ? (
94    name + (type === 'array' ? '[]' : '')
95  ) : (
96    <Link href={hardcodedTypeLinks[name] || `#${name.toLowerCase()}`} key={`type-link-${name}`}>
97      {name}
98      {type === 'array' && '[]'}
99    </Link>
100  );
101
102const renderUnion = (types: TypeDefinitionData[]) =>
103  types.map(resolveTypeName).map((valueToRender, index) => (
104    <span key={`union-type-${index}`}>
105      {valueToRender}
106      {index + 1 !== types.length && ' | '}
107    </span>
108  ));
109
110export const resolveTypeName = ({
111  elements,
112  elementType,
113  name,
114  type,
115  types,
116  typeArguments,
117  declaration,
118  value,
119  queryType,
120  checkType,
121  extendsType,
122}: TypeDefinitionData): string | JSX.Element | (string | JSX.Element)[] => {
123  try {
124    if (name) {
125      if (type === 'reference') {
126        if (typeArguments) {
127          if (name === 'Record' || name === 'React.ComponentProps') {
128            return (
129              <>
130                {name}&lt;
131                {typeArguments.map((type, index) => (
132                  <span key={`record-type-${index}`}>
133                    {resolveTypeName(type)}
134                    {index !== typeArguments.length - 1 ? ', ' : null}
135                  </span>
136                ))}
137                &gt;
138              </>
139            );
140          } else {
141            return (
142              <>
143                {renderWithLink(name)}
144                &lt;
145                {typeArguments.map((type, index) => (
146                  <span key={`${name}-nested-type-${index}`}>
147                    {resolveTypeName(type)}
148                    {index !== typeArguments.length - 1 ? ', ' : null}
149                  </span>
150                ))}
151                &gt;
152              </>
153            );
154          }
155        } else {
156          return renderWithLink(name);
157        }
158      } else {
159        return name;
160      }
161    } else if (elementType?.name) {
162      if (elementType.type === 'reference') {
163        return renderWithLink(elementType.name, type);
164      } else if (type === 'array') {
165        return elementType.name + '[]';
166      }
167      return elementType.name + type;
168    } else if (elementType?.declaration) {
169      if (type === 'array') {
170        const { parameters, type: paramType } = elementType.declaration.indexSignature || {};
171        if (parameters && paramType) {
172          return `{ [${listParams(parameters)}]: ${resolveTypeName(paramType)} }`;
173        }
174      }
175      return elementType.name + type;
176    } else if (type === 'union' && types?.length) {
177      return renderUnion(types);
178    } else if (elementType && elementType.type === 'union' && elementType?.types?.length) {
179      const unionTypes = elementType?.types || [];
180      return (
181        <>
182          ({renderUnion(unionTypes)}){type === 'array' && '[]'}
183        </>
184      );
185    } else if (declaration?.signatures) {
186      const baseSignature = declaration.signatures[0];
187      if (baseSignature?.parameters?.length) {
188        return (
189          <>
190            (
191            {baseSignature.parameters?.map((param, index) => (
192              <span key={`param-${index}-${param.name}`}>
193                {param.name}: {resolveTypeName(param.type)}
194                {index + 1 !== baseSignature.parameters?.length && ', '}
195              </span>
196            ))}
197            ) {'=>'} {resolveTypeName(baseSignature.type)}
198          </>
199        );
200      } else {
201        return (
202          <>
203            {'() =>'} {resolveTypeName(baseSignature.type)}
204          </>
205        );
206      }
207    } else if (type === 'reflection' && declaration?.children) {
208      return (
209        <>
210          {'{ '}
211          {declaration?.children.map((child: PropData, i) => (
212            <span key={`reflection-${name}-${i}`}>
213              {child.name + ': ' + resolveTypeName(child.type)}
214              {i + 1 !== declaration?.children?.length ? ', ' : null}
215            </span>
216          ))}
217          {' }'}
218        </>
219      );
220    } else if (type === 'tuple' && elements) {
221      return (
222        <>
223          [
224          {elements.map((elem, i) => (
225            <span key={`tuple-${name}-${i}`}>
226              {resolveTypeName(elem)}
227              {i + 1 !== elements.length ? ', ' : null}
228            </span>
229          ))}
230          ]
231        </>
232      );
233    } else if (type === 'query' && queryType) {
234      return queryType.name;
235    } else if (type === 'literal' && typeof value === 'boolean') {
236      return `${value}`;
237    } else if (type === 'literal' && value) {
238      return `'${value}'`;
239    } else if (value === null) {
240      return 'null';
241    }
242    return 'undefined';
243  } catch (e) {
244    console.warn('Type resolve has failed!', e);
245    return 'undefined';
246  }
247};
248
249export const parseParamName = (name: string) => (name.startsWith('__') ? name.substr(2) : name);
250
251export const renderParam = ({ comment, name, type, flags }: MethodParamData): JSX.Element => (
252  <LI key={`param-${name}`}>
253    <B>
254      {parseParamName(name)}
255      {flags?.isOptional && '?'} (<InlineCode>{resolveTypeName(type)}</InlineCode>)
256    </B>
257    <CommentTextBlock comment={comment} components={mdInlineComponents} withDash />
258  </LI>
259);
260
261export const listParams = (parameters: MethodParamData[]) =>
262  parameters ? parameters?.map(param => parseParamName(param.name)).join(', ') : '';
263
264export const renderTypeOrSignatureType = (
265  type?: TypeDefinitionData,
266  signatures?: MethodSignatureData[],
267  includeParamType: boolean = false
268) => {
269  if (type) {
270    return <InlineCode key={`signature-type-${type.name}`}>{resolveTypeName(type)}</InlineCode>;
271  } else if (signatures && signatures.length) {
272    return signatures.map(({ name, type, parameters }) => (
273      <InlineCode key={`signature-type-${name}`}>
274        (
275        {parameters && includeParamType
276          ? parameters.map(param => (
277              <span key={`signature-param-${param.name}`}>
278                {param.name}
279                {param.flags?.isOptional && '?'}: {resolveTypeName(param.type)}
280              </span>
281            ))
282          : listParams(parameters)}
283        ) =&gt; {resolveTypeName(type)}
284      </InlineCode>
285    ));
286  }
287  return undefined;
288};
289
290export const renderFlags = (flags?: TypePropertyDataFlags) =>
291  flags?.isOptional ? (
292    <>
293      <br />
294      <span css={STYLES_OPTIONAL}>(optional)</span>
295    </>
296  ) : undefined;
297
298export type CommentTextBlockProps = {
299  comment?: CommentData;
300  components?: MDComponents;
301  withDash?: boolean;
302  beforeContent?: JSX.Element;
303};
304
305export const parseCommentContent = (content?: string): string =>
306  content && content.length ? content.replace(/&ast;/g, '*').replace(/\t/g, '') : '';
307
308export const getCommentOrSignatureComment = (
309  comment?: CommentData,
310  signatures?: MethodSignatureData[]
311) => comment || (signatures && signatures[0]?.comment);
312
313export const getTagData = (tagName: string, comment?: CommentData) =>
314  comment?.tags?.filter(tag => tag.tag === tagName)[0];
315
316export const CommentTextBlock = ({
317  comment,
318  components = mdComponents,
319  withDash,
320  beforeContent,
321}: CommentTextBlockProps) => {
322  const shortText = comment?.shortText?.trim().length ? (
323    <ReactMarkdown components={components} remarkPlugins={[remarkGfm]}>
324      {parseCommentContent(comment.shortText)}
325    </ReactMarkdown>
326  ) : null;
327  const text = comment?.text?.trim().length ? (
328    <ReactMarkdown components={components} remarkPlugins={[remarkGfm]}>
329      {parseCommentContent(comment.text)}
330    </ReactMarkdown>
331  ) : null;
332
333  const example = getTagData('example', comment);
334  const exampleText = example ? (
335    <>
336      <H4>Example</H4>
337      <ReactMarkdown components={components}>{example.text}</ReactMarkdown>
338    </>
339  ) : null;
340
341  const deprecation = getTagData('deprecated', comment);
342  const deprecationNote = deprecation ? (
343    <Quote key="deprecation-note">
344      {deprecation.text.trim().length ? (
345        <ReactMarkdown components={mdInlineComponents}>{deprecation.text}</ReactMarkdown>
346      ) : (
347        <B>Deprecated</B>
348      )}
349    </Quote>
350  ) : null;
351
352  const see = getTagData('see', comment);
353  const seeText = see ? (
354    <Quote>
355      <B>See: </B>
356      <ReactMarkdown components={mdInlineComponents}>{see.text}</ReactMarkdown>
357    </Quote>
358  ) : null;
359
360  return (
361    <>
362      {deprecationNote}
363      {beforeContent}
364      {withDash && (shortText || text) && ' - '}
365      {shortText}
366      {text}
367      {seeText}
368      {exampleText}
369    </>
370  );
371};
372
373export const STYLES_OPTIONAL = css`
374  color: ${theme.text.secondary};
375  font-size: 90%;
376  padding-top: 22px;
377`;
378
379export const STYLES_SECONDARY = css`
380  color: ${theme.text.secondary};
381  font-size: 90%;
382  font-weight: 600;
383`;
384