|
1
|
import { |
|
2
|
ComponentPropsWithoutRef, |
|
3
|
forwardRef, |
|
4
|
useImperativeHandle, |
|
5
|
useRef, |
|
6
|
} from "react" |
|
7
|
|
|
8
|
import { TrianglesMini } from "@medusajs/icons" |
|
9
|
import { clx } from "@medusajs/ui" |
|
10
|
import { countries } from "../../lib/data/countries" |
|
11
|
|
|
12
|
export const CountrySelect = forwardRef< |
|
13
|
HTMLSelectElement, |
|
14
|
ComponentPropsWithoutRef<"select"> & { |
|
15
|
placeholder?: string |
|
16
|
value?: string |
|
17
|
defaultValue?: string |
|
18
|
} |
|
19
|
>( |
|
20
|
( |
|
21
|
{ className, disabled, placeholder, value, defaultValue, ...props }, |
|
22
|
ref |
|
23
|
) => { |
|
24
|
const innerRef = useRef<HTMLSelectElement>(null) |
|
25
|
|
|
26
|
useImperativeHandle(ref, () => innerRef.current as HTMLSelectElement) |
|
27
|
|
|
28
|
const isPlaceholder = innerRef.current?.value === "" |
|
29
|
|
|
30
|
return ( |
|
31
|
<div className="relative"> |
|
32
|
<TrianglesMini |
|
33
|
className={clx( |
|
34
|
"text-ui-fg-muted transition-fg pointer-events-none absolute right-2 top-1/2 -translate-y-1/2", |
|
35
|
{ |
|
36
|
"text-ui-fg-disabled": disabled, |
|
37
|
} |
|
38
|
)} |
|
39
|
/> |
|
40
|
<select |
|
41
|
value={value !== undefined ? value.toLowerCase() : undefined} |
|
42
|
defaultValue={defaultValue ? defaultValue.toLowerCase() : undefined} |
|
43
|
disabled={disabled} |
|
44
|
className={clx( |
|
45
|
"bg-ui-bg-field shadow-buttons-neutral transition-fg txt-compact-small flex w-full select-none appearance-none items-center justify-between rounded-md px-2 py-1.5 outline-none", |
|
46
|
"placeholder:text-ui-fg-muted text-ui-fg-base", |
|
47
|
"hover:bg-ui-bg-field-hover", |
|
48
|
"focus-visible:shadow-borders-interactive-with-active data-[state=open]:!shadow-borders-interactive-with-active", |
|
49
|
"aria-[invalid=true]:border-ui-border-error aria-[invalid=true]:shadow-borders-error", |
|
50
|
"invalid::border-ui-border-error invalid:shadow-borders-error", |
|
51
|
"disabled:!bg-ui-bg-disabled disabled:!text-ui-fg-disabled", |
|
52
|
{ |
|
53
|
"text-ui-fg-muted": isPlaceholder, |
|
54
|
}, |
|
55
|
className |
|
56
|
)} |
|
57
|
{...props} |
|
58
|
ref={innerRef} |
|
59
|
> |
|
60
|
{/* Add an empty option so the first option is preselected */} |
|
61
|
<option value="" disabled className="text-ui-fg-muted"> |
|
62
|
{placeholder || "Select country"} |
|
63
|
</option> |
|
64
|
{countries.map((country) => { |
|
65
|
return ( |
|
66
|
<option key={country.iso_2} value={country.iso_2.toLowerCase()}> |
|
67
|
{country.display_name} |
|
68
|
</option> |
|
69
|
) |
|
70
|
})} |
|
71
|
</select> |
|
72
|
</div> |
|
73
|
) |
|
74
|
} |
|
75
|
) |
|
76
|
CountrySelect.displayName = "CountrySelect" |