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