-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathList.tsx
86 lines (72 loc) · 2.25 KB
/
List.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import "./_list.scss";
import React, {Fragment, Ref} from "react";
import classNames from "classnames";
import {generateListItemKey} from "./util/listUtils";
export interface ListProps<Item = any> {
items: Item[];
children: (item: Item, testid: string, index?: number) => JSX.Element;
listItemKeyGenerator?: (item: Item, testid: string) => string;
testid?: string;
role?: string;
customClassName?: string;
placeholderProps?: {
shouldDisplayPlaceholder: boolean;
placeholder: React.ReactNode;
};
emptyStateProps?: {
shouldDisplayEmptyState: boolean;
emptyState: React.ReactNode;
};
type?: "unordered" | "ordered" | "description";
}
export type ListElementType = Extract<keyof JSX.IntrinsicElements, "ul" | "ol" | "dl">;
function ListComponent<Item extends any>(
{
items,
children,
customClassName,
testid,
listItemKeyGenerator,
placeholderProps,
emptyStateProps,
type = "unordered",
role
}: ListProps<Item>,
ref?: React.ForwardedRef<ListElementType>
) {
const listClassName = classNames("list", customClassName);
let ListTypeElement: Extract<keyof JSX.IntrinsicElements, "ul" | "ol" | "dl">;
switch (type) {
case "ordered":
ListTypeElement = "ol";
break;
case "description":
ListTypeElement = "dl";
break;
default:
ListTypeElement = "ul";
break;
}
return (
// @ts-ignore - ref type is compatible
<ListTypeElement ref={ref} className={listClassName} role={role} data-testid={testid}>
{items.map((item: Item, index: number) => {
const listItemTestId = `${testid}.item-${index}`;
return (
<Fragment
key={generateListItemKey({listItemKeyGenerator, listItemTestId, item})}>
{children(item, listItemTestId, index)}
</Fragment>
);
})}
{placeholderProps?.shouldDisplayPlaceholder && placeholderProps.placeholder}
{!placeholderProps?.shouldDisplayPlaceholder &&
emptyStateProps?.shouldDisplayEmptyState &&
emptyStateProps.emptyState}
</ListTypeElement>
);
}
const List = React.forwardRef<ListElementType, ListProps>(ListComponent);
export default List as <Item = any>(
props: ListProps<Item> & {ref?: Ref<ListElementType>}
) => JSX.Element;