Files
community-rule/app/components/controls/SelectInput/SelectInput.container.tsx
T

403 lines
12 KiB
TypeScript

"use client";
import React, {
Children,
type CSSProperties,
type ReactElement,
type ReactNode,
forwardRef,
useId,
useState,
useRef,
useCallback,
memo,
useImperativeHandle,
useEffect,
useLayoutEffect,
useMemo,
} from "react";
import { useClickOutside } from "../../../hooks";
import { useTranslation } from "../../../contexts/MessagesContext";
import { SelectInputView } from "./SelectInput.view";
import type { SelectInputProps, SelectOptionData } from "./SelectInput.types";
/**
* Figma: "Control / SelectInput". Custom-styled select dropdown
* with a labelled trigger button and floating option menu.
*/
const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
(
{
id,
labelText,
showLabel,
labelVariant: labelVariantProp,
size: sizeProp,
state: externalStateProp = "default",
asterisk = false,
iconHelp = true,
textOptional = false,
textData = true,
iconRight = true,
textHint = false,
disabled = false,
error = false,
placeholder,
className = "",
children,
value,
onChange,
options,
...props
},
ref,
) => {
const t = useTranslation("controlsChrome");
const resolvedPlaceholder = placeholder ?? t("selectPlaceholder");
// Determine if label should be shown
const shouldShowLabel =
showLabel !== undefined ? showLabel : labelText !== undefined;
let normalizedState = externalStateProp;
if (normalizedState === "state5" || normalizedState === "State5") {
normalizedState = "default";
}
const externalState = normalizedState;
const _labelVariant = labelVariantProp;
const _size = sizeProp;
void _labelVariant;
void _size;
const generatedId = useId();
const selectId = id || `select-input-${generatedId}`;
const labelId = `${selectId}-label`;
const listboxId = `${selectId}-listbox`;
const [isOpen, setIsOpen] = useState(false);
const [selectedValue, setSelectedValue] = useState(value || "");
const [highlightedIndex, setHighlightedIndex] = useState(0);
const [menuStyle, setMenuStyle] = useState<CSSProperties | null>(null);
const selectRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const optionItems = useMemo((): SelectOptionData[] => {
if (options && Array.isArray(options)) return options;
return Children.toArray(children).flatMap((child) => {
if (!React.isValidElement(child) || child.type !== "option") return [];
const optionProps = child.props as {
value: string;
children: ReactNode;
};
return [
{
value: optionProps.value,
label: String(optionProps.children),
},
];
});
}, [options, children]);
// Internal state management: track if focused and how (mouse vs keyboard)
const [isFocused, setIsFocused] = useState(false);
const [focusMethod, setFocusMethod] = useState<"mouse" | "keyboard" | null>(
null,
);
const wasMouseDownRef = useRef(false);
// Determine if we should auto-manage focus (only when state is "default" or undefined)
const shouldAutoManageFocus =
externalState === "default" || externalState === undefined;
// Sync internal state with external value prop
useEffect(() => {
if (value !== undefined && value !== selectedValue) {
setSelectedValue(value);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
useImperativeHandle(
ref,
() => selectRef.current as HTMLButtonElement | null,
);
const closeMenu = useCallback(() => {
setIsOpen(false);
setMenuStyle(null);
}, []);
// Handle click outside to close menu
useClickOutside([menuRef, selectRef], closeMenu, isOpen);
const indexForValue = useCallback(
(current: string) => {
const index = optionItems.findIndex((option) => option.value === current);
return index >= 0 ? index : 0;
},
[optionItems],
);
const openMenu = useCallback(() => {
const trigger = selectRef.current?.getBoundingClientRect();
setMenuStyle({
top: (trigger?.bottom ?? 0) + 4,
left: trigger?.left ?? 0,
width: Math.max(trigger?.width ?? 0, 200),
});
setHighlightedIndex(indexForValue(selectedValue));
setIsOpen(true);
}, [indexForValue, selectedValue]);
useLayoutEffect(() => {
if (!isOpen) {
setMenuStyle(null);
return;
}
const update = () => {
const trigger = selectRef.current;
if (!trigger) return;
const rect = trigger.getBoundingClientRect();
const menuHeight = menuRef.current?.offsetHeight ?? optionItems.length * 44 + 8;
const gap = 4;
const openUp =
rect.bottom + gap + menuHeight > window.innerHeight &&
rect.top > menuHeight + gap;
setMenuStyle({
top: openUp
? Math.max(8, rect.top - menuHeight - gap)
: rect.bottom + gap,
left: rect.left,
width: Math.max(rect.width, 200),
});
};
update();
window.addEventListener("resize", update);
window.addEventListener("scroll", update, true);
return () => {
window.removeEventListener("resize", update);
window.removeEventListener("scroll", update, true);
};
}, [isOpen, optionItems.length, highlightedIndex]);
// Handle option selection
const handleOptionSelect = useCallback(
(optionValue: string, optionText: string) => {
setSelectedValue(optionValue);
closeMenu();
if (onChange) {
onChange({ target: { value: optionValue, text: optionText } });
}
if (selectRef.current) {
selectRef.current.focus();
}
},
[closeMenu, onChange],
);
// Handle mouse down to detect mouse clicks
const handleMouseDown = useCallback(() => {
if (!disabled && shouldAutoManageFocus) {
wasMouseDownRef.current = true;
}
}, [disabled, shouldAutoManageFocus]);
// Handle select button click
const handleSelectClick = useCallback(() => {
if (disabled) return;
if (isOpen) {
closeMenu();
return;
}
openMenu();
}, [closeMenu, disabled, isOpen, openMenu]);
// Handle keyboard navigation
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLButtonElement>) => {
if (disabled) return;
if (e.key === "ArrowDown") {
e.preventDefault();
if (!isOpen) {
openMenu();
return;
}
setHighlightedIndex((index) =>
Math.min(index + 1, Math.max(optionItems.length - 1, 0)),
);
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
if (!isOpen) {
openMenu();
return;
}
setHighlightedIndex((index) => Math.max(index - 1, 0));
return;
}
if (e.key === "Home" && isOpen) {
e.preventDefault();
setHighlightedIndex(0);
return;
}
if (e.key === "End" && isOpen) {
e.preventDefault();
setHighlightedIndex(Math.max(optionItems.length - 1, 0));
return;
}
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
if (!isOpen) {
openMenu();
return;
}
const option = optionItems[highlightedIndex];
if (option) {
handleOptionSelect(option.value, option.label);
}
return;
}
if (e.key === "Escape") {
if (!isOpen) return;
e.preventDefault();
e.stopPropagation();
closeMenu();
}
},
[
closeMenu,
disabled,
handleOptionSelect,
highlightedIndex,
isOpen,
openMenu,
optionItems,
],
);
// Handle focus to detect mouse vs keyboard
const handleFocus = useCallback(() => {
if (disabled) return;
const method = wasMouseDownRef.current ? "mouse" : "keyboard";
if (shouldAutoManageFocus) {
setIsFocused(true);
setFocusMethod(method);
wasMouseDownRef.current = false;
}
}, [disabled, shouldAutoManageFocus]);
const handleMenuMouseDown = useCallback((event: React.MouseEvent) => {
event.preventDefault();
}, []);
const handleBlur = useCallback(
(event: React.FocusEvent<HTMLButtonElement>) => {
if (shouldAutoManageFocus) {
setIsFocused(false);
setFocusMethod(null);
wasMouseDownRef.current = false;
}
const next = event.relatedTarget;
if (next instanceof Node && menuRef.current?.contains(next)) return;
closeMenu();
},
[closeMenu, shouldAutoManageFocus],
);
// Determine actual state:
// - Active: when clicked (mouse focus) or when dropdown is open
// - Focus: when tabbed (keyboard focus)
// - Default: when not focused
const actualState = shouldAutoManageFocus
? isOpen || isFocused
? focusMethod === "mouse" || isOpen
? "active"
: "focus"
: "default"
: externalState;
// Determine if select is filled (has selected value)
const isFilled = Boolean(selectedValue && selectedValue.trim().length > 0);
// Get display text for selected value
const getDisplayText = (): string => {
if (!selectedValue) return resolvedPlaceholder;
if (options && Array.isArray(options)) {
const selectedOption = options.find(
(option) => option.value === selectedValue,
);
return selectedOption ? selectedOption.label : resolvedPlaceholder;
}
const selectedOption = Children.toArray(children).find(
(
child,
): child is ReactElement<{
value: string;
children: ReactNode;
}> => {
if (!React.isValidElement(child)) return false;
const props = child.props as {
value?: string;
children?: ReactNode;
};
return props.value === selectedValue;
},
);
return selectedOption
? String(selectedOption.props.children)
: resolvedPlaceholder;
};
return (
<SelectInputView
label={shouldShowLabel ? labelText : undefined}
placeholder={resolvedPlaceholder}
state={actualState}
disabled={disabled}
error={error}
className={className}
options={options}
selectId={selectId}
labelId={labelId}
isOpen={isOpen}
selectedValue={selectedValue}
displayText={getDisplayText()}
isFilled={isFilled}
onButtonClick={handleSelectClick}
onButtonKeyDown={handleKeyDown}
onButtonMouseDown={handleMouseDown}
onButtonFocus={handleFocus}
onButtonBlur={handleBlur}
onMenuMouseDown={handleMenuMouseDown}
onOptionClick={handleOptionSelect}
selectRef={selectRef}
menuRef={menuRef}
listboxId={listboxId}
highlightedIndex={highlightedIndex}
menuStyle={menuStyle}
ariaLabelledby={shouldShowLabel ? labelId : undefined}
ariaInvalid={error}
asterisk={asterisk}
iconHelp={iconHelp}
textOptional={textOptional}
textData={textData}
iconRight={iconRight}
textHint={textHint}
selectAriaLabel={t("selectAriaLabel")}
hintDefault={t("hintDefault")}
{...props}
/>
);
},
);
SelectInputContainer.displayName = "SelectInput";
export default memo(SelectInputContainer);