mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
feat(tours): complete planner follow-up scope
This commit completes the reviewed Tours follow-up scope after the Tours MVP was merged into dev. Included feature blocks: - RC-01: identify Tours in PLAN day rows and show compact Tour facts; - RC-06: search for a city or address in TOUR-PLANNER without hidden writes; - RC-07: reorder Tour waypoints in the left sidebar; - RC-08: drag Tour waypoints on Leaflet, MapLibre and Mapbox with stable viewport, history and routing behavior; - RS-01: persist Tour descriptions and HTTPS information links with local provider classification; - RS-02: persist breaks/additional time and calculated or manually adjusted planned Tour duration without changing scheduling semantics. The implementation preserves: - ordinary Place and Legacy Track behavior; - Tours-off fallback behavior; - existing GPX/import behavior; - Tour assignment and deletion behavior; - calculated routing duration as a separate value; - existing Tour provenance fields; - keyboard/list alternatives for waypoint editing. Not included: - PR1-09 trip-wide Tour summary; - Wanderer integration; - GPX import changes; - new Tour types; - Tour-to-Day drag-and-drop; - further roadmap or Post-Release features. Validation: - focused RC-01/RC-06/RC-07/RC-08/RS-01/RS-02 tests passed; - affected shared/server/client typechecks passed; - migration and generated DB type checks passed; - scoped ESLint passed; - staged diff checks passed; - owner manual tests passed for all six feature blocks.
This commit is contained in:
@@ -1534,6 +1534,58 @@ describe('DayPlanSidebar', () => {
|
||||
expect(onDeletePlace).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('RS-01: previews Tour descriptions in two lines only while Tours is enabled', () => {
|
||||
const description = 'A long description of the ridge route, the lake overlook, and the return path.'
|
||||
const place = buildPlace({ id: 45, name: 'Ridge walk', description, tour_place_id: 45 })
|
||||
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
|
||||
const assignment = buildAssignment({ id: 101, day_id: 10, order_index: 0, place })
|
||||
const times = { walkingMinutes: 60, breakMinutes: 35, plannedTotalMinutes: 95, manuallyOverridden: false }
|
||||
const props = makeDefaultProps({ days: [day], places: [place], tourPlaceIds: new Set([place.id]), plannedTourDurations: new Map([[place.id, times]]), assignments: { '10': [assignment] } })
|
||||
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: true }] })
|
||||
const view = render(<DayPlanSidebar {...props} />)
|
||||
const tourPreview = view.container.querySelector('[data-testid="trip-plan-tour-description"]') as HTMLElement
|
||||
expect(tourPreview).toHaveTextContent(description)
|
||||
expect(tourPreview.style.display).toBe('-webkit-box')
|
||||
expect(tourPreview.style.webkitLineClamp).toBe('2')
|
||||
expect(tourPreview.style.maxHeight).toBe('2.6em')
|
||||
expect(screen.getByTestId('trip-plan-tour-walking-time')).toHaveTextContent('Walk: 1 h')
|
||||
expect(screen.getByTestId('trip-plan-tour-breaks')).toHaveTextContent('Breaks: 35 min')
|
||||
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('Planned: 1 h 35 min')
|
||||
|
||||
view.rerender(<DayPlanSidebar {...{ ...props, plannedTourDurations: new Map([[place.id, { ...times, plannedTotalMinutes: 125, manuallyOverridden: true }]]) }} />)
|
||||
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('Manual override')
|
||||
|
||||
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: false }] })
|
||||
view.rerender(<DayPlanSidebar {...props} />)
|
||||
expect(view.container.querySelector('[data-testid="trip-plan-tour-description"]')).toBeNull()
|
||||
expect(view.container.querySelector('[data-testid="trip-plan-tour-planned-duration"]')).toBeNull()
|
||||
expect(screen.getByText(description).closest('.collab-note-md')).toHaveStyle({ whiteSpace: 'nowrap', maxHeight: '1.3em' })
|
||||
})
|
||||
|
||||
it('RC-01: uses facet type and compact facts only for Tours, preserving Tours-off Place presentation', () => {
|
||||
const place = buildPlace({ id: 45, name: 'Ridge walk', description: 'Above the lake', tour_place_id: 45 })
|
||||
const day = buildDay({ id: 10, title: 'Day 1' })
|
||||
const assignment = buildAssignment({ id: 101, day_id: 10, order_index: 0, place })
|
||||
const tour = {
|
||||
place_id: 45, name: place.name, tour_type: 'hike' as const, distance: 4, elevation_gain: 100, elevation_loss: 80,
|
||||
duration: 53, break_additional_minutes: 10, planned_duration_minutes: null, difficulty: null,
|
||||
wanderer_ref: null, match_confidence: 1, max_hiking_difficulty: 2, planned: true, caution: false,
|
||||
}
|
||||
const props = makeDefaultProps({ days: [day], places: [place], tourPlaceIds: new Set([45]), assignments: { '10': [assignment] },
|
||||
plannedTourDurations: new Map([[45, { tour, walkingMinutes: 53, breakMinutes: 10, plannedTotalMinutes: 63, manuallyOverridden: false }]]) })
|
||||
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: true }] })
|
||||
const view = render(<DayPlanSidebar {...props} />)
|
||||
expect(screen.getByTestId('plan-tour-icon').querySelector('.lucide-mountain')).toBeTruthy()
|
||||
expect(screen.getByTestId('plan-tour-distance')).toHaveTextContent('4')
|
||||
expect(screen.getByTestId('plan-tour-ascent')).toHaveTextContent('100')
|
||||
expect(screen.getByTestId('trip-plan-tour-walking-time')).toHaveAccessibleName('Walking time: 53 min')
|
||||
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('1 h 3 min')
|
||||
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: false }] })
|
||||
view.rerender(<DayPlanSidebar {...props} />)
|
||||
expect(screen.queryByTestId('plan-tour-icon')).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId('plan-tour-facts')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('TRIP-PLAN preserves legacy route-backed Place Delete when Tours is disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: false }] })
|
||||
|
||||
@@ -80,6 +80,9 @@ import { DayPlanSidebarFooter } from './DayPlanSidebarFooter'
|
||||
import type { DayAddControls } from '../../utils/dayAdd'
|
||||
import type { DayDeleteQuestion } from '../../utils/dayImpactLines'
|
||||
import type { Trip, Day, Place, Category, Assignment, Accommodation, Reservation, AssignmentsMap, RouteResult, RouteSegment, DayNote } from '../../types'
|
||||
import { formatPlannedTourDuration, type TourPlannedTimes } from '../Tours/tourPresentation'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import TourDayRowFacts, { TourDayRowIcon } from '../Tours/TourDayRowFacts'
|
||||
|
||||
export interface DayPlanSidebarProps {
|
||||
tripId: number
|
||||
@@ -87,6 +90,7 @@ export interface DayPlanSidebarProps {
|
||||
days: Day[]
|
||||
places: Place[]
|
||||
tourPlaceIds?: ReadonlySet<number>
|
||||
plannedTourDurations?: ReadonlyMap<number, TourPlannedTimes & { tour?: TourListItem }>
|
||||
categories: Category[]
|
||||
assignments: AssignmentsMap
|
||||
selectedDayId: number | null
|
||||
@@ -1823,6 +1827,9 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
const assignment = item.data
|
||||
const place = assignment.place
|
||||
if (!place) return null
|
||||
const isTourPlace = toursEnabled && (props.tourPlaceIds?.has(place.id) || place.tour_place_id === place.id)
|
||||
const tourTimes = isTourPlace ? props.plannedTourDurations?.get(place.id) : undefined
|
||||
const dayRowTour = tourTimes?.tour
|
||||
const cat = categories.find(c => c.id === place.category_id)
|
||||
const isPlaceSelected = selectedAssignmentId ? assignment.id === selectedAssignmentId : place.id === selectedPlaceId
|
||||
const isDraggingThis = draggingId === assignment.id
|
||||
@@ -1994,7 +2001,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
onMouseLeave={() => setLockHoverId(null)}
|
||||
className="relative flex flex-none rounded-full"
|
||||
>
|
||||
<PlaceAvatar place={place} category={cat} size={32} />
|
||||
{dayRowTour ? <TourDayRowIcon type={dayRowTour.tour_type} size={32} /> : <PlaceAvatar place={place} category={cat} size={32} />}
|
||||
{/* Hover/locked overlay */}
|
||||
{(lockHoverId === assignment.id || isLocked) && (
|
||||
<span className="absolute inset-0 grid place-items-center rounded-full transition-colors"
|
||||
@@ -2006,7 +2013,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
</Tooltip>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
{cat && (() => {
|
||||
{!dayRowTour && cat && (() => {
|
||||
const CatIcon = getCategoryIcon(cat.icon)
|
||||
return (
|
||||
<Tooltip label={cat.name}>
|
||||
@@ -2027,15 +2034,37 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
{(place.place_time || place.description || place.address || cat?.name) && (
|
||||
<div className="mt-0.5 flex min-w-0 items-center gap-1.5">
|
||||
{(dayRowTour || place.place_time || (tourTimes && (tourTimes.walkingMinutes != null || tourTimes.breakMinutes != null || tourTimes.plannedTotalMinutes != null)) || place.description || place.address || cat?.name) && (
|
||||
<div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-1.5">
|
||||
{place.place_time && (
|
||||
<TimePill quiet>
|
||||
{formatTime(place.place_time, locale, timeFormat)}{place.end_time ? ` – ${formatTime(place.end_time, locale, timeFormat)}` : ''}
|
||||
</TimePill>
|
||||
)}
|
||||
{dayRowTour && <TourDayRowFacts tour={dayRowTour} />}
|
||||
{!dayRowTour && tourTimes?.walkingMinutes != null && (
|
||||
<TimePill>
|
||||
<span data-testid="trip-plan-tour-walking-time" aria-label={`${t('tours.planner.inspector.duration')}: ${formatPlannedTourDuration(tourTimes.walkingMinutes)}`}>
|
||||
{t('tours.planner.walkingShort')}: {formatPlannedTourDuration(tourTimes.walkingMinutes)}
|
||||
</span>
|
||||
</TimePill>
|
||||
)}
|
||||
{!dayRowTour && tourTimes?.breakMinutes != null && (
|
||||
<TimePill>
|
||||
<span data-testid="trip-plan-tour-breaks" aria-label={`${t('tours.planner.breaksAdditional')}: ${formatPlannedTourDuration(tourTimes.breakMinutes)}`}>
|
||||
{t('tours.planner.breaksShort')}: {formatPlannedTourDuration(tourTimes.breakMinutes)}
|
||||
</span>
|
||||
</TimePill>
|
||||
)}
|
||||
{!dayRowTour && tourTimes?.plannedTotalMinutes != null && (
|
||||
<TimePill>
|
||||
<span data-testid="trip-plan-tour-planned-duration" aria-label={`${t('tours.planner.plannedTotalDuration')}: ${formatPlannedTourDuration(tourTimes.plannedTotalMinutes)}${tourTimes.manuallyOverridden ? `, ${t('tours.planner.plannedTotalManual')}` : ''}`}>
|
||||
{t('tours.planner.plannedShort')}: {formatPlannedTourDuration(tourTimes.plannedTotalMinutes)}{tourTimes.manuallyOverridden ? ` · ${t('tours.planner.plannedTotalManual')}` : ''}
|
||||
</span>
|
||||
</TimePill>
|
||||
)}
|
||||
{(place.description || place.address || cat?.name) && (
|
||||
<div className="collab-note-md min-w-0 flex-1 text-content-faint" style={{ ...fs(10.5), overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', lineHeight: 1.3, maxHeight: '1.3em' }}>
|
||||
<div data-testid={isTourPlace ? 'trip-plan-tour-description' : undefined} className="collab-note-md min-w-0 flex-1 text-content-faint" style={{ ...fs(10.5), overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: isTourPlace ? 'normal' : 'nowrap', lineHeight: 1.3, maxHeight: isTourPlace ? '2.6em' : '1.3em', ...(isTourPlace ? { display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' as const } : {}) }}>
|
||||
<Markdown remarkPlugins={[remarkGfm]}>{place.description || place.address || cat?.name || ''}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -364,4 +364,43 @@ describe('LocationSelect', () => {
|
||||
expect(screen.queryByText('Gare du Nord')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Gare de Lyon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('marks the keyboard-highlighted result as active and selects it with Enter', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(searchRoute([GARE, LYON]));
|
||||
const onPick = vi.fn();
|
||||
|
||||
render(<LocationSelect value={null} onChange={onPick} ariaLabel="Search map location" showSearchStatus />);
|
||||
const input = screen.getByRole('combobox', { name: 'Search map location' });
|
||||
await user.type(input, 'Gare');
|
||||
const firstOption = await screen.findByRole('option', { name: /Gare du Nord/ });
|
||||
await user.keyboard('{ArrowDown}');
|
||||
|
||||
expect(firstOption).toHaveAttribute('aria-selected', 'true');
|
||||
expect(input).toHaveAttribute('aria-activedescendant', firstOption.id);
|
||||
await user.keyboard('{Enter}');
|
||||
expect(onPick).toHaveBeenCalledWith(expect.objectContaining({ name: 'Gare du Nord' }));
|
||||
});
|
||||
|
||||
it('shows a localized no-result status after an empty successful search', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(searchRoute([]));
|
||||
|
||||
render(<LocationSelect value={null} onChange={vi.fn()} ariaLabel="Search map location" showSearchStatus />);
|
||||
await user.type(screen.getByRole('combobox', { name: 'Search map location' }), 'Nowhere');
|
||||
|
||||
expect(await screen.findByText(/Nothing found for/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows a non-mutating error status when the provider request fails', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/maps/search', () => HttpResponse.json({ error: 'unavailable' }, { status: 503 })));
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(<LocationSelect value={null} onChange={onChange} ariaLabel="Search map location" showSearchStatus />);
|
||||
await user.type(screen.getByRole('combobox', { name: 'Search map location' }), 'Kyoto');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Error');
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useEffect, useId, useRef, useState } from 'react'
|
||||
import { MapPin } from 'lucide-react'
|
||||
import { mapsApi } from '../../api/client'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -18,6 +18,9 @@ interface Props {
|
||||
value: LocationPoint | null
|
||||
onChange: (loc: LocationPoint | null) => void
|
||||
placeholder?: string
|
||||
ariaLabel?: string
|
||||
/** Announces the field as a combobox and says "nothing found" or an error in its list. */
|
||||
showSearchStatus?: boolean
|
||||
style?: React.CSSProperties
|
||||
/**
|
||||
* The trip's own places, offered while the field is empty or holds fewer than three
|
||||
@@ -27,7 +30,7 @@ interface Props {
|
||||
places?: LocationPoint[]
|
||||
}
|
||||
|
||||
export default function LocationSelect({ value, onChange, placeholder, style, places }: Props) {
|
||||
export default function LocationSelect({ value, onChange, placeholder, ariaLabel, showSearchStatus = false, style, places }: Props) {
|
||||
const { t, locale } = useTranslation()
|
||||
const placeLang = usePlaceLanguage()
|
||||
// Ohne Reisekontext ist der Hinweis leer, und die Suche laeuft wie bisher.
|
||||
@@ -36,6 +39,10 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
const { open, setOpen, highlight, setHighlight, wrapRef, handleKey } = useSuggestionDropdown()
|
||||
const [results, setResults] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [searchError, setSearchError] = useState(false)
|
||||
// The text the last answer was for, so a status never describes older text.
|
||||
const [searchedQuery, setSearchedQuery] = useState<string | null>(null)
|
||||
const listId = `${useId()}-location-results`
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -47,6 +54,9 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
const trimmed = query.trim()
|
||||
if (trimmed.length < 3 || (value && trimmed === value.name)) {
|
||||
setResults([])
|
||||
setLoading(false)
|
||||
setSearchError(false)
|
||||
setSearchedQuery(null)
|
||||
return
|
||||
}
|
||||
// Clearing the timer does nothing to a request already out: an answer for
|
||||
@@ -54,13 +64,20 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
let stale = false
|
||||
debounceRef.current = setTimeout(async () => {
|
||||
setLoading(true)
|
||||
setSearchError(false)
|
||||
setSearchedQuery(null)
|
||||
try {
|
||||
const data = await mapsApi.search(trimmed, placeLang, locationBias)
|
||||
if (stale) return
|
||||
setResults(data.places || [])
|
||||
setHighlight(-1)
|
||||
setSearchedQuery(trimmed)
|
||||
} catch {
|
||||
if (!stale) setResults([])
|
||||
if (!stale) {
|
||||
setResults([])
|
||||
setSearchError(true)
|
||||
setSearchedQuery(trimmed)
|
||||
}
|
||||
} finally {
|
||||
if (!stale) setLoading(false)
|
||||
}
|
||||
@@ -79,13 +96,21 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
onChange(loc)
|
||||
setQuery(loc.name)
|
||||
setOpen(false)
|
||||
setResults([])
|
||||
resetSearch()
|
||||
}
|
||||
|
||||
const clear = () => {
|
||||
onChange(null)
|
||||
setQuery('')
|
||||
resetSearch()
|
||||
}
|
||||
|
||||
function resetSearch() {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
setResults([])
|
||||
setLoading(false)
|
||||
setSearchError(false)
|
||||
setSearchedQuery(null)
|
||||
}
|
||||
|
||||
// The trip's places stand in for the search below three characters. Derived rather
|
||||
@@ -96,6 +121,30 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
const rows = showPicks
|
||||
? (places ?? []).filter(p => !typed || p.name.toLowerCase().includes(typed.toLowerCase()))
|
||||
: results
|
||||
const showNoResults =
|
||||
showSearchStatus && !showPicks && searchedQuery === typed && rows.length === 0 && !loading && !searchError
|
||||
const showError = showSearchStatus && searchError && searchedQuery === typed
|
||||
const listOpen = open && ((loading && !showPicks) || rows.length > 0 || showNoResults || showError)
|
||||
const accessibleLabel = ariaLabel ?? placeholder ?? t('reservations.searchLocation')
|
||||
const statusLine = showError ? (
|
||||
<div role="alert" className="text-content-faint" style={{ padding: 10, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>
|
||||
{t('common.error')}
|
||||
</div>
|
||||
) : showNoResults ? (
|
||||
<div role="status" className="text-content-faint" style={{ padding: 10, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>
|
||||
{t('help.center.searchEmpty', { query: typed })}
|
||||
</div>
|
||||
) : null
|
||||
|
||||
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
// Escape closes the list even while it only shows a status line.
|
||||
if (e.key === 'Escape' && open) {
|
||||
e.preventDefault()
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
handleKey(e, rows, pick)
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={wrapRef} style={{ position: 'relative', ...style }}>
|
||||
@@ -103,14 +152,27 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
icon={<MapPin size={14} className="text-content-faint" style={{ flexShrink: 0 }} />}
|
||||
query={query}
|
||||
placeholder={placeholder ?? t('reservations.searchLocation')}
|
||||
onType={(text) => { setQuery(text); setOpen(true); setHighlight(-1); if (value) onChange(null) }}
|
||||
onType={(text) => { setQuery(text); setOpen(true); setHighlight(-1); setSearchError(false); setSearchedQuery(null); if (value) onChange(null) }}
|
||||
onOpen={() => setOpen(true)}
|
||||
onKeyDown={(e) => handleKey(e, rows, pick)}
|
||||
onKeyDown={onKeyDown}
|
||||
onClear={value ? clear : undefined}
|
||||
inputAria={showSearchStatus ? {
|
||||
role: 'combobox',
|
||||
'aria-label': accessibleLabel,
|
||||
'aria-autocomplete': 'list',
|
||||
'aria-expanded': listOpen,
|
||||
'aria-controls': listOpen ? listId : undefined,
|
||||
'aria-activedescendant': listOpen && highlight >= 0 ? `${listId}-option-${highlight}` : undefined,
|
||||
} : undefined}
|
||||
/>
|
||||
|
||||
{open && (
|
||||
<SuggestionList loading={loading && !showPicks} rowCount={rows.length}>
|
||||
<SuggestionList
|
||||
loading={loading && !showPicks}
|
||||
rowCount={rows.length}
|
||||
status={statusLine}
|
||||
listbox={showSearchStatus ? { id: listId, label: accessibleLabel } : undefined}
|
||||
>
|
||||
{rows.map((r, i) => (
|
||||
<SuggestionRow
|
||||
key={showPicks ? `pick:${r.name}:${r.lat}:${r.lng}` : `${r.osm_id || r.google_place_id || i}`}
|
||||
@@ -118,6 +180,7 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
onPick={() => pick(r)}
|
||||
onHover={() => setHighlight(i)}
|
||||
align="flex-start"
|
||||
optionId={showSearchStatus ? `${listId}-option-${i}` : undefined}
|
||||
>
|
||||
<PlaceSuggestion name={r.name} address={r.address} />
|
||||
</SuggestionRow>
|
||||
|
||||
@@ -15,6 +15,8 @@ interface SuggestionInputBoxProps {
|
||||
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void;
|
||||
/** Shown as the clear button while a value is picked. */
|
||||
onClear?: () => void;
|
||||
/** Combobox wiring for a field that announces its list (role, aria-expanded, ...). */
|
||||
inputAria?: React.AriaAttributes & { role?: React.AriaRole };
|
||||
}
|
||||
|
||||
export function SuggestionInputBox({
|
||||
@@ -25,6 +27,7 @@ export function SuggestionInputBox({
|
||||
onOpen,
|
||||
onKeyDown,
|
||||
onClear,
|
||||
inputAria,
|
||||
}: SuggestionInputBoxProps) {
|
||||
return (
|
||||
<div
|
||||
@@ -41,6 +44,7 @@ export function SuggestionInputBox({
|
||||
{icon}
|
||||
<input
|
||||
type="text"
|
||||
{...inputAria}
|
||||
value={query}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => onType(e.target.value)}
|
||||
@@ -76,13 +80,17 @@ interface SuggestionListProps {
|
||||
/** Shows the loading line while there are no rows yet. */
|
||||
loading: boolean;
|
||||
rowCount: number;
|
||||
/** A line above the rows, such as "nothing found"; keeps the list open without rows. */
|
||||
status?: React.ReactNode;
|
||||
/** Wraps the rows in a listbox when the field is a combobox. */
|
||||
listbox?: { id: string; label: string };
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/** The floating list under the field. Rendered only while it is loading or has rows; the caller checks `open`. */
|
||||
export function SuggestionList({ loading, rowCount, children }: SuggestionListProps) {
|
||||
/** The floating list under the field. Rendered only while it is loading, has rows or a status; the caller checks `open`. */
|
||||
export function SuggestionList({ loading, rowCount, status, listbox, children }: SuggestionListProps) {
|
||||
const { t } = useTranslation();
|
||||
if (!loading && rowCount === 0) return null;
|
||||
if (!loading && rowCount === 0 && !status) return null;
|
||||
return (
|
||||
<div
|
||||
className="bg-surface-card"
|
||||
@@ -99,11 +107,22 @@ export function SuggestionList({ loading, rowCount, children }: SuggestionListPr
|
||||
}}
|
||||
>
|
||||
{loading && rowCount === 0 && (
|
||||
<div className="text-content-faint" style={{ padding: 10, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>
|
||||
<div
|
||||
role={listbox ? 'status' : undefined}
|
||||
className="text-content-faint"
|
||||
style={{ padding: 10, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}
|
||||
>
|
||||
{t('common.loading')}
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
{status}
|
||||
{listbox ? (
|
||||
<div id={listbox.id} role="listbox" aria-label={listbox.label}>
|
||||
{children}
|
||||
</div>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -114,13 +133,18 @@ interface SuggestionRowProps {
|
||||
onHover: () => void;
|
||||
/** How the row lines up its icon and text. */
|
||||
align: 'center' | 'flex-start';
|
||||
/** Set inside a listbox: the row becomes an option the input can point at. */
|
||||
optionId?: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function SuggestionRow({ active, onPick, onHover, align, children }: SuggestionRowProps) {
|
||||
export function SuggestionRow({ active, onPick, onHover, align, optionId, children }: SuggestionRowProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
id={optionId}
|
||||
role={optionId ? 'option' : undefined}
|
||||
aria-selected={optionId ? active : undefined}
|
||||
onClick={onPick}
|
||||
onMouseEnter={onHover}
|
||||
className={`text-content ${active ? 'bg-surface-hover' : 'bg-transparent'}`}
|
||||
|
||||
Reference in New Issue
Block a user