-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathItem.tsx
More file actions
executable file
·84 lines (72 loc) · 2.95 KB
/
Item.tsx
File metadata and controls
executable file
·84 lines (72 loc) · 2.95 KB
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
import React, { useCallback, useMemo } from "react";
import { COLORS, DEFAULT_CLASSNAMES, DEFAULT_THEME, THEME_DATA } from "../constants";
import DisabledItem from "./DisabledItem";
import { useSelectContext } from "./SelectProvider";
import { Option } from "./type";
interface ItemProps {
item: Option;
primaryColor: string;
}
const Item: React.FC<ItemProps> = ({ item, primaryColor }) => {
const { classNames, value, handleValueChange, formatOptionLabel } = useSelectContext();
const isSelected = useMemo(() => {
return value !== null && !Array.isArray(value) && value.value === item.value;
}, [item.value, value]);
const textHoverColor = useMemo(() => {
if (COLORS.includes(primaryColor)) {
return THEME_DATA.textHover[primaryColor as keyof typeof THEME_DATA.textHover];
}
return THEME_DATA.textHover[DEFAULT_THEME];
}, [primaryColor]);
const bgColor = useMemo(() => {
if (COLORS.includes(primaryColor)) {
return THEME_DATA.bg[primaryColor as keyof typeof THEME_DATA.bg];
}
return THEME_DATA.bg[DEFAULT_THEME];
}, [primaryColor]);
const bgHoverColor = useMemo(() => {
if (COLORS.includes(primaryColor)) {
return THEME_DATA.bgHover[primaryColor as keyof typeof THEME_DATA.bgHover];
}
return THEME_DATA.bgHover[DEFAULT_THEME];
}, [primaryColor]);
const getItemClass = useCallback(() => {
const selectedClass = isSelected
? `text-white ${bgColor}`
: `text-gray-500 ${bgHoverColor} ${textHoverColor}`;
return classNames && classNames.listItem
? classNames.listItem(DEFAULT_CLASSNAMES.listItem, { isSelected })
: `${DEFAULT_CLASSNAMES.listItem} ${selectedClass}`;
}, [bgColor, bgHoverColor, classNames, isSelected, textHoverColor]);
return (
<>
{formatOptionLabel ? (
<div onClick={() => handleValueChange(item)}>
{formatOptionLabel({ ...item, isSelected })}
</div>
) : (
<>
{item.disabled ? (
<DisabledItem>{item.label}</DisabledItem>
) : (
<li
tabIndex={0}
onKeyDown={(e: React.KeyboardEvent<HTMLLIElement>) => {
if (e.key === " " || e.key === "Enter") {
handleValueChange(item);
}
}}
aria-selected={isSelected}
role={"option"}
onClick={() => handleValueChange(item)}
className={getItemClass()}
>
{item.label}
</li>
)}
</>
)}
</>
);
};
export default Item;