Files
TREK/client/src/components/Planner/useSuggestionDropdown.ts
T
Maurice eb271f0d45 refactor(planner): share the suggestion dropdown between the airport, location and address fields
AirportSelect, LocationSelect and AddressInput each carried their own copy
of the open state, the keyboard highlight, the outside click that closes the
list, the floating list with its loading line and the suggestion row.

useSuggestionDropdown now holds the open state, the highlight, the outside
click and the arrow, Enter and Escape handling. SuggestionDropdown.tsx holds
the boxed input with its icon and clear button (airport and location), the
floating list (all three), the row button and the place row content
(location and address).

What still differs between the fields stays with them or is a parameter:
the icon, the placeholder, what typing does (LocationSelect also resets the
highlight), the rows the keys walk (LocationSelect walks the trip's places
below three characters), whether the loading line may show (not while
LocationSelect offers the trip's places) and how a row lines up its content
(centred for airports). Each field keeps its own query, search and pick.
2026-10-09 16:15:48 +02:00

39 lines
1.5 KiB
TypeScript

import type React from 'react';
import { useEffect, useRef, useState } from 'react';
/**
* The open state, the keyboard highlight and the outside click that closes the
* list, shared by the planner's search fields (AirportSelect, LocationSelect and
* AddressInput). Each field keeps its own query, search and pick.
*/
export function useSuggestionDropdown() {
const [open, setOpen] = useState(false);
const [highlight, setHighlight] = useState(-1);
const wrapRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handler = (e: MouseEvent) => {
if (!wrapRef.current?.contains(e.target as Node)) setOpen(false);
};
if (open) document.addEventListener('mousedown', handler);
return () => document.removeEventListener('mousedown', handler);
}, [open]);
/** Arrow keys move the highlight over `rows`, Enter picks the highlighted row, Escape closes. */
const handleKey = <T>(e: React.KeyboardEvent<HTMLInputElement>, rows: T[], pick: (row: T) => void) => {
if (!open || rows.length === 0) return;
if (e.key === 'ArrowDown') {
e.preventDefault();
setHighlight((h) => Math.min(h + 1, rows.length - 1));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setHighlight((h) => Math.max(h - 1, 0));
} else if (e.key === 'Enter' && highlight >= 0 && highlight < rows.length) {
e.preventDefault();
pick(rows[highlight]);
} else if (e.key === 'Escape') setOpen(false);
};
return { open, setOpen, highlight, setHighlight, wrapRef, handleKey };
}