1import { css } from '@emotion/react';
2import { spacing, theme } from '@expo/styleguide';
3
4import { H2, H3Code, H4Code } from '~/components/plugins/Headings';
5import { EnumDefinitionData, EnumValueData } from '~/components/plugins/api/APIDataTypes';
6import { APISectionDeprecationNote } from '~/components/plugins/api/APISectionDeprecationNote';
7import { APISectionPlatformTags } from '~/components/plugins/api/APISectionPlatformTags';
8import {
9  CommentTextBlock,
10  getTagNamesList,
11  STYLES_APIBOX,
12  STYLES_APIBOX_NESTED,
13} from '~/components/plugins/api/APISectionUtils';
14import { CODE } from '~/ui/components/Text';
15
16export type APISectionEnumsProps = {
17  data: EnumDefinitionData[];
18};
19
20const sortByValue = (a: EnumValueData, b: EnumValueData) => {
21  if (a.defaultValue && b.defaultValue) {
22    if (a.defaultValue.includes(`'`) && b.defaultValue.includes(`'`)) {
23      return a.defaultValue.localeCompare(b.defaultValue);
24    } else {
25      return parseInt(a.defaultValue, 10) - parseInt(b.defaultValue, 10);
26    }
27  }
28  return 0;
29};
30
31const renderEnum = ({ name, children, comment }: EnumDefinitionData): JSX.Element => (
32  <div key={`enum-definition-${name}`} css={[STYLES_APIBOX, enumContentStyles]}>
33    <APISectionDeprecationNote comment={comment} />
34    <APISectionPlatformTags comment={comment} prefix="Only for:" />
35    <H3Code tags={getTagNamesList(comment)}>
36      <CODE>{name}</CODE>
37    </H3Code>
38    <CommentTextBlock comment={comment} includePlatforms={false} />
39    {children.sort(sortByValue).map((enumValue: EnumValueData) => (
40      <div css={[STYLES_APIBOX, STYLES_APIBOX_NESTED]} key={enumValue.name}>
41        <APISectionPlatformTags comment={enumValue.comment} prefix="Only for:" />
42        <div css={enumValueNameStyle}>
43          <H4Code>
44            <CODE>{enumValue.name}</CODE>
45          </H4Code>
46        </div>
47        <CODE css={enumValueStyles}>
48          {name}.{enumValue.name}
49          {enumValue?.defaultValue ? ` = ${enumValue?.defaultValue}` : ''}
50        </CODE>
51        <CommentTextBlock comment={enumValue.comment} includePlatforms={false} />
52      </div>
53    ))}
54  </div>
55);
56
57const APISectionEnums = ({ data }: APISectionEnumsProps) =>
58  data?.length ? (
59    <>
60      <H2 key="enums-header">Enums</H2>
61      {data.map(renderEnum)}
62    </>
63  ) : null;
64
65const enumValueNameStyle = css({
66  h4: {
67    marginTop: 0,
68  },
69});
70
71const enumValueStyles = css({
72  display: 'inline-block',
73  padding: `0 ${spacing[2]}px`,
74  color: theme.text.secondary,
75  fontSize: '75%',
76  marginBottom: spacing[4],
77});
78
79const enumContentStyles = css({
80  paddingBottom: 0,
81});
82
83export default APISectionEnums;
84