@trail-ui/react
Version:
460 lines (457 loc) • 15.8 kB
JavaScript
import {
Overlay,
Positions
} from "./chunk-R44NAPT5.mjs";
import {
Input,
Label
} from "./chunk-DYJZEB7Z.mjs";
import {
Text
} from "./chunk-VIVC5TFC.mjs";
// src/select/customSelect.tsx
import { multiselect } from "@trail-ui/theme";
import React, {
useState,
useRef,
useEffect,
forwardRef,
useMemo
} from "react";
import { CheckIcon, ChevronDownIcon, ErrorIcon } from "@trail-ui/icons";
import { Button } from "react-aria-components";
import { jsx, jsxs } from "react/jsx-runtime";
var Keys = {
Backspace: "Backspace",
Clear: "Clear",
Down: "ArrowDown",
End: "End",
Enter: "Enter",
Escape: "Escape",
Home: "Home",
Left: "ArrowLeft",
PageDown: "PageDown",
PageUp: "PageUp",
Right: "ArrowRight",
Space: " ",
Tab: "Tab",
Up: "ArrowUp"
};
var MenuActions = {
Close: "Close",
CloseSelect: "CloseSelect",
First: "First",
Last: "Last",
Next: "Next",
Open: "Open",
Previous: "Previous",
Select: "Select",
Space: "Space",
Type: "Type"
};
function getActionFromKey(key, menuOpen) {
if (!menuOpen && key === Keys.Down)
return MenuActions.Open;
if (!menuOpen && key === Keys.Enter)
return MenuActions.Open;
if (key === Keys.Down)
return MenuActions.Next;
if (key === Keys.Up)
return MenuActions.Previous;
if (key === Keys.Home)
return MenuActions.First;
if (key === Keys.End)
return MenuActions.Last;
if (key === Keys.Escape)
return MenuActions.Close;
if (key === Keys.Enter)
return MenuActions.CloseSelect;
if (key === Keys.Backspace || key === Keys.Clear || key.length === 1)
return MenuActions.Type;
return void 0;
}
var CustomSelect = forwardRef(
({
options,
label,
labelKey = "value",
valueKey = "id",
id = "select",
onChange,
onBlur,
defaultValue,
classNames,
errorMessage,
description,
errorIcon = /* @__PURE__ */ jsx(
ErrorIcon,
{
className: "h-4 w-4 text-red-800 dark:text-red-600",
role: "img",
"aria-label": "Error",
"aria-hidden": false
}
),
errorId,
isRequired,
isDisabled,
isInvalid,
placeholder = "Select items",
value: selectedValue,
form,
name,
maxOptionsBeforeConversionToComboBox = 6,
isCombobox,
...otherprops
}, ref) => {
const [isOpen, setIsOpen] = useState(false);
const [searchValue, setSearchValue] = useState("");
const [activeIndex, setActiveIndex] = useState(-1);
const [value, setValue] = useState({ label: "", value: "" });
const listboxRef = useRef(null);
const inputRef = useRef(null);
const localRef = useRef(null);
const buttonRef = useRef(null);
const optionRefs = useRef([]);
const hiddenInputRef = useRef(null);
const refElementForOverlay = useRef(null);
const slots = useMemo(() => multiselect(), []);
const isComponentCombobox = useMemo(() => {
if (isCombobox !== void 0) {
return isCombobox;
} else {
return options.length > maxOptionsBeforeConversionToComboBox;
}
}, [isCombobox, options, maxOptionsBeforeConversionToComboBox]);
const getOptionLabel = (option) => {
if (typeof option === "string")
return option;
return option[labelKey] || option.label || "";
};
const getOptionValue = (option) => {
if (typeof option === "string")
return option;
return option[valueKey] || option.value || "";
};
const resetIndex = () => setActiveIndex(-1);
const filteredOptions = useMemo(
() => options.filter((option) => {
return getOptionLabel(option).toString().toLowerCase().includes(searchValue.toLowerCase());
}),
[searchValue, options]
);
const toggleDropdown = () => setIsOpen((prevState) => !prevState);
const toggleItem = (option) => {
if (isDisabled)
return;
onChange(option.value);
setSearchValue("");
toggleDropdown();
if (inputRef.current) {
inputRef.current.focus();
inputRef.current.value = getOptionLabel(option);
}
if (buttonRef.current) {
buttonRef.current.focus();
}
if (hiddenInputRef.current) {
hiddenInputRef.current.value = getOptionLabel(option);
}
};
const handleInputChange = (e) => {
if (isDisabled)
return;
setSearchValue(e.target.value);
if (!isOpen)
toggleDropdown();
if (activeIndex === -1) {
setActiveIndex(0);
}
};
function getUpdatedIndex(current, action) {
switch (action) {
case MenuActions.First:
return 0;
case MenuActions.Last:
return filteredOptions.length;
case MenuActions.Previous:
return (activeIndex - 1 + filteredOptions.length) % filteredOptions.length;
case MenuActions.Next:
return (activeIndex + 1) % filteredOptions.length;
default:
return current;
}
}
const handleKeyDown = (e) => {
var _a, _b;
const action = getActionFromKey(e.key, isOpen);
if (isDisabled) {
e.preventDefault();
e.stopPropagation();
return;
}
if (e.key === Keys.Tab) {
if (isOpen) {
toggleDropdown();
resetIndex();
setSearchValue("");
}
return;
}
if (!action)
return;
if (MenuActions.Type !== action)
e.preventDefault();
switch (action) {
case MenuActions.Next:
case MenuActions.Last:
case MenuActions.First:
case MenuActions.Previous:
const nextIndex = getUpdatedIndex(activeIndex, action);
setActiveIndex(nextIndex);
(_a = optionRefs.current[nextIndex].current) == null ? void 0 : _a.focus();
break;
case MenuActions.Type:
if (inputRef.current)
inputRef.current.focus();
break;
case MenuActions.CloseSelect:
if (activeIndex >= 0) {
(_b = optionRefs.current[activeIndex].current) == null ? void 0 : _b.click();
}
break;
case MenuActions.Close:
handleOnClick({ detail: 1 });
setSearchValue("");
resetIndex();
break;
case MenuActions.Open:
handleOnClick({ detail: 1 });
break;
}
};
const handleOnClick = (e) => {
if (!isDisabled && (e == null ? void 0 : e.detail) === 1) {
toggleDropdown();
if (isOpen) {
resetIndex();
}
}
};
useEffect(() => {
const handleClickOutside = (event) => {
if (localRef.current && !localRef.current.contains(event.target)) {
setIsOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
useEffect(() => {
if (!ref)
return;
if (typeof ref === "function") {
ref(localRef.current);
} else {
ref.current = localRef.current;
}
}, [ref]);
useEffect(() => {
const index = options.findIndex((item) => item.value === selectedValue);
setValue(index !== -1 ? options[index] : { label: "", value: "" });
}, [selectedValue, options]);
useEffect(() => {
var _a;
if (isOpen) {
(_a = buttonRef.current) == null ? void 0 : _a.setAttribute("role", "combobox");
optionRefs.current = filteredOptions.map(
(_, i) => optionRefs.current[i] || React.createRef()
);
if (filteredOptions.length > 1 && !isCombobox) {
setActiveIndex(0);
}
}
}, [isOpen]);
useEffect(() => {
if (filteredOptions.length > 0) {
resetIndex();
}
}, [filteredOptions]);
useEffect(() => {
var _a, _b;
if (isOpen && activeIndex >= 0) {
requestAnimationFrame(() => {
var _a2, _b2;
(_b2 = (_a2 = optionRefs.current[activeIndex]) == null ? void 0 : _a2.current) == null ? void 0 : _b2.scrollIntoView({ block: "nearest" });
});
}
if (isOpen)
(_a = buttonRef.current) == null ? void 0 : _a.setAttribute("aria-activedescendant", `${id}-option-${activeIndex}`);
else
(_b = buttonRef.current) == null ? void 0 : _b.removeAttribute("aria-activedescendant");
}, [activeIndex]);
return /* @__PURE__ */ jsxs(
"div",
{
ref: localRef,
className: "group relative flex w-full max-w-xs flex-col transition-opacity duration-200 data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 motion-reduce:transition-none",
children: [
/* @__PURE__ */ jsx(
Label,
{
id: `${id}-label`,
isDisabled,
requiredHint: isRequired,
className: slots.label({ class: classNames == null ? void 0 : classNames.label }),
children: label
}
),
/* @__PURE__ */ jsxs("div", { ref: refElementForOverlay, className: "relative", children: [
/* @__PURE__ */ jsx(
"input",
{
ref: hiddenInputRef,
type: "hidden",
name,
value: getOptionValue(value),
form,
required: isRequired
}
),
/* @__PURE__ */ jsx("div", { className: slots.control({ class: classNames == null ? void 0 : classNames.control }), children: /* @__PURE__ */ jsxs("div", { className: "flex flex-1 items-center gap-2", children: [
isComponentCombobox ? /* @__PURE__ */ jsx(
Input,
{
ref: inputRef,
autoComplete: "off",
"aria-autocomplete": "list",
"aria-labelledby": `${id}-label`,
onBlur,
className: slots.input({ class: classNames == null ? void 0 : classNames.input }),
onChange: handleInputChange,
onKeyDown: handleKeyDown,
onClick: handleOnClick,
placeholder: !getOptionValue(value) ? `${placeholder}` : "",
"aria-expanded": isOpen,
"aria-controls": isOpen ? "select-combobox" : void 0,
"aria-activedescendant": isOpen && activeIndex >= 0 ? `${id}-option-${activeIndex}` : void 0,
disabled: isDisabled,
required: isRequired && !getOptionValue(value) && !searchValue,
"aria-invalid": isInvalid,
"aria-required": isRequired,
role: "combobox",
"aria-describedby": errorId || "",
"aria-haspopup": "listbox",
...otherprops
}
) : /* @__PURE__ */ jsx(
Button,
{
ref: buttonRef,
onKeyDown: handleKeyDown,
onClick: handleOnClick,
className: slots.input({ class: classNames == null ? void 0 : classNames.label }) + ` text-left`,
"aria-expanded": isOpen,
"aria-controls": isOpen ? "select-listbox" : void 0,
"aria-activedescendant": isOpen && activeIndex >= 0 ? `${id}-option-${activeIndex}` : void 0,
"aria-invalid": isInvalid,
"aria-required": isRequired,
"aria-describedby": errorId || "",
"aria-labelledby": `${id}-label`,
isDisabled,
"aria-haspopup": "listbox",
...otherprops,
children: getOptionLabel(value) || placeholder
}
),
/* @__PURE__ */ jsx(
ChevronDownIcon,
{
height: 24,
width: 24,
onKeyDown: handleKeyDown,
onClick: (e) => {
var _a, _b;
handleOnClick(e);
(_a = inputRef.current) == null ? void 0 : _a.focus();
(_b = buttonRef.current) == null ? void 0 : _b.focus();
},
className: `${isOpen ? "rotate-180" : ""} cursor-pointer`
}
)
] }) }),
errorMessage ? /* @__PURE__ */ jsxs(
Text,
{
id: errorId,
slot: "errorMessage",
elementType: "div",
className: slots.errorMessage({
class: classNames == null ? void 0 : classNames.errorMessage
}),
children: [
errorIcon,
/* @__PURE__ */ jsx("span", { children: errorMessage })
]
}
) : description ? /* @__PURE__ */ jsx(
Text,
{
slot: "description",
elementType: "div",
className: slots.description({ class: classNames == null ? void 0 : classNames.description }),
children: /* @__PURE__ */ jsx("span", { children: description })
}
) : null
] }),
isOpen && filteredOptions.length > 0 && /* @__PURE__ */ jsx(
Overlay,
{
referenceElement: refElementForOverlay,
position: Positions.bottom,
style: { maxHeight: 240 },
offset: { x: 8, y: 8 },
children: /* @__PURE__ */ jsx(
"ul",
{
ref: listboxRef,
role: "listbox",
id: `select-${isComponentCombobox ? "combobox " : "listbox"}`,
"aria-label": label,
className: "absolute z-30 max-h-60 w-full overflow-auto rounded-md bg-neutral-50 py-2 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none",
children: filteredOptions.map((option, index) => {
const isActive = index === activeIndex;
return /* @__PURE__ */ jsxs(
"li",
{
ref: optionRefs.current[index],
role: "option",
id: `${id}-option-${index}`,
"aria-selected": getOptionValue(value) === getOptionValue(option),
tabIndex: isActive ? 0 : -1,
className: `relative flex cursor-pointer justify-between border-l-[3px] p-2 hover:bg-purple-50 focus:bg-purple-50 ${isActive ? "border-purple-600 bg-purple-50" : "border-transparent"} ${getOptionValue(value) === getOptionValue(option) ? "font-medium" : ""}`,
onClick: () => toggleItem(option),
onKeyDown: handleKeyDown,
onMouseEnter: () => setActiveIndex(index),
children: [
/* @__PURE__ */ jsx("span", { className: `block truncate text-sm text-neutral-900`, children: getOptionLabel(option) }),
getOptionValue(value) === getOptionValue(option) && /* @__PURE__ */ jsx("span", { className: "flex items-center pl-1.5", children: /* @__PURE__ */ jsx(CheckIcon, { className: "h-5 w-5 text-purple-600" }) })
]
},
getOptionValue(option)
);
})
}
)
}
)
]
}
);
}
);
CustomSelect.displayName = "CustomSelectComponent";
var customSelect_default = CustomSelect;
export {
customSelect_default
};