List components #31

Merged
stne3960 merged 68 commits from list_item into main 2025-12-18 12:41:13 +01:00
2 changed files with 237 additions and 209 deletions
Showing only changes of commit 14ab479b26 - Show all commits

View File

@ -1,15 +1,21 @@
import { useState, useRef, useEffect } from 'react'; import { useState, useRef, useEffect } from "react";
import TextInput from '../TextInput/TextInput'; import clsx from "clsx";
import SearchResultList, { type SearchResultOption } from '../SearchResultList/SearchResultList'; import TextInput from "../TextInput/TextInput";
import { SearchIcon } from "../Icon/Icon";
import SearchResultList, {
type SearchResultOption,
} from "../SearchResultList/SearchResultList";
import { useClickOutside } from "../../hooks/useClickOutside";
export type ComboboxOption = SearchResultOption; export type ComboboxOption = SearchResultOption;
export type ComboboxSize = 'sm' | 'md' | 'lg'; export type ComboboxSize = "sm" | "md" | "lg";
export interface ComboboxProps { export interface ComboboxProps {
options: ComboboxOption[]; options: ComboboxOption[];
placeholder?: string; placeholder?: string;
label?: string; label: string;
hideLabel?: boolean;
size?: ComboboxSize; size?: ComboboxSize;
fullWidth?: boolean; fullWidth?: boolean;
customWidth?: string; customWidth?: string;
@ -23,63 +29,56 @@ export interface ComboboxProps {
} }
const widthClasses: Record<ComboboxSize, string> = { const widthClasses: Record<ComboboxSize, string> = {
sm: 'w-(--text-input-default-width-md)', sm: "w-(--text-input-default-width-md)",
md: 'w-(--text-input-default-width-md)', md: "w-(--text-input-default-width-md)",
lg: 'w-(--text-input-default-width-lg)', lg: "w-(--text-input-default-width-lg)",
}; };
const dropdownWrapperClasses = 'absolute top-full left-0 z-50 w-full mt-(--spacing-sm)'; const dropdownWrapperClasses =
"absolute top-full left-0 z-50 w-full mt-(--spacing-sm)";
function SearchIcon({ className }: { className?: string }) { /**
return ( * Scrolls the focused item into view when navigating with arrow keys.
<svg * Uses "nearest" to minimize scrolling - only scrolls if the item is outside the visible area.
className={className} */
viewBox="0 0 24 24" function useScrollIntoView(
fill="none" index: number,
stroke="currentColor" refs: React.RefObject<(HTMLDivElement | null)[]>,
strokeWidth="2" ) {
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="11" cy="11" r="8" />
<path d="M21 21l-4.35-4.35" />
</svg>
);
}
function useClickOutside(ref: React.RefObject<HTMLElement | null>, onClickOutside: () => void) {
useEffect(() => {
const handleClick = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
onClickOutside();
}
};
document.addEventListener('mousedown', handleClick);
return () => document.removeEventListener('mousedown', handleClick);
}, [ref, onClickOutside]);
}
function useScrollIntoView(index: number, refs: React.RefObject<(HTMLDivElement | null)[]>) {
useEffect(() => { useEffect(() => {
if (index >= 0 && refs.current[index]) { if (index >= 0 && refs.current[index]) {
refs.current[index]?.scrollIntoView({ block: 'nearest' }); refs.current[index]?.scrollIntoView({ block: "nearest" });
} }
}, [index, refs]); }, [index, refs]);
} }
function filterOptions(options: ComboboxOption[], searchTerm: string): ComboboxOption[] { function filterOptions(
options: ComboboxOption[],
searchTerm: string,
): ComboboxOption[] {
const term = searchTerm.toLowerCase(); const term = searchTerm.toLowerCase();
return options.filter( return options.filter(
(opt) => opt.label.toLowerCase().includes(term) || opt.subtitle?.toLowerCase().includes(term), (opt) =>
opt.label.toLowerCase().includes(term) ||
opt.subtitle?.toLowerCase().includes(term),
); );
} }
function getNextIndex(currentIndex: number, direction: 'up' | 'down', maxIndex: number): number { function getNextIndex(
const next = currentIndex + (direction === 'down' ? 1 : -1); currentIndex: number,
direction: "up" | "down",
maxIndex: number,
): number {
const next = currentIndex + (direction === "down" ? 1 : -1);
return Math.max(0, Math.min(next, maxIndex)); return Math.max(0, Math.min(next, maxIndex));
} }
/**
* Determines what text to display in the input field.
* - If user is typing, show the search term
* - If multi-select mode, show nothing (selections appear as ListCards below)
* - If single-select with a selection, show the selected option's label
*/
function getDisplayValue( function getDisplayValue(
options: ComboboxOption[], options: ComboboxOption[],
selectedValues: string[], selectedValues: string[],
@ -89,46 +88,53 @@ function getDisplayValue(
if (searchTerm) return searchTerm; if (searchTerm) return searchTerm;
if (multiple) { if (multiple) {
return ''; return "";
} }
if (selectedValues.length === 0) return ''; if (selectedValues.length === 0) return "";
return options.find((opt) => opt.value === selectedValues[0])?.label || ''; return options.find((opt) => opt.value === selectedValues[0])?.label || "";
} }
export default function Combobox({ export default function Combobox({
options, options,
placeholder = 'Search...', placeholder = "Search...",
label, label,
size = 'md', hideLabel = false,
size = "md",
fullWidth = false, fullWidth = false,
customWidth, customWidth,
dropdownHeight = 300, dropdownHeight = 300,
noResultsText = 'No results found', noResultsText = "No results found",
multiple = false, multiple = false,
value, value,
onChange, onChange,
onSearchChange, onSearchChange,
}: ComboboxProps) { }: ComboboxProps) {
// Normalize value to array for internal use // Convert value (undefined | string | string[]) to always be an array
const selectedValues: string[] = value === undefined ? [] : Array.isArray(value) ? value : [value]; const selectedValues: string[] =
value === undefined ? [] : Array.isArray(value) ? value : [value];
// State
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [searchTerm, setSearchTerm] = useState(''); const [searchTerm, setSearchTerm] = useState("");
const [focusedIndex, setFocusedIndex] = useState(-1); const [focusedIndex, setFocusedIndex] = useState(-1);
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const itemRefs = useRef<(HTMLDivElement | null)[]>([]); const itemRefs = useRef<(HTMLDivElement | null)[]>([]);
// Derived state - skip local filtering when onSearchChange is provided (API handles filtering) // Derived state - skip local filtering when onSearchChange is provided (API handles filtering)
const filteredOptions = onSearchChange ? options : filterOptions(options, searchTerm); const filteredOptions = onSearchChange
const displayValue = getDisplayValue(options, selectedValues, multiple, searchTerm); ? options
: filterOptions(options, searchTerm);
const displayValue = getDisplayValue(
options,
selectedValues,
multiple,
searchTerm,
);
const closeDropdown = () => setIsOpen(false); const closeDropdown = () => setIsOpen(false);
// Hooks
useClickOutside(containerRef, closeDropdown); useClickOutside(containerRef, closeDropdown);
useScrollIntoView(focusedIndex, itemRefs); useScrollIntoView(focusedIndex, itemRefs);
@ -138,10 +144,10 @@ export default function Combobox({
setSearchTerm(value); setSearchTerm(value);
onSearchChange?.(value); onSearchChange?.(value);
if (value === '') { if (value === "") {
// Clear selection when user empties the field in single-select mode // Clear selection when user empties the field in single-select mode
if (!multiple && selectedValues.length > 0) { if (!multiple && selectedValues.length > 0) {
onChange?.(''); onChange?.("");
} }
closeDropdown(); closeDropdown();
} else { } else {
@ -161,14 +167,14 @@ export default function Combobox({
// Replace selection in single-select mode // Replace selection in single-select mode
onChange?.(option.value); onChange?.(option.value);
} }
setSearchTerm(''); // Clear search so selected label shows setSearchTerm(""); // Clear search so selected label shows
closeDropdown(); closeDropdown();
}; };
const handleKeyDown = (e: React.KeyboardEvent) => { const handleKeyDown = (e: React.KeyboardEvent) => {
// Open dropdown on arrow keys when closed (only if we have options to show) // Open dropdown on arrow keys when closed (only if we have options to show)
if (!isOpen) { if (!isOpen) {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { if (e.key === "ArrowDown" || e.key === "ArrowUp") {
if (filteredOptions.length > 0) { if (filteredOptions.length > 0) {
setIsOpen(true); setIsOpen(true);
} }
@ -179,35 +185,39 @@ export default function Combobox({
// Handle navigation when open // Handle navigation when open
switch (e.key) { switch (e.key) {
case 'ArrowDown': case "ArrowDown":
e.preventDefault(); e.preventDefault();
setFocusedIndex((prev) => getNextIndex(prev, 'down', filteredOptions.length - 1)); setFocusedIndex((prev) =>
getNextIndex(prev, "down", filteredOptions.length - 1),
);
break; break;
case 'ArrowUp': case "ArrowUp":
e.preventDefault(); e.preventDefault();
setFocusedIndex((prev) => getNextIndex(prev, 'up', filteredOptions.length - 1)); setFocusedIndex((prev) =>
getNextIndex(prev, "up", filteredOptions.length - 1),
);
break; break;
case 'Enter': case "Enter":
e.preventDefault(); e.preventDefault();
if (focusedIndex >= 0 && focusedIndex < filteredOptions.length) { if (focusedIndex >= 0 && focusedIndex < filteredOptions.length) {
handleSelect(filteredOptions[focusedIndex]); handleSelect(filteredOptions[focusedIndex]);
} }
break; break;
case 'Escape': case "Escape":
case 'Tab': case "Tab":
closeDropdown(); closeDropdown();
break; break;
} }
}; };
const containerClasses = fullWidth const containerClasses = clsx(
? 'relative w-full' "relative",
: customWidth fullWidth && "w-full",
? 'relative' !fullWidth && !customWidth && widthClasses[size],
: `relative ${widthClasses[size]}`; );
const widthStyle = customWidth ? { width: customWidth } : undefined; const widthStyle = customWidth ? { width: customWidth } : undefined;
return ( return (
@ -219,10 +229,11 @@ export default function Combobox({
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
placeholder={placeholder} placeholder={placeholder}
label={label} label={label}
hideLabel={hideLabel}
size={size} size={size}
fullWidth={fullWidth || !!customWidth} fullWidth={fullWidth || !!customWidth}
customWidth={customWidth} customWidth={customWidth}
icon={<SearchIcon />} Icon={SearchIcon}
/> />
{isOpen && ( {isOpen && (

View File

@ -0,0 +1,17 @@
import { useEffect } from "react";
export function useClickOutside(
ref: React.RefObject<HTMLElement | null>,
onClickOutside: () => void,
) {
useEffect(() => {
const handleClick = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
onClickOutside();
}
};
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [ref, onClickOutside]);
}