1import { css } from '@emotion/react';
2import { spacing, theme } from '@expo/styleguide';
3
4import { EnumDefinitionData, EnumValueData } from '~/components/plugins/api/APIDataTypes';
5import { APISectionDeprecationNote } from '~/components/plugins/api/APISectionDeprecationNote';
6import { APISectionPlatformTags } from '~/components/plugins/api/APISectionPlatformTags';
7import {
8  CommentTextBlock,
9  getTagNamesList,
10  STYLES_APIBOX,
11  STYLES_APIBOX_NESTED,
12  H3Code,
13} from '~/components/plugins/api/APISectionUtils';
14import { H2, H4, 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        <H4 css={enumValueNameStyle}>
43          <CODE>{enumValue.name}</CODE>
44        </H4>
45        <CODE css={enumValueStyles}>
46          {name}.{enumValue.name}
47          {enumValue?.defaultValue ? ` = ${enumValue?.defaultValue}` : ''}
48        </CODE>
49        <CommentTextBlock comment={enumValue.comment} includePlatforms={false} />
50      </div>
51    ))}
52  </div>
53);
54
55const APISectionEnums = ({ data }: APISectionEnumsProps) =>
56  data?.length ? (
57    <>
58      <H2 key="enums-header">Enums</H2>
59      {data.map(renderEnum)}
60    </>
61  ) : null;
62
63const enumValueNameStyle = css({
64  h4: {
65    marginTop: 0,
66  },
67});
68
69const enumValueStyles = css({
70  display: 'inline-block',
71  padding: `0 ${spacing[2]}px`,
72  color: theme.text.secondary,
73  fontSize: '75%',
74  marginBottom: spacing[4],
75});
76
77const enumContentStyles = css({
78  paddingBottom: 0,
79});
80
81export default APISectionEnums;
82