mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
feat(dashboard): search every trip by title, date or a place on it (#2190)
This commit is contained in:
@@ -26,7 +26,7 @@ import {
|
||||
type TripAddMemberRequest, type TripTransferOwnershipRequest,
|
||||
type TripCreateGuestRequest, type TripRenameGuestRequest, type AssignmentReorderRequest,
|
||||
type PackingReorderRequest, type PackingCreateBagRequest, type TodoReorderRequest,
|
||||
type TripCreateRequest, type TripUpdateRequest, type TripCopyRequest, type ActiveTripResponse,
|
||||
type TripCreateRequest, type TripUpdateRequest, type TripCopyRequest, type ActiveTripResponse, type TripSearchResponse,
|
||||
type DayCreateRequest, type DayUpdateRequest, type DayReorderRequest,
|
||||
type PlaceCreateRequest, type PlaceUpdateRequest, type PlaceImageFromFileRequest,
|
||||
type ReservationCreateRequest, type ReservationUpdateRequest,
|
||||
@@ -427,6 +427,7 @@ export const tripsApi = {
|
||||
delete: (id: number | string) => apiClient.delete(`/trips/${id}`).then(r => r.data),
|
||||
uploadCover: (id: number | string, formData: FormData) => postMultipart(`/trips/${id}/cover`, formData),
|
||||
searchCoverImages: (query: string) => apiClient.get('/trips/cover-images/search', { params: { query } }).then(r => r.data),
|
||||
search: (q: string): Promise<TripSearchResponse> => apiClient.get('/trips/search', { params: { q } }).then(r => r.data),
|
||||
archive: (id: number | string) => apiClient.put(`/trips/${id}`, { is_archived: true }).then(r => r.data),
|
||||
unarchive: (id: number | string) => apiClient.put(`/trips/${id}`, { is_archived: false }).then(r => r.data),
|
||||
getMembers: (id: number | string) => apiClient.get(`/trips/${id}/members`).then(r => r.data),
|
||||
|
||||
@@ -1056,4 +1056,48 @@ describe('DashboardPage', () => {
|
||||
expect(card.querySelector('[aria-label="Archive"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('FE-PAGE-DASH-2190: trip search', () => {
|
||||
it('finds trips across filters by title and date, and by a place on them, then clears', async () => {
|
||||
const oldTrip = buildTrip({ id: 77, title: 'Old Rome Trip', start_date: '2024-05-01', end_date: '2024-05-07', is_archived: 1 });
|
||||
const philly = buildTrip({ id: 78, title: 'East Coast', start_date: '2026-09-01', end_date: '2026-09-07' });
|
||||
server.use(
|
||||
http.get('/api/trips', ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
if (url.searchParams.get('archived')) return HttpResponse.json({ trips: [oldTrip] });
|
||||
return HttpResponse.json({ trips: [buildTrip({ title: 'Paris Adventure', start_date: '2026-07-01', end_date: '2026-07-10' }), philly] });
|
||||
}),
|
||||
http.get('/api/trips/search', ({ request }) => {
|
||||
const q = new URL(request.url).searchParams.get('q');
|
||||
return HttpResponse.json({ matches: q === 'diner' ? [{ trip_id: 78, places: ["Dante's Diner"] }] : [] });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<DashboardPage />);
|
||||
await waitFor(() => expect(screen.getAllByText('Paris Adventure')[0]).toBeInTheDocument());
|
||||
|
||||
const box = screen.getByRole('searchbox', { name: 'Search all trips by title, date or place' });
|
||||
await user.type(box, 'rome');
|
||||
// The archived trip shows up without switching the filter.
|
||||
expect(await screen.findByText('Old Rome Trip')).toBeInTheDocument();
|
||||
|
||||
await user.clear(box);
|
||||
await user.type(box, 'may 2024');
|
||||
expect(await screen.findByText('Old Rome Trip')).toBeInTheDocument();
|
||||
|
||||
await user.clear(box);
|
||||
await user.type(box, 'diner');
|
||||
expect(await screen.findByText("Dante's Diner")).toBeInTheDocument();
|
||||
expect(screen.getByText('East Coast')).toBeInTheDocument();
|
||||
|
||||
await user.clear(box);
|
||||
await user.type(box, 'zzzz');
|
||||
expect(await screen.findByText('No trip matches “zzzz”')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Clear search' }));
|
||||
expect(box).toHaveValue('');
|
||||
expect(screen.queryByText('Old Rome Trip')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
import {
|
||||
Plus, Edit2, Trash2, Archive, ArchiveRestore, Copy, ArrowRight, MapPin,
|
||||
Plane, Hotel, Utensils, Clock, RefreshCw, ArrowRightLeft, Calendar,
|
||||
LayoutGrid, List, Ticket, X, CalendarPlus, ParkingSquare, LogIn, LogOut,
|
||||
LayoutGrid, List, Ticket, X, CalendarPlus, ParkingSquare, LogIn, LogOut, Search,
|
||||
} from 'lucide-react'
|
||||
import { IcsSubscribeModal } from '../components/Planner/IcsSubscribeModal'
|
||||
import CollectionsWidget from '../components/Dashboard/CollectionsWidget'
|
||||
@@ -120,7 +120,7 @@ function DashboardPageDesktop(): React.ReactElement {
|
||||
showForm, setShowForm, editingTrip, setEditingTrip,
|
||||
deleteTrip, setDeleteTrip, copyTrip, setCopyTrip, applyCoverUpdate,
|
||||
handleCreate, handleUpdate, confirmDelete, handleArchive, handleUnarchive, confirmCopy,
|
||||
allSubOpen, setAllSubOpen,
|
||||
allSubOpen, setAllSubOpen, search,
|
||||
} = useDashboard()
|
||||
|
||||
// Dashboard widget visibility (from the appearance config). Phones never reach this
|
||||
@@ -191,7 +191,24 @@ function DashboardPageDesktop(): React.ReactElement {
|
||||
<div className="sec-head">
|
||||
<h3 className="sec-title">{t('dashboard.title')}</h3>
|
||||
<div className="sec-tools">
|
||||
<div className="seg">
|
||||
{/* Trip search (#2190): every trip, by title, date or a place on it */}
|
||||
<label className={`dash-search${search.active ? ' on' : ''}`}>
|
||||
<Search size={15} strokeWidth={2.2} aria-hidden />
|
||||
<input
|
||||
type="search"
|
||||
value={search.query}
|
||||
onChange={e => search.setQuery(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Escape') search.setQuery('') }}
|
||||
placeholder={t('dashboard.search.placeholder')}
|
||||
aria-label={t('dashboard.search.label')}
|
||||
/>
|
||||
{search.active && (
|
||||
<button type="button" className="dash-search-clear" onClick={() => search.setQuery('')} aria-label={t('dashboard.search.clear')}>
|
||||
<X size={13} strokeWidth={2.4} />
|
||||
</button>
|
||||
)}
|
||||
</label>
|
||||
<div className={`seg${search.active ? ' is-muted' : ''}`}>
|
||||
<button type="button" className={tripFilter === 'planned' ? 'on' : ''} onClick={() => setTripFilter('planned')}>{t('dashboard.filter.planned')}</button>
|
||||
<button type="button" className={tripFilter === 'archive' ? 'on' : ''} onClick={() => setTripFilter('archive')}>{t('dashboard.archived')}</button>
|
||||
<button type="button" className={tripFilter === 'completed' ? 'on' : ''} onClick={() => setTripFilter('completed')}>{t('dashboard.mobile.completed')}</button>
|
||||
@@ -222,7 +239,13 @@ function DashboardPageDesktop(): React.ReactElement {
|
||||
{/* "No trips yet" only when there really are none — a user whose trips are
|
||||
all finished has a hero, and telling them to create their first trip is
|
||||
simply wrong (#1706). Same condition the mobile dashboard already uses. */}
|
||||
{gridTrips.length === 0 && !spotlight && tripFilter === 'planned' && !isLoading && !loadError && (
|
||||
{search.active && gridTrips.length === 0 && (
|
||||
<div className="trips-empty">
|
||||
<EmptyState scene="dashboard" title={t('dashboard.search.empty', { query: search.query.trim() })} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!search.active && gridTrips.length === 0 && !spotlight && tripFilter === 'planned' && !isLoading && !loadError && (
|
||||
<div className="trips-empty">
|
||||
<EmptyState scene="dashboard" title={t('dashboard.emptyTitle')} />
|
||||
</div>
|
||||
@@ -235,6 +258,7 @@ function DashboardPageDesktop(): React.ReactElement {
|
||||
trip={trip}
|
||||
locale={locale}
|
||||
badges={badgesFor(trip.id)}
|
||||
matchedPlaces={search.active ? search.placeHits.get(trip.id) : undefined}
|
||||
onOpen={() => navigate(`/trips/${trip.id}`)}
|
||||
onEdit={() => { setEditingTrip(trip); setShowForm(true) }}
|
||||
onCopy={() => setCopyTrip(trip)}
|
||||
@@ -249,7 +273,7 @@ function DashboardPageDesktop(): React.ReactElement {
|
||||
<TripCardSkeleton />
|
||||
</>
|
||||
)}
|
||||
{tripFilter === 'planned' && !isLoading && (
|
||||
{tripFilter === 'planned' && !search.active && !isLoading && (
|
||||
<button type="button" className="add-trip-card" onClick={() => { setEditingTrip(null); setShowForm(true) }}>
|
||||
<div>
|
||||
<div className="circ"><Plus size={20} /></div>
|
||||
@@ -575,8 +599,10 @@ function AtlasStats({ stats }: { stats: TravelStats | null }): React.ReactElemen
|
||||
}
|
||||
|
||||
// ── Trip card ────────────────────────────────────────────────────────────────
|
||||
function TripCard({ trip, locale, badges, onOpen, onEdit, onCopy, onArchive, onDelete }: {
|
||||
function TripCard({ trip, locale, badges, matchedPlaces, onOpen, onEdit, onCopy, onArchive, onDelete }: {
|
||||
trip: DashboardTrip; locale: string; badges?: TripCardBadge[]; onOpen: () => void
|
||||
/** The places that made this trip a search result (#2190). */
|
||||
matchedPlaces?: string[]
|
||||
onEdit: () => void; onCopy: () => void; onArchive: () => void; onDelete: () => void
|
||||
}): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
@@ -631,6 +657,12 @@ function TripCard({ trip, locale, badges, onOpen, onEdit, onCopy, onArchive, onD
|
||||
</>
|
||||
) : <span>{t('dashboard.hero.noDates')}</span>}
|
||||
</div>
|
||||
{matchedPlaces && matchedPlaces.length > 0 && (
|
||||
<div className="trip-match" title={matchedPlaces.join(', ')}>
|
||||
<MapPin size={12} strokeWidth={2.2} aria-hidden />
|
||||
<span>{matchedPlaces.join(' · ')}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="trip-meta" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
|
||||
<div><span className="n mono">{trip.day_count ?? 0}</span><span className="k">{t('dashboard.days')}</span></div>
|
||||
<div><span className="n mono">{trip.place_count ?? 0}</span><span className="k">{t('dashboard.places')}</span></div>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../../components/shared/Toast'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import { localIsoToday } from './dashboardModel'
|
||||
import { useTripSearch } from './useTripSearch'
|
||||
import type { TripCreateRequest } from '@trek/shared'
|
||||
import {
|
||||
type DashboardTrip,
|
||||
@@ -193,7 +194,10 @@ export function useDashboard() {
|
||||
setArchivedTrips(patch)
|
||||
}
|
||||
|
||||
const gridTrips = tripFilter === 'archive' ? archivedTrips
|
||||
// While a search runs it spans every trip, archived ones included (#2190).
|
||||
const search = useTripSearch(trips, archivedTrips, locale)
|
||||
const gridTrips = search.active ? search.results
|
||||
: tripFilter === 'archive' ? archivedTrips
|
||||
: tripFilter === 'completed' ? rest.filter(t => getTripStatus(t) === 'past')
|
||||
: rest.filter(t => getTripStatus(t) !== 'past')
|
||||
|
||||
@@ -208,6 +212,7 @@ export function useDashboard() {
|
||||
showForm, setShowForm, editingTrip, setEditingTrip,
|
||||
deleteTrip, setDeleteTrip, copyTrip, setCopyTrip, applyCoverUpdate,
|
||||
allSubOpen, setAllSubOpen,
|
||||
search,
|
||||
// actions
|
||||
handleCreate, handleUpdate, confirmDelete, handleArchive, handleUnarchive, confirmCopy,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { tripsApi } from '../../api/client'
|
||||
import { isEffectivelyOffline } from '../../sync/networkMode'
|
||||
import type { DashboardTrip } from './dashboardModel'
|
||||
|
||||
/** Lower-cased, accents folded, so "cafe" finds "Café". */
|
||||
const fold = (s: string) => s.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase()
|
||||
|
||||
/**
|
||||
* Whether a trip's own words match (#2190): its title, its description, and its
|
||||
* dates both as written (2024-05) and as read (May 2024, in the viewer's language).
|
||||
*/
|
||||
export function tripMatchesText(trip: DashboardTrip, query: string, locale?: string): boolean {
|
||||
const q = fold(query.trim())
|
||||
if (!q) return true
|
||||
const dates = [trip.start_date, trip.end_date].filter((d): d is string => !!d)
|
||||
const spoken = dates.map(d => {
|
||||
const parsed = new Date(`${d}T00:00:00`)
|
||||
return Number.isNaN(parsed.getTime()) ? '' : parsed.toLocaleDateString(locale, { month: 'long', year: 'numeric' })
|
||||
})
|
||||
const haystack = [trip.title, trip.description ?? '', ...dates, ...spoken].map(fold).join(' \n ')
|
||||
return q.split(/\s+/).every(word => haystack.includes(word))
|
||||
}
|
||||
|
||||
const DEBOUNCE_MS = 250
|
||||
|
||||
/**
|
||||
* The dashboard's trip search (#2190). Searches every trip, archived ones too,
|
||||
* by its own words on the device and by its places on the server; offline the
|
||||
* place half simply stays out. Returns the matching trips and, per trip, the
|
||||
* places that made it match.
|
||||
*/
|
||||
export function useTripSearch(trips: DashboardTrip[], archivedTrips: DashboardTrip[], locale?: string) {
|
||||
const [query, setQuery] = useState('')
|
||||
const [placeHits, setPlaceHits] = useState<Map<number, string[]>>(new Map())
|
||||
const active = query.trim().length > 0
|
||||
|
||||
useEffect(() => {
|
||||
const q = query.trim()
|
||||
if (q.length < 2 || isEffectivelyOffline()) { setPlaceHits(new Map()); return }
|
||||
let cancelled = false
|
||||
const timer = setTimeout(() => {
|
||||
tripsApi.search(q)
|
||||
.then(({ matches }) => { if (!cancelled) setPlaceHits(new Map(matches.map(m => [m.trip_id, m.places]))) })
|
||||
// The place half is a bonus on top of the local match; a failed request
|
||||
// leaves the title and date results standing.
|
||||
.catch(() => { if (!cancelled) setPlaceHits(new Map()) })
|
||||
}, DEBOUNCE_MS)
|
||||
return () => { cancelled = true; clearTimeout(timer) }
|
||||
}, [query])
|
||||
|
||||
const results = useMemo(() => {
|
||||
if (!active) return []
|
||||
const seen = new Set<number>()
|
||||
return [...trips, ...archivedTrips].filter(trip => {
|
||||
if (seen.has(trip.id)) return false
|
||||
seen.add(trip.id)
|
||||
return tripMatchesText(trip, query, locale) || placeHits.has(trip.id)
|
||||
})
|
||||
}, [active, trips, archivedTrips, query, locale, placeHits])
|
||||
|
||||
return { query, setQuery, active, results, placeHits }
|
||||
}
|
||||
@@ -429,6 +429,24 @@
|
||||
.dark .trek-dash .seg { background: var(--bg-2); }
|
||||
.trek-dash .seg button { padding: 7px 14px; font-size: 13px; border-radius: 8px; color: var(--ink-2); font-weight: 500; transition: background .12s, color .12s; }
|
||||
.trek-dash .seg button.on { background: var(--surface); color: var(--ink); box-shadow: var(--sh-xs); }
|
||||
/* While a search spans every trip the filter does not apply: quieted, still usable. */
|
||||
.trek-dash .seg.is-muted { opacity: .5; }
|
||||
.trek-dash .seg.is-muted button.on { box-shadow: none; }
|
||||
|
||||
/* trip search (#2190): the segment's height and ground, widening on focus */
|
||||
.trek-dash .dash-search { display: flex; align-items: center; gap: 7px; height: 38px; width: 190px; padding: 0 8px 0 11px; border-radius: 11px; background: oklch(0.94 0.008 70); color: var(--ink-3); transition: width .2s ease, background .12s, box-shadow .12s; }
|
||||
.dark .trek-dash .dash-search { background: var(--bg-2); }
|
||||
.trek-dash .dash-search:focus-within,
|
||||
.trek-dash .dash-search.on { width: 260px; background: var(--surface); box-shadow: var(--sh-xs), 0 0 0 1px var(--line); color: var(--ink-2); }
|
||||
.trek-dash .dash-search input { flex: 1; min-width: 0; border: 0; background: transparent; outline: none; font: inherit; font-size: 13px; color: var(--ink); }
|
||||
.trek-dash .dash-search input::placeholder { color: var(--ink-3); }
|
||||
.trek-dash .dash-search input::-webkit-search-cancel-button { display: none; }
|
||||
.trek-dash .dash-search-clear { display: grid; place-items: center; width: 22px; height: 22px; border-radius: 7px; color: var(--ink-3); flex: none; }
|
||||
.trek-dash .dash-search-clear:hover { background: var(--bg-2); color: var(--ink); }
|
||||
.trek-dash .trip-match { display: flex; align-items: center; justify-content: center; gap: 5px; margin: -6px 0 12px; font-size: 12px; color: var(--ink-2); min-width: 0; }
|
||||
.trek-dash .trip-match span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.trek-dash .trip-match svg { flex: none; color: var(--ink-3); }
|
||||
.trek-dash .trips.list-view .trip-match { margin: 0; justify-content: flex-start; max-width: 220px; }
|
||||
|
||||
/* ----------------- trips grid ----------------- */
|
||||
.trek-dash .trips { display: grid; grid-template-columns: repeat(3, 1fr); gap: 22px; margin-bottom: 56px; transition: all 0.3s ease; }
|
||||
|
||||
Reference in New Issue
Block a user