1import { css } from '@emotion/react';
2
3import { EnumDefinitionData, EnumValueData } from '~/components/plugins/api/APIDataTypes';
4import { APISectionDeprecationNote } from '~/components/plugins/api/APISectionDeprecationNote';
5import { APISectionPlatformTags } from '~/components/plugins/api/APISectionPlatformTags';
6import {
7  CommentTextBlock,
8  getTagNamesList,
9  STYLES_APIBOX,
10  STYLES_APIBOX_NESTED,
11  H3Code,
12} from '~/components/plugins/api/APISectionUtils';
13import { H2, H4, CODE, MONOSPACE } from '~/ui/components/Text';
14
15export type APISectionEnumsProps = {
16  data: EnumDefinitionData[];
17};
18
19const sortByValue = (a: EnumValueData, b: EnumValueData) => {
20  if (a.type && a.type.value !== undefined && b.type && b.type.value !== undefined) {
21    if (typeof a.type.value === 'string' && typeof b.type.value === 'string') {
22      return a.type.value.localeCompare(b.type.value);
23    } else if (typeof a.type.value === 'number' && typeof b.type.value === 'number') {
24      return (a.type.value ?? Number.MIN_VALUE) - (b.type.value ?? Number.MIN_VALUE);
25    }
26  }
27  return 0;
28};
29
30const renderEnumValue = (value: any) => (typeof value === 'string' ? `"${value}"` : value);
31
32const renderEnum = ({ name, children, comment }: EnumDefinitionData): JSX.Element => (
33  <div key={`enum-definition-${name}`} css={[STYLES_APIBOX, enumContentStyles]}>
34    <APISectionDeprecationNote comment={comment} />
35    <APISectionPlatformTags comment={comment} prefix="Only for:" />
36    <H3Code tags={getTagNamesList(comment)}>
37      <MONOSPACE weight="medium">{name}</MONOSPACE>
38    </H3Code>
39    <CommentTextBlock comment={comment} includePlatforms={false} />
40    {children.sort(sortByValue).map((enumValue: EnumValueData) => (
41      <div css={[STYLES_APIBOX, STYLES_APIBOX_NESTED]} key={enumValue.name}>
42        <APISectionDeprecationNote comment={enumValue.comment} />
43        <APISectionPlatformTags comment={enumValue.comment} prefix="Only for:" />
44        <H4 css={enumValueNameStyle}>
45          <CODE>{enumValue.name}</CODE>
46        </H4>
47        <CODE theme="secondary" className="mb-4">
48          {`${name}.${enumValue.name} = ${renderEnumValue(enumValue.type.value)}`}
49        </CODE>
50        <CommentTextBlock comment={enumValue.comment} includePlatforms={false} />
51      </div>
52    ))}
53  </div>
54);
55
56const APISectionEnums = ({ data }: APISectionEnumsProps) =>
57  data?.length ? (
58    <>
59      <H2 key="enums-header">Enums</H2>
60      {data.map(renderEnum)}
61    </>
62  ) : null;
63
64const enumValueNameStyle = css({
65  h4: {
66    marginTop: 0,
67  },
68});
69
70const enumContentStyles = css({
71  paddingBottom: 0,
72});
73
74export default APISectionEnums;
75