1import { css } from '@emotion/react';
2import { theme } from '@expo/styleguide';
3import React from 'react';
4
5import { InlineCode } from '~/components/base/code';
6import { LI, UL } from '~/components/base/list';
7import { H2, H3Code } from '~/components/plugins/Headings';
8import { EnumDefinitionData, EnumValueData } from '~/components/plugins/api/APIDataTypes';
9import { CommentTextBlock, mdInlineComponents } from '~/components/plugins/api/APISectionUtils';
10
11export type APISectionEnumsProps = {
12  data: EnumDefinitionData[];
13};
14
15const STYLES_ENUM_VALUE = css({ color: theme.text.secondary, fontSize: '75%' });
16
17const sortByValue = (a: EnumValueData, b: EnumValueData) => {
18  if (a.defaultValue && b.defaultValue) {
19    if (a.defaultValue.includes(`'`) && b.defaultValue.includes(`'`)) {
20      return a.defaultValue.localeCompare(b.defaultValue);
21    } else {
22      return parseInt(a.defaultValue, 10) - parseInt(b.defaultValue, 10);
23    }
24  }
25  return 0;
26};
27
28const renderEnum = ({ name, children, comment }: EnumDefinitionData): JSX.Element => (
29  <div key={`enum-definition-${name}`}>
30    <H3Code>
31      <InlineCode>{name}</InlineCode>
32    </H3Code>
33    <CommentTextBlock comment={comment} />
34    <UL>
35      {children.sort(sortByValue).map((enumValue: EnumValueData) => (
36        <LI key={enumValue.name}>
37          <span css={{ fontSize: '120%' }}>
38            <InlineCode>{enumValue.name}</InlineCode>
39          </span>
40          {enumValue.comment ? (
41            <CommentTextBlock
42              comment={enumValue.comment}
43              components={mdInlineComponents}
44              withDash
45            />
46          ) : null}
47          <br />
48          {enumValue?.defaultValue && (
49            <InlineCode customCss={STYLES_ENUM_VALUE}>
50              {name}.{enumValue.name} = {enumValue?.defaultValue}
51            </InlineCode>
52          )}
53        </LI>
54      ))}
55    </UL>
56  </div>
57);
58
59const APISectionEnums = ({ data }: APISectionEnumsProps) =>
60  data?.length ? (
61    <>
62      <H2 key="enums-header">Enums</H2>
63      {data.map(renderEnum)}
64    </>
65  ) : null;
66
67export default APISectionEnums;
68