mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 06:37:33 +00:00
feat: quality of life sweep from the feature discussions
Small requests from the discussions, each built end to end: planner and map (cycling mode, date first headings, clear a day, stay times per day, off-route stops, map lock, compact unplanned markers, pending stays, cable car, transit quick picks), places (location filter, category from OSM, open in maps, geo: link, image from an attachment, enrichment on file import, places near a pin, place name language, Amap first in China), lists and costs (packed counter, inherited sharing, Markdown to-dos, payment notes, bookings CSV, my plan PDF), sharing (unplanned places, travel only, without photos), journey (photo zoom, drafts, photo order, trip suggestion, day jump), atlas (region counter, region bucket list, places per country), vacay half company holidays, studio copy and paste plus the book's own layouts, and RESTORE_FROM_BACKUP for a first start restore.
This commit is contained in:
@@ -3,6 +3,7 @@ import { MapPin } from 'lucide-react'
|
||||
import { mapsApi } from '../../api/client'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useLocationBias } from '../../hooks/useLocationBias'
|
||||
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage'
|
||||
|
||||
interface Props {
|
||||
value: string
|
||||
@@ -17,6 +18,7 @@ interface Props {
|
||||
// is never lost, and picking a suggestion just replaces the text (#1496).
|
||||
export default function AddressInput({ value, onChange, placeholder, className }: Props) {
|
||||
const { t, locale } = useTranslation()
|
||||
const placeLang = usePlaceLanguage()
|
||||
// Ohne Reisekontext ist der Hinweis leer, und die Suche laeuft wie bisher.
|
||||
const { point: locationBias } = useLocationBias()
|
||||
const [open, setOpen] = useState(false)
|
||||
@@ -50,7 +52,7 @@ export default function AddressInput({ value, onChange, placeholder, className }
|
||||
const myReq = ++reqIdRef.current
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await mapsApi.search(trimmed, locale, locationBias)
|
||||
const data = await mapsApi.search(trimmed, placeLang, locationBias)
|
||||
if (myReq !== reqIdRef.current) return
|
||||
setResults(data.places || [])
|
||||
setHighlight(-1)
|
||||
|
||||
@@ -2221,4 +2221,35 @@ describe('DayDetailPanel opening a booking', () => {
|
||||
expect(screen.queryByRole('button', { name: /Grand Hotel Booking/ })).toBeNull();
|
||||
expect(screen.getByRole('button', { name: '#XY99' })).toHaveAttribute('aria-pressed', 'false');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-DAYDETAIL-099: the arrival day shows only the check-in time and the middle night shows neither', async () => {
|
||||
const middleDay = buildDay({ id: 2, trip_id: 1, date: '2025-06-16', title: 'Middle Day' });
|
||||
server.use(
|
||||
http.get('/api/trips/1/accommodations', () =>
|
||||
HttpResponse.json({
|
||||
accommodations: [{
|
||||
id: 1, place_id: 5, place_name: 'Grand Hotel', place_address: 'Paris',
|
||||
start_day_id: 1, end_day_id: 3, check_in: '14:00', check_out: '11:00', confirmation: null,
|
||||
}],
|
||||
})
|
||||
),
|
||||
);
|
||||
const { unmount } = render(<DayDetailPanel {...defaultProps} />);
|
||||
await screen.findByText('14:00');
|
||||
expect(screen.queryByText('11:00')).toBeNull();
|
||||
unmount();
|
||||
render(<DayDetailPanel {...defaultProps} day={middleDay} days={[day, middleDay]} />);
|
||||
await screen.findByText('Grand Hotel');
|
||||
expect(screen.queryByText('14:00')).toBeNull();
|
||||
expect(screen.queryByText('11:00')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-DAYDETAIL-100: date-first headings lead with the date and name the day second', async () => {
|
||||
seedStore(useSettingsStore, {
|
||||
settings: { time_format: '24h', temperature_unit: 'celsius', day_date_first: true },
|
||||
});
|
||||
render(<DayDetailPanel {...defaultProps} />);
|
||||
const title = await screen.findByText(/June 15/);
|
||||
expect(title.className).toContain('font-bold');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,6 +11,8 @@ import CustomTimePicker from '../shared/CustomTimePicker'
|
||||
import { BlurredCode, BookingCodeInput } from '../shared/BookingCode'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { dayHeadingParts } from '../../utils/dayLabel'
|
||||
import { stayDayTimes } from './stayDayTimes'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { getLocaleForLanguage, useTranslation } from '../../i18n'
|
||||
import type { Day, Place, Category, Reservation, AssignmentsMap, Accommodation } from '../../types'
|
||||
@@ -82,6 +84,7 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
|
||||
const canEditDays = can('day_edit', tripObj)
|
||||
const isFahrenheit = useSettingsStore(s => s.settings.temperature_unit) === 'fahrenheit'
|
||||
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
|
||||
const dateFirst = useSettingsStore(s => s.settings.day_date_first === true)
|
||||
const collapsed = collapsedProp
|
||||
const toggleCollapse = () => onToggleCollapse?.()
|
||||
|
||||
@@ -147,7 +150,7 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
|
||||
getLocaleForLanguage(language),
|
||||
{ weekday: 'long', day: 'numeric', month: 'long', timeZone: 'UTC' }
|
||||
) : null
|
||||
const dayTitle = day.title || t('planner.dayN', { n: (days.indexOf(day) + 1) || '?' })
|
||||
const heading = dayHeadingParts(day.title || t('planner.dayN', { n: (days.indexOf(day) + 1) || '?' }), formattedDate, dateFirst)
|
||||
const showError = (err: unknown) => toast.error(apiErrorMessage(err) || t('common.unknownError'))
|
||||
|
||||
// Saving the picker: a new stay or the one being edited. Both say what went
|
||||
@@ -199,12 +202,12 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
|
||||
/>
|
||||
) : collapsed ? (
|
||||
<div className="truncate font-bold text-content" style={fs(13.5, 'body')}>
|
||||
{dayTitle}
|
||||
{formattedDate && <span className="ml-2 font-medium text-content-muted">{formattedDate}</span>}
|
||||
{heading.primary}
|
||||
{heading.secondary && <span className="ml-2 font-medium text-content-muted">{heading.secondary}</span>}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex min-w-0 items-center gap-1">
|
||||
<span className="truncate font-bold tracking-[-0.01em] text-content" style={fs(17, 'subtitle')}>{dayTitle}</span>
|
||||
<span className="truncate font-bold tracking-[-0.01em] text-content" style={fs(17, 'subtitle')}>{heading.primary}</span>
|
||||
{canEditDays && onUpdateDayTitle && (
|
||||
<Tooltip label={t('common.edit')}>
|
||||
<button type="button" onClick={startRename} aria-label={t('common.edit')}
|
||||
@@ -215,7 +218,7 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!collapsed && formattedDate && <div className="mt-0.5 truncate font-geist text-content-muted" style={fs(12.5)}>{formattedDate}</div>}
|
||||
{!collapsed && heading.secondary && <div className="mt-0.5 truncate font-geist text-content-muted" style={fs(12.5)}>{heading.secondary}</div>}
|
||||
</div>
|
||||
<HeadButton label={collapsed ? t('common.expand') : t('common.collapse')} expanded={!collapsed}
|
||||
onClick={() => toggleCollapse()}>
|
||||
@@ -457,8 +460,9 @@ function AccommodationCard({ acc, day, linked, canEdit, onEdit, onRemove, onOpen
|
||||
const leaving = isCheckOutDay && !isCheckInDay
|
||||
const tint = isCheckInDay ? tintOf('var(--success)') : isCheckOutDay ? tintOf('var(--danger)') : NEUTRAL_TINT
|
||||
const cells: { label: string; value: ReactNode }[] = []
|
||||
if (acc.check_in) cells.push({ label: t('day.checkIn'), value: `${fmtTime(acc.check_in)}${acc.check_in_end ? ` – ${fmtTime(acc.check_in_end)}` : ''}` })
|
||||
if (acc.check_out) cells.push({ label: t('day.checkOut'), value: fmtTime(acc.check_out) })
|
||||
const times = stayDayTimes(acc, day.id)
|
||||
if (times.checkIn && acc.check_in) cells.push({ label: t('day.checkIn'), value: `${fmtTime(acc.check_in)}${acc.check_in_end ? ` – ${fmtTime(acc.check_in_end)}` : ''}` })
|
||||
if (times.checkOut && acc.check_out) cells.push({ label: t('day.checkOut'), value: fmtTime(acc.check_out) })
|
||||
if (acc.confirmation) cells.push({ label: t('day.confirmation'), value: <BlurredCode className="font-geist">{acc.confirmation}</BlurredCode> })
|
||||
const confirmed = linked?.status === 'confirmed'
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import {
|
||||
FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship,
|
||||
Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle,
|
||||
ShoppingBag, Bookmark, Hotel, Utensils, Users, Sailboat, Bike, CarTaxiFront, Route, TramFront,
|
||||
ShoppingBag, Bookmark, Hotel, Utensils, Users, Sailboat, CableCar, Bike, CarTaxiFront, Route, TramFront,
|
||||
Wine, ParkingSquare, Fuel, Footprints, Mountain, Waves, Sun, Umbrella, Music, Landmark, Gift,
|
||||
} from 'lucide-react'
|
||||
|
||||
export const RES_ICONS = { flight: Plane, hotel: Hotel, restaurant: Utensils, train: Train, car: Car, cruise: Ship, bus: Bus, ferry: Sailboat, bicycle: Bike, taxi: CarTaxiFront, transit: TramFront, transport_other: Route, event: Ticket, tour: Users, parking: ParkingSquare, other: FileText }
|
||||
export const RES_ICONS = { flight: Plane, hotel: Hotel, restaurant: Utensils, train: Train, car: Car, cruise: Ship, bus: Bus, ferry: Sailboat, cable_car: CableCar, bicycle: Bike, taxi: CarTaxiFront, transit: TramFront, transport_other: Route, event: Ticket, tour: Users, parking: ParkingSquare, other: FileText }
|
||||
|
||||
export const NOTE_ICONS = [
|
||||
{ id: 'FileText', Icon: FileText },
|
||||
@@ -46,8 +46,8 @@ export function getNoteIcon(iconId) { return NOTE_ICON_MAP[iconId] || FileText }
|
||||
|
||||
export const TYPE_ICONS = {
|
||||
flight: '✈️', hotel: '🏨', restaurant: '🍽️', train: '🚆',
|
||||
car: '🚗', cruise: '🚢', bus: '🚌', ferry: '⛴️', bicycle: '🚲', taxi: '🚕',
|
||||
car: '🚗', cruise: '🚢', bus: '🚌', ferry: '⛴️', cable_car: '🚡', bicycle: '🚲', taxi: '🚕',
|
||||
transport_other: '🧭', event: '🎫', parking: '🅿️', other: '📋',
|
||||
}
|
||||
|
||||
export const TRANSPORT_DETAIL_COLORS = { flight: '#3b82f6', train: '#06b6d4', bus: '#059669', ferry: '#0d9488', bicycle: '#84cc16', taxi: '#ca8a04', car: '#6b7280', cruise: '#0ea5e9', transit: '#7c3aed', transport_other: '#6b7280' }
|
||||
export const TRANSPORT_DETAIL_COLORS = { flight: '#3b82f6', train: '#06b6d4', bus: '#059669', ferry: '#0d9488', cable_car: '#dc2626', bicycle: '#84cc16', taxi: '#ca8a04', car: '#6b7280', cruise: '#0ea5e9', transit: '#7c3aed', transport_other: '#6b7280' }
|
||||
|
||||
@@ -850,9 +850,9 @@ describe('DayPlanSidebar', () => {
|
||||
] },
|
||||
trip: buildTrip({ id: 1, currency: 'NOK' }),
|
||||
})} />)
|
||||
// $25 + 250 NOK / 10 = $50, marked as approximate; footer and day header agree.
|
||||
// $25 + 250 NOK / 10 = $50, marked as approximate. The day header carries no money.
|
||||
await waitFor(() => expect(screen.getByText('≈ $50.00')).toBeInTheDocument())
|
||||
expect(screen.getByText('≈ $50')).toBeInTheDocument()
|
||||
expect(screen.queryByText('≈ $50')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-037c: falls back to a per-currency breakdown when rates are unavailable (#1561)', async () => {
|
||||
@@ -876,7 +876,7 @@ describe('DayPlanSidebar', () => {
|
||||
expect(screen.queryByText(/5\s?230/)).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-037d: with Costs on, the day and the total follow the expenses, and drop one that is deleted (#2551)', async () => {
|
||||
it('FE-PLANNER-DAYPLAN-037d: with Costs on, the total follows the expenses and drops one that is deleted (#2551)', async () => {
|
||||
seedStore(useAddonStore, { addons: [{ id: 'budget', name: 'Costs', type: 'trip', icon: 'wallet', enabled: true }], loaded: true })
|
||||
// The price on the place is not an expense: it stays out of both figures.
|
||||
const place = buildPlace({ id: 1, name: 'Hanging Bridges', price: 999 })
|
||||
@@ -890,8 +890,8 @@ describe('DayPlanSidebar', () => {
|
||||
assignments: { '10': [buildAssignment({ id: 1, day_id: 10, order_index: 0, place })] },
|
||||
trip: buildTrip({ id: 1, currency: 'EUR' }),
|
||||
})} />)
|
||||
// The ticket is on the day of its place; the insurance belongs to no day but to the trip.
|
||||
expect(screen.getByText(/^60\s€$/)).toBeInTheDocument()
|
||||
// Both count toward the trip; the day header itself shows no amount.
|
||||
expect(screen.queryByText(/^60\s€$/)).toBeNull()
|
||||
expect(screen.getByText(/^100,00\s€$/)).toBeInTheDocument()
|
||||
expect(screen.queryByText(/999/)).toBeNull()
|
||||
|
||||
@@ -3925,7 +3925,7 @@ describe('DayPlanSidebar', () => {
|
||||
expect(toggle).toHaveAccessibleName('Keep position during route optimization')
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-167: the place context menu opens the website, maps and collection actions', async () => {
|
||||
it('FE-PLANNER-DAYPLAN-167: the place context menu opens the website but offers no navigation apps', async () => {
|
||||
const user = userEvent.setup()
|
||||
const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)
|
||||
const place = buildPlace({ id: 1, name: 'Louvre', website: 'https://louvre.fr', google_place_id: 'abc' })
|
||||
@@ -3936,10 +3936,9 @@ describe('DayPlanSidebar', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Open Website' }))
|
||||
expect(openSpy).toHaveBeenCalledWith('https://louvre.fr', '_blank', 'noopener,noreferrer')
|
||||
|
||||
// Navigation lives on the place's own Navigation button, not in this menu.
|
||||
fireEvent.contextMenu(dragRow(screen.getByText('Louvre')))
|
||||
await user.click(screen.getByRole('button', { name: 'Google Maps' }))
|
||||
expect(openSpy).toHaveBeenCalledTimes(2)
|
||||
expect(openSpy.mock.calls[1][0]).toContain('google.com/maps')
|
||||
expect(screen.queryByRole('button', { name: 'Google Maps' })).not.toBeInTheDocument()
|
||||
openSpy.mockRestore()
|
||||
})
|
||||
|
||||
@@ -5055,4 +5054,14 @@ describe('the day route-tools row', () => {
|
||||
|
||||
/* The click itself is already pinned by FE-PLANNER-DAYPLAN-038 above, which
|
||||
finds the button the same way. */
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-235: with "date first" the day heading leads with its date', () => {
|
||||
seedStore(useSettingsStore, { settings: { time_format: '24h', temperature_unit: 'celsius', day_date_first: true } } as any)
|
||||
const day = buildDay({ id: 10, date: '2025-06-01', title: null })
|
||||
render(<DayPlanSidebar {...makeDefaultProps({ days: [day], assignments: {} })} />)
|
||||
const secondary = screen.getByText('Day 1')
|
||||
expect(secondary.className).toContain('text-content-faint')
|
||||
expect(secondary.previousElementSibling?.className).toContain('font-bold')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ declare global { interface Window { __dragData: DragDataPayload | null } }
|
||||
import React, { useState, useEffect, useLayoutEffect, useRef, useMemo, useCallback } from 'react'
|
||||
import { avatarSrc } from '../../utils/avatarSrc'
|
||||
import { safeHttpUrl } from '../../utils/safeUrl'
|
||||
import { ChevronDown, ChevronRight, ChevronUp, Compass, Navigation, RotateCcw, ExternalLink, Pencil, GripVertical, Ticket, Plus, FileText, Trash2, Car, Lock, Hotel, Footprints, Route as RouteIcon, Bookmark, StickyNote, TramFront, Zap, MapPin, Wallet, Globe } from 'lucide-react'
|
||||
import { ChevronDown, ChevronRight, ChevronUp, Compass, RotateCcw, ExternalLink, Pencil, GripVertical, Ticket, Plus, FileText, Trash2, Car, Lock, Hotel, Eraser, Route as RouteIcon, RouteOff, Bookmark, StickyNote, TramFront, Zap, MapPin, Globe } from 'lucide-react'
|
||||
import { type PickedPlace } from './TransitSearchPanel'
|
||||
import { buildTransitLeg, buildTransitNameIndex } from './transitLeg'
|
||||
import { assignmentsApi, reservationsApi, daysApi } from '../../api/client'
|
||||
@@ -26,10 +26,10 @@ import { useTripStore } from '../../store/tripStore'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { usePluginStore } from '../../store/pluginStore'
|
||||
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'
|
||||
import { placeToSaveTarget } from '../Collections/saveTarget'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { routeModeIcon, useRouteModeOptions } from './routeModes'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
|
||||
import { BarButton, MoreButton, SoftPill, TimePill, tintOf } from './planParts'
|
||||
@@ -49,6 +49,8 @@ import {
|
||||
} from '../../utils/dayMerge'
|
||||
import { withinDriveRange } from '@trek/shared/roadtrip'
|
||||
import { formatDate, formatTime, formatMoneySum, splitReservationDateTime } from '../../utils/formatters'
|
||||
import { dayHeadingParts } from '../../utils/dayLabel'
|
||||
import { pendingStayIds } from '../../utils/pendingStays'
|
||||
import { planCosts } from './planCosts'
|
||||
import { useDayNotes } from '../../hooks/useDayNotes'
|
||||
import { useExchangeRates } from '../../hooks/useExchangeRates'
|
||||
@@ -69,7 +71,6 @@ 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 { getNavigationTargets, openNavigationTarget } from './placeNavigation'
|
||||
|
||||
interface DayPlanSidebarProps {
|
||||
tripId: number
|
||||
@@ -94,6 +95,8 @@ interface DayPlanSidebarProps {
|
||||
onDeleteDay?: (dayId: number) => void
|
||||
/** The open delete question, which the reorder dialog asks in place of its list. */
|
||||
deleteDayQuestion?: DayDeleteQuestion | null
|
||||
/** Asks to take every place off a day (#2470); the planner owns the question. */
|
||||
onClearDay?: (dayId: number) => void
|
||||
/** Renaming lives in the day-detail panel (#1065); the sidebar only forwards the prop. */
|
||||
onUpdateDayTitle: (dayId: number, title: string) => void
|
||||
/** The day route is computed by the planner page itself; kept for the existing call sites. */
|
||||
@@ -651,6 +654,8 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
// flight, not a drive — and surface it as a bogus connector distance (#1394).
|
||||
let curHasPlace = false
|
||||
for (const it of merged) {
|
||||
// A stop out of the route (#2532) is passed by, like a note.
|
||||
if (it.type === 'place' && it.data.route_excluded) continue
|
||||
if (it.type === 'place' && it.data.place?.lat && it.data.place?.lng) {
|
||||
// Mirror of the guard below: the open run may hold nothing but a far-away
|
||||
// arrival endpoint, which is no more drivable in this direction (#2133).
|
||||
@@ -709,7 +714,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
// is one you flew out of or landed at rather than drove between (#2133).
|
||||
const wayPts: { lat: number; lng: number; isPlace: boolean; time: string | null; carrierEdge?: CarrierEdge; leg_transport_mode?: string | null; incoming_leg_transport_mode?: string | null; id?: number }[] = []
|
||||
for (const it of merged) {
|
||||
if (it.type === 'place' && it.data.place?.lat && it.data.place?.lng) {
|
||||
if (it.type === 'place' && it.data.place?.lat && it.data.place?.lng && !it.data.route_excluded) {
|
||||
wayPts.push({ lat: it.data.place.lat, lng: it.data.place.lng, isPlace: true, time: it.data.place?.place_time ?? null, leg_transport_mode: it.data.leg_transport_mode ?? null, incoming_leg_transport_mode: it.data.incoming_leg_transport_mode ?? null, id: it.data.id })
|
||||
} else if (it.type === 'transport') {
|
||||
const { from, to } = getTransportRouteEndpoints(it.data, dayId)
|
||||
@@ -1164,14 +1169,12 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
window.__dragData = null
|
||||
}
|
||||
|
||||
// The day pills and Total Cost read the expenses in Costs when it is on (#2551).
|
||||
// Total Cost reads the expenses in Costs when it is on (#2551).
|
||||
const budgetItems = useTripStore(s => s.budgetItems)
|
||||
const costsEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
const { totalCostLabel, dayCostLabels } = useMemo(() => {
|
||||
const totalCostLabel = useMemo(() => {
|
||||
const costs = planCosts({ days, assignments, reservations, budgetItems, costsEnabled, tripCurrency: currency })
|
||||
const labels = new Map<number, string | null>()
|
||||
for (const [dayId, entries] of costs.byDay) labels.set(dayId, formatMoneySum(entries, costBase, locale, fxRates, { decimals: 0 }))
|
||||
return { totalCostLabel: formatMoneySum(costs.total, costBase, locale, fxRates), dayCostLabels: labels }
|
||||
return formatMoneySum(costs.total, costBase, locale, fxRates)
|
||||
}, [days, assignments, reservations, budgetItems, costsEnabled, currency, costBase, locale, fxRates])
|
||||
|
||||
return {
|
||||
@@ -1316,7 +1319,6 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
handleOptimize,
|
||||
handleDropOnDay,
|
||||
totalCostLabel,
|
||||
dayCostLabels,
|
||||
expandedRouteDayIds,
|
||||
setExpandedRouteDayIds,
|
||||
}
|
||||
@@ -1334,6 +1336,7 @@ const NARROW_PLAN_PX = 320
|
||||
|
||||
const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
const S = useDayPlanSidebar(props)
|
||||
const onClearDay = props.onClearDay
|
||||
// The plan sidebar is resizable. Below this the route button's own word is the
|
||||
// first thing that stops fitting beside the two export buttons — the icon says
|
||||
// the same thing, and the accessible name still spells it out.
|
||||
@@ -1359,27 +1362,14 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
// Needed by the route-tools visibility gate in the render below (#1330); the hook
|
||||
// keeps its own copy, so read it reactively here in the component scope too.
|
||||
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
|
||||
const dateFirst = useSettingsStore(s => s.settings.day_date_first === true)
|
||||
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
|
||||
// Route-profile picker entries: the two built-ins plus every profile an active
|
||||
// routeProvider plugin declared (keyed 'plugin:<id>/<profile>', labeled by the
|
||||
// plugin's manifest). The feed only lists granted providers.
|
||||
const activePlugins = usePluginStore(s => s.plugins)
|
||||
// Plugin time contributions in the day plan (dayScheduleProvider hook).
|
||||
const daySchedule = usePluginDaySchedule(S.tripId)
|
||||
// Per-day colours from the dayTintProvider hook — e.g. which leg of the trip a
|
||||
// day belongs to. Empty unless a granted plugin provides them.
|
||||
const dayTints = usePluginDayTints(S.tripId)
|
||||
const tr = S.t
|
||||
const routeProfileOptions = useMemo(() => {
|
||||
const opts: Array<{ key: string; label: string }> = [
|
||||
{ key: 'driving', label: tr('mobileTrip.profileDriving') },
|
||||
{ key: 'walking', label: tr('mobileTrip.profileWalking') },
|
||||
]
|
||||
for (const p of activePlugins) {
|
||||
for (const prof of p.routeProfiles ?? []) opts.push({ key: `plugin:${p.id}/${prof.id}`, label: prof.label })
|
||||
}
|
||||
return opts
|
||||
}, [activePlugins, tr])
|
||||
const routeProfileOptions = useRouteModeOptions()
|
||||
const {
|
||||
tripId,
|
||||
trip,
|
||||
@@ -1522,17 +1512,16 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
handleOptimize,
|
||||
handleDropOnDay,
|
||||
totalCostLabel,
|
||||
dayCostLabels,
|
||||
expandedRouteDayIds,
|
||||
setExpandedRouteDayIds,
|
||||
} = S
|
||||
// Stays still waiting for their booking to be confirmed, for the day pills (#2281).
|
||||
const pendingStays = useMemo(() => pendingStayIds(reservations), [reservations])
|
||||
// Rows that can be dragged lead with a grip; the rest keep its room so every tile lines up.
|
||||
const gripsShown = canEditDays && !dragDisabled
|
||||
|
||||
// ── Per-segment / per-day travel mode (#1281) ──────────────────────────────
|
||||
// Icon per mode, matching the route picker (driving→Car, walking→Footprints,
|
||||
// any plugin profile→Zap).
|
||||
const modeIcon = (key: string) => (key === 'walking' ? Footprints : key.startsWith('plugin:') ? Zap : Car)
|
||||
const modeIcon = routeModeIcon
|
||||
|
||||
// Set the mode of the leg LEAVING this stop. Optimistic (the connector + map
|
||||
// recompute from the store), then persisted; null clears the override so the leg
|
||||
@@ -1679,8 +1668,8 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
}
|
||||
const isExpanded = expandedDays.has(day.id)
|
||||
const da = getDayAssignments(day.id)
|
||||
const cost = dayCostLabels.get(day.id) ?? null
|
||||
const formattedDate = formatDate(day.date, locale)
|
||||
const heading = dayHeadingParts(day.title || t('dayplan.dayN', { n: index + 1 }), formattedDate, dateFirst)
|
||||
const loc = da.find(a => a.place?.lat && a.place?.lng)
|
||||
// Route tools normally need 2+ stops, but a single located place is still
|
||||
// routable when accommodation optimization can bookend it with a hotel
|
||||
@@ -1798,6 +1787,14 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
onPlanTransit && { label: t('transit.title'), icon: TramFront, onClick: () => onPlanTransit(day.id) },
|
||||
{ label: t('dayplan.addNote'), icon: FileText, onClick: () => openAddNote(day.id, undefined) },
|
||||
].filter(Boolean)
|
||||
// Right-click on the head: what can be added, and emptying the day (#2470).
|
||||
const dayMenuItems = [
|
||||
...addItems,
|
||||
...(onClearDay && da.length > 0 ? [
|
||||
{ divider: true },
|
||||
{ label: t('dayplan.clearDay'), icon: Eraser, danger: true, onClick: () => onClearDay(day.id) },
|
||||
] : []),
|
||||
]
|
||||
|
||||
return (
|
||||
// One card per day, in the language of the booking cards: a head band
|
||||
@@ -1830,6 +1827,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
onDragOver={e => { e.preventDefault(); if (dragOverDayId !== day.id) setDragOverDayId(day.id) }}
|
||||
onDragLeave={e => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDragOverDayId(null) }}
|
||||
onDrop={e => handleDropOnDay(e, day.id)}
|
||||
onContextMenu={canEditDays ? e => ctxMenu.open(e, dayMenuItems) : undefined}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'flex-start', gap: 10,
|
||||
padding: '10px 8px 10px 10px',
|
||||
@@ -1878,15 +1876,15 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
<div className="min-w-0 flex-1 pt-px">
|
||||
<div className="flex min-w-0 items-baseline gap-2">
|
||||
<span className="min-w-0 truncate font-bold text-content" style={fs(13.5, 'body')}>
|
||||
{day.title || t('dayplan.dayN', { n: index + 1 })}
|
||||
{heading.primary}
|
||||
</span>
|
||||
{formattedDate && (
|
||||
{heading.secondary && (
|
||||
<span className="flex-none whitespace-nowrap text-content-faint" style={fs(11)}>
|
||||
{formattedDate}
|
||||
{heading.secondary}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{(dayAccs.length > 0 || activeRentals.length > 0 || cost || dayTint?.label) && (
|
||||
{(dayAccs.length > 0 || activeRentals.length > 0 || dayTint?.label) && (
|
||||
<div className="mt-1.5 flex min-w-0 flex-wrap items-center gap-1">
|
||||
{dayAccs.map(acc => {
|
||||
const isCheckIn = acc.start_day_id === day.id
|
||||
@@ -1896,11 +1894,15 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
// check-out red, a stay in between quiet.
|
||||
const state = isCheckOut && !isCheckIn ? t('day.checkOut') : isCheckIn ? t('day.checkIn') : null
|
||||
const iconTone = isCheckOut && !isCheckIn ? 'text-danger' : isCheckIn ? 'text-success' : 'text-content-faint'
|
||||
// Not confirmed yet: a dashed ring says so at a glance, the tooltip in words (#2281).
|
||||
const pending = pendingStays.has(acc.id)
|
||||
const named = state ? `${state}: ${accName}` : accName
|
||||
const tip = pending ? `${named} (${t('reservations.pending')})` : named
|
||||
return (
|
||||
<Tooltip key={acc.id} label={state ? `${state}: ${accName}` : accName}>
|
||||
<button type="button" data-dp="day-pill"
|
||||
<Tooltip key={acc.id} label={tip}>
|
||||
<button type="button" data-dp="day-pill" data-pending={pending || undefined}
|
||||
onClick={e => { e.stopPropagation(); if ((acc as any).place_id) onPlaceClick((acc as any).place_id) }}
|
||||
className="inline-flex min-w-0 max-w-full items-center gap-1 rounded-full bg-surface-card px-2 py-[2px] font-geist font-normal text-content-secondary shadow-sm hover:text-content"
|
||||
className={`inline-flex min-w-0 max-w-full items-center gap-1 rounded-full px-2 py-[2px] font-geist font-normal text-content-secondary hover:text-content ${pending ? 'border border-dashed border-warning bg-warning-soft' : 'bg-surface-card shadow-sm'}`}
|
||||
style={{ ...fs(10.5), cursor: (acc as any).place_id ? 'pointer' : 'default' }}>
|
||||
<Hotel size={11} strokeWidth={2} className={`flex-none ${iconTone}`} />
|
||||
<span className="truncate">{accName}</span>
|
||||
@@ -1917,7 +1919,6 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
<span className="truncate">{r.title}</span>
|
||||
</button>
|
||||
))}
|
||||
{cost && <SoftPill tone="success" icon={<Wallet size={10} strokeWidth={2.2} />}>{cost}</SoftPill>}
|
||||
{/* A plugin's name for this day (which leg of the trip it belongs to). */}
|
||||
{dayTint?.label && <SoftPill>{dayTint.label}</SoftPill>}
|
||||
</div>
|
||||
@@ -2110,13 +2111,15 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
const isLocked = lockedIds.has(assignment.id)
|
||||
// The actions a right-click offers; the row's "…" offers the same, so a
|
||||
// mouse that never right-clicks and the keyboard reach them too.
|
||||
// Flat entries, one per navigation app: a submenu would need a
|
||||
// component that does not exist here.
|
||||
const placeMenu = () => [
|
||||
canEditPlaces && onEditPlace && { label: t('common.edit'), icon: Pencil, onClick: () => onEditPlace(place, assignment.id) },
|
||||
canEditDays && onRemoveAssignment && { label: t('planner.removeFromDay'), icon: Trash2, onClick: () => onRemoveAssignment(day.id, assignment.id) },
|
||||
canEditDays && place.lat != null && place.lng != null && {
|
||||
label: assignment.route_excluded ? t('dayplan.includeInRoute') : t('dayplan.excludeFromRoute'),
|
||||
icon: assignment.route_excluded ? RouteIcon : RouteOff,
|
||||
onClick: () => { tripActions.setAssignmentRouteExcluded(tripId, day.id, assignment.id, !assignment.route_excluded).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) },
|
||||
},
|
||||
safeHttpUrl(place.website) && { label: t('inspector.website'), icon: ExternalLink, onClick: () => window.open(safeHttpUrl(place.website)!, '_blank', 'noopener,noreferrer') },
|
||||
...getNavigationTargets(place).map(target => ({ label: target.label, icon: Navigation, onClick: () => openNavigationTarget(target) })),
|
||||
collectionsEnabled && { label: t('inspector.saveToCollection'), icon: Bookmark, onClick: () => useSaveToCollectionStore.getState().open(placeToSaveTarget(place)) },
|
||||
{ divider: true },
|
||||
canEditPlaces && onDeletePlace && { label: t('common.delete'), icon: Trash2, danger: true, onClick: () => onDeletePlace(place.id) },
|
||||
@@ -2245,6 +2248,15 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
<span className="min-w-0 truncate font-semibold text-content" style={{ ...fs(13, 'body'), lineHeight: 1.25 }}>
|
||||
{place.name}
|
||||
</span>
|
||||
{assignment.route_excluded && (
|
||||
// Kept on the day but passed by (#2532): said once, beside the name.
|
||||
<Tooltip label={t('dayplan.offRouteHint')}>
|
||||
<span className="inline-flex flex-none items-center gap-1 rounded-full bg-surface-secondary px-1.5 py-[1px] font-geist font-semibold text-content-muted" style={fs(9.5)}>
|
||||
<RouteOff size={10} strokeWidth={2.2} />
|
||||
{t('dayplan.offRoute')}
|
||||
</span>
|
||||
</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">
|
||||
@@ -2848,7 +2860,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
{/* The day's travel mode as one segmented control. */}
|
||||
<div className={`inline-flex h-8 flex-none items-center gap-0.5 rounded-[10px] p-[3px] ${ROUTE_TOOL}`}>
|
||||
{routeProfileOptions.map(p => {
|
||||
const ModeIcon = p.key === 'driving' ? Car : p.key === 'walking' ? Footprints : Zap
|
||||
const ModeIcon = routeModeIcon(p.key)
|
||||
const active = (day.default_transport_mode ?? routeProfile) === p.key
|
||||
return (
|
||||
<Tooltip key={p.key} label={p.label} placement="top">
|
||||
|
||||
@@ -1,22 +1,14 @@
|
||||
import { Car, Footprints, Hotel, Zap } from 'lucide-react'
|
||||
import { Hotel } from 'lucide-react'
|
||||
import type { RouteSegment } from '../../types'
|
||||
import { fs } from '../shared/DialogShell'
|
||||
|
||||
// Walking gets the foot icon; a plugin route profile ('plugin:…') gets the bolt —
|
||||
// its legs carry the profile-true durationText anyway, the icon just signals that
|
||||
// the time came from a plugin router (e.g. EV routing with charge time folded in).
|
||||
export function profileIcon(profile: string) {
|
||||
if (profile === 'walking') return Footprints
|
||||
if (profile.startsWith('plugin:')) return Zap
|
||||
return Car
|
||||
}
|
||||
import { routeModeIcon } from './routeModes'
|
||||
|
||||
/** The leg's figures as one quiet pill: mode, time, distance and a router note, side by side. */
|
||||
function LegPill({ seg, profile }: { seg: RouteSegment; profile: string }) {
|
||||
// The leg's own mode (#1281) wins over the day-wide fallback for icon + text.
|
||||
const effProfile = seg.mode ?? profile
|
||||
const driving = effProfile !== 'walking'
|
||||
const Icon = profileIcon(effProfile)
|
||||
const Icon = routeModeIcon(effProfile)
|
||||
return (
|
||||
<span className="inline-flex flex-none items-center gap-1.5 whitespace-nowrap rounded-full bg-surface-secondary px-2 py-[2px] font-geist font-semibold tabular-nums text-content-muted" style={fs(10)}>
|
||||
<Icon size={11} strokeWidth={2} className="flex-none" />
|
||||
|
||||
@@ -5,6 +5,8 @@ import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { placesApi } from '../../api/client'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import ToggleSwitch from '../Settings/ToggleSwitch'
|
||||
import {
|
||||
DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs,
|
||||
} from '../shared/DialogShell'
|
||||
@@ -57,6 +59,10 @@ export default function FileImportModal({ isOpen, onClose, tripId, pushUndo, ini
|
||||
const [summary, setSummary] = useState<PlacesImportSummary | null>(null)
|
||||
const [gpxOpts, setGpxOpts] = useState({ waypoints: true, routes: true, tracks: true })
|
||||
const [kmlOpts, setKmlOpts] = useState({ points: true, paths: true })
|
||||
// The Google pass a list import offers, for the points of a file too (#2536).
|
||||
const canEnrichImport = useAuthStore(s => s.hasMapsKey)
|
||||
const [enrich, setEnrich] = useState(false)
|
||||
const enrichHintId = useId()
|
||||
|
||||
const validateFile = (f: File): string | null => {
|
||||
const ext = f.name.toLowerCase().split('.').pop()
|
||||
@@ -168,13 +174,13 @@ export default function FileImportModal({ isOpen, onClose, tripId, pushUndo, ini
|
||||
try {
|
||||
if (ext === 'gpx') {
|
||||
importedGpx = true
|
||||
const result = await placesApi.importGpx(tripId, f, gpxOpts)
|
||||
const result = await placesApi.importGpx(tripId, f, { ...gpxOpts, enrich: enrich && canEnrichImport })
|
||||
totalCreated += result.count ?? 0
|
||||
totalSkipped += result.skipped ?? 0
|
||||
if (result.places?.length > 0) createdIds.push(...result.places.map((p: { id: number }) => p.id))
|
||||
} else {
|
||||
importedKml = true
|
||||
const result = await placesApi.importMapFile(tripId, f, kmlOpts)
|
||||
const result = await placesApi.importMapFile(tripId, f, { ...kmlOpts, enrich: enrich && canEnrichImport })
|
||||
totalCreated += result.count ?? 0
|
||||
if (result.places?.length > 0) createdIds.push(...result.places.map((p: { id: number }) => p.id))
|
||||
const s = result.summary as PlacesImportSummary | undefined
|
||||
@@ -327,6 +333,16 @@ export default function FileImportModal({ isOpen, onClose, tripId, pushUndo, ini
|
||||
</DialogSection>
|
||||
)}
|
||||
|
||||
{canEnrichImport && ((isGpx && gpxOpts.waypoints) || (isKml && kmlOpts.points)) && (
|
||||
<div className="flex items-start gap-3 rounded-[14px] border border-edge-faint bg-surface-secondary p-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="font-semibold text-content" style={fs(12.5, 'body')}>{t('places.enrichOnImport')}</div>
|
||||
<div id={enrichHintId} className="mt-0.5 text-content-faint" style={fs(12, 'body')}>{t('places.enrichOnImportFileHint')}</div>
|
||||
</div>
|
||||
<ToggleSwitch on={enrich} onToggle={() => setEnrich(v => !v)} label={t('places.enrichOnImport')} describedBy={enrichHintId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{summary && (
|
||||
<div className="flex flex-col gap-2 rounded-[14px] border border-edge-faint bg-surface-secondary px-3 py-2.5">
|
||||
<div className="text-content-muted" style={fs(12, 'body')}>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { MapPin, X } from 'lucide-react'
|
||||
import { mapsApi } from '../../api/client'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useLocationBias } from '../../hooks/useLocationBias'
|
||||
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage'
|
||||
|
||||
export interface LocationPoint {
|
||||
name: string
|
||||
@@ -26,6 +27,7 @@ interface Props {
|
||||
|
||||
export default function LocationSelect({ value, onChange, placeholder, style, places }: Props) {
|
||||
const { t, locale } = useTranslation()
|
||||
const placeLang = usePlaceLanguage()
|
||||
// Ohne Reisekontext ist der Hinweis leer, und die Suche laeuft wie bisher.
|
||||
const { point: locationBias } = useLocationBias()
|
||||
const [query, setQuery] = useState(value?.name || '')
|
||||
@@ -58,7 +60,7 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
debounceRef.current = setTimeout(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await mapsApi.search(trimmed, locale, locationBias)
|
||||
const data = await mapsApi.search(trimmed, placeLang, locationBias)
|
||||
setResults(data.places || [])
|
||||
setHighlight(-1)
|
||||
} catch {
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
DEFAULT_FORM, endsBeforeStart, findDuplicatePlace, isAmapUrl, isGoogleMapsUrl, isMapUrl, parseCoordinatePair,
|
||||
timeCollisions,
|
||||
} from './PlaceFormModal.helpers'
|
||||
import { formPin } from './PlaceFormModal.helpers'
|
||||
|
||||
describe('isGoogleMapsUrl', () => {
|
||||
it('accepts the short share hosts', () => {
|
||||
@@ -146,3 +147,14 @@ describe('timeCollisions', () => {
|
||||
expect(timeCollisions(99, day, '12:00', '13:00')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('formPin', () => {
|
||||
it('FE-PLACEFORM-PIN-001: reads a pin only from two real coordinates', () => {
|
||||
expect(formPin({ lat: '52.5163', lng: '13.3777' })).toEqual({ lat: 52.5163, lng: 13.3777 })
|
||||
expect(formPin({ lat: '0', lng: '0' })).toEqual({ lat: 0, lng: 0 })
|
||||
expect(formPin({ lat: '', lng: '13.4' })).toBeNull()
|
||||
expect(formPin({ lat: '52.5', lng: ' ' })).toBeNull()
|
||||
expect(formPin({ lat: 'abc', lng: '13.4' })).toBeNull()
|
||||
expect(formPin({ lat: '91', lng: '13.4' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -233,3 +233,15 @@ export function timeCollisions(
|
||||
return s1 < (e2 || '23:59') && s2 < (e1 || '23:59') && s1 !== e2 && s2 !== e1
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The pin the form holds, when both fields are real coordinates: what "places
|
||||
* near here" asks about (#976). Empty or half-typed fields are no pin.
|
||||
*/
|
||||
export function formPin(form: Pick<PlaceFormData, 'lat' | 'lng'>): { lat: number; lng: number } | null {
|
||||
if (!form.lat.trim() || !form.lng.trim()) return null
|
||||
const lat = Number(form.lat)
|
||||
const lng = Number(form.lng)
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lng) || Math.abs(lat) > 90 || Math.abs(lng) > 180) return null
|
||||
return { lat, lng }
|
||||
}
|
||||
|
||||
@@ -310,6 +310,38 @@ describe('PlaceFormModal', () => {
|
||||
expect(await screen.findByText('Eiffel Tower')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-018c: a pin lists the places around it, nearest first with their distance, and one pick fills the form', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true, hasMapsKey: true });
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.post('/api/maps/nearby', async ({ request }) => {
|
||||
bodies.push((await request.json()) as Record<string, unknown>);
|
||||
return HttpResponse.json({
|
||||
places: [{ name: 'Café am Tor', address: 'Pariser Platz 1', lat: 52.5163, lng: 13.378, distance_m: 40 }],
|
||||
source: 'trek-places',
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
render(<PlaceFormModal {...defaultProps} prefillCoords={{ lat: 52.5163, lng: 13.3777 }} />);
|
||||
await user.click(screen.getByRole('button', { name: 'Places near this pin' }));
|
||||
|
||||
expect(bodies).toEqual([{ lat: 52.5163, lng: 13.3777 }]);
|
||||
expect(await screen.findByText('Café am Tor')).toBeInTheDocument();
|
||||
expect(screen.getByText('40 m')).toBeInTheDocument();
|
||||
// No typed query, so nothing to send to Google instead.
|
||||
expect(screen.queryByText('Not the right place? Search Google instead')).not.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByText('Café am Tor'));
|
||||
expect(screen.getByDisplayValue('Pariser Platz 1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-018d: without a pin there is nothing to look around', () => {
|
||||
render(<PlaceFormModal {...defaultProps} />);
|
||||
expect(screen.queryByRole('button', { name: 'Places near this pin' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-018b: a list the index answered offers Google instead, and the link sends the same query there alone', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true, hasMapsKey: true });
|
||||
|
||||
@@ -12,13 +12,16 @@ import CollectionPicker from '../Collections/CollectionPicker'
|
||||
import PlaceDetailsColumn, { type PlaceDetailsSelection } from './PlaceDetailsColumn'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { Search, Paperclip, X, AlertTriangle, Loader2, Plus, RotateCcw, MapPin } from 'lucide-react'
|
||||
import { Search, Paperclip, X, AlertTriangle, Loader2, Plus, RotateCcw, MapPin, Navigation, LocateFixed } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import CustomTimePicker from '../shared/CustomTimePicker'
|
||||
import {
|
||||
DEFAULT_FORM, endsBeforeStart, findDuplicatePlace, isMapUrl, mergeResult, parseCoordinatePair, timeCollisions,
|
||||
DEFAULT_FORM, endsBeforeStart, findDuplicatePlace, formPin, isMapUrl, mergeResult, parseCoordinatePair, timeCollisions,
|
||||
type PlaceFormData, type ResultField,
|
||||
} from './PlaceFormModal.helpers'
|
||||
import { guessCategoryId } from './placeCategoryGuess'
|
||||
import { getNavigationTargets, openNavigationTarget } from './placeNavigation'
|
||||
import { NavigationMenu } from '../shared/NavigationMenu'
|
||||
import { getApiErrorMessage } from '../../utils/apiError'
|
||||
import { corePickRank, offersGoogleRetry, selectGoogleHoldsSlot } from '../../utils/placeSource'
|
||||
import { safeHexColor } from '../../utils/safeColor'
|
||||
@@ -28,6 +31,7 @@ import { BookingCostsSection } from './BookingCostsSection'
|
||||
import type { BookingExpenseRequest } from './BookingCostsSection.types'
|
||||
import type { Place, Category, Assignment, BudgetItem } from '../../types'
|
||||
import { NumericInput } from '../shared/NumericInput'
|
||||
import { formatDistance } from '../../utils/units'
|
||||
import { PlacesSession } from '../../utils/placesSession'
|
||||
import ServiceStopSection from '../Roadtrip/ServiceStopSection'
|
||||
import { DEFAULT_SERVICE_KIND, serviceStopChoice, type ServiceStopMode } from '../Roadtrip/manualStop'
|
||||
@@ -39,6 +43,7 @@ import {
|
||||
import { EditorField, GRID_2, INPUT, LABEL, PANEL, PillSelect, TEXTAREA } from '../shared/dialogParts'
|
||||
import { SoftPill, tintOf } from './planParts'
|
||||
import { WHITE_BUTTON } from './placeDialogParts'
|
||||
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage'
|
||||
|
||||
// The submit payload mirrors the form, but lat/lng are parsed to numbers and
|
||||
// category_id is normalised, plus any files chosen before the place existed.
|
||||
@@ -60,7 +65,7 @@ interface PlaceFormModalProps {
|
||||
onClose: () => void
|
||||
onSave: (data: PlaceSubmitData, files?: File[]) => Promise<{ id: number } | void> | void
|
||||
place: Place | null
|
||||
prefillCoords?: { lat: number; lng: number; name?: string; address?: string; website?: string; phone?: string; osm_id?: string; stop_type?: RoadtripStopType | null; duration_minutes?: number } | null
|
||||
prefillCoords?: { lat: number; lng: number; name?: string; address?: string; website?: string; phone?: string; osm_id?: string; stop_type?: RoadtripStopType | null; duration_minutes?: number; category?: string } | null
|
||||
tripId: number
|
||||
categories: Category[]
|
||||
onCategoryCreated: (category: { name: string; color?: string; icon?: string }) => Promise<Category> | undefined
|
||||
@@ -124,6 +129,9 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const [mapsResults, setMapsResults] = useState([])
|
||||
/** What answered the last full search. Only a fallback: a merged list carries the source per place. */
|
||||
const [searchSource, setSearchSource] = useState<string>('')
|
||||
// The list on screen answers "what is near the pin" rather than a typed query (#976).
|
||||
const [nearbyList, setNearbyList] = useState(false)
|
||||
const distanceUnit = useSettingsStore(s => s.settings.distance_unit) || 'metric'
|
||||
/**
|
||||
* What produced the list currently on screen, kept for the shadow log: the
|
||||
* query as typed and the provider the envelope named. A ref rather than
|
||||
@@ -146,6 +154,14 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
// to that place and goes when another is picked; anything outside it is the
|
||||
// user's and survives. See mergeResult.
|
||||
const autoFilledRef = useRef<Set<ResultField>>(new Set())
|
||||
// Whether the category was preselected from a search result rather than chosen, so
|
||||
// the next pick may replace it and a hand choice is never overwritten (#2282).
|
||||
const categoryGuessedRef = useRef(false)
|
||||
const guessedCategory = (result: Record<string, unknown>): string => {
|
||||
const id = guessCategoryId(result, categories || [])
|
||||
categoryGuessedRef.current = id != null
|
||||
return id != null ? String(id) : ''
|
||||
}
|
||||
const [pendingFiles, setPendingFiles] = useState([])
|
||||
/**
|
||||
* The leg of the drive the traveller picked, or empty while the projection's own
|
||||
@@ -170,7 +186,9 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
// billing session (see utils/placesSession).
|
||||
const placesSessionRef = useRef(new PlacesSession())
|
||||
const toast = useToast()
|
||||
const { t, language, locale } = useTranslation()
|
||||
const { t, locale } = useTranslation()
|
||||
// Place names in the language the user picked for them, the app's otherwise (#1799).
|
||||
const language = usePlaceLanguage()
|
||||
const { placesEnrichEnabled } = useAuthStore()
|
||||
const googleAnswers = useAuthStore(selectGoogleHoldsSlot)
|
||||
const can = useCanDo()
|
||||
@@ -185,6 +203,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const expenseIntentRef = useRef<{ editItem?: BudgetItem; create?: boolean } | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
categoryGuessedRef.current = false
|
||||
if (place) {
|
||||
// Times are stored per day-assignment, not on the pool place. When an
|
||||
// assignment is in context (itinerary edit, or a single-assignment pool
|
||||
@@ -222,6 +241,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
website: prefillCoords.website || '',
|
||||
phone: prefillCoords.phone || '',
|
||||
osm_id: prefillCoords.osm_id,
|
||||
category_id: guessedCategory(prefillCoords),
|
||||
stop_type: prefillCoords.stop_type ?? null,
|
||||
duration_minutes: prefillCoords.duration_minutes,
|
||||
})
|
||||
@@ -387,6 +407,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const handleChange = (field: string, value: string) => {
|
||||
// Typed by hand, so the next pick must not clear it.
|
||||
autoFilledRef.current.delete(field as ResultField)
|
||||
if (field === 'category_id') categoryGuessedRef.current = false
|
||||
setForm(prev => ({ ...prev, [field]: value }))
|
||||
}
|
||||
|
||||
@@ -423,6 +444,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const result = await mapsApi.search(trimmed, language, locationBiasPoint, provider)
|
||||
if (epoch !== searchEpochRef.current) return
|
||||
searchMetaRef.current = { query: trimmed, source: result.source || 'unknown' }
|
||||
setNearbyList(false)
|
||||
setMapsResults(result.places || [])
|
||||
setSearchSource(result.source || '')
|
||||
} catch (err: unknown) {
|
||||
@@ -433,6 +455,30 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
}
|
||||
}
|
||||
|
||||
// What is around the pin the form holds (#976): the list a search would show,
|
||||
// nearest first. Not logged as a search pick, because no query was typed.
|
||||
const pin = formPin(form)
|
||||
const handleNearby = async () => {
|
||||
if (!pin) return
|
||||
const epoch = searchEpochRef.current
|
||||
setIsSearchingMaps(true)
|
||||
setAcSuggestions([])
|
||||
try {
|
||||
const result = await mapsApi.nearby(pin.lat, pin.lng, language)
|
||||
if (epoch !== searchEpochRef.current) return
|
||||
searchMetaRef.current = null
|
||||
setNearbyList(true)
|
||||
setMapsResults(result.places || [])
|
||||
setSearchSource(result.source || '')
|
||||
if (!result.places?.length) toast.info(t('places.nearbyNone'))
|
||||
} catch (err: unknown) {
|
||||
if (epoch !== searchEpochRef.current) return
|
||||
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
|
||||
} finally {
|
||||
if (epoch === searchEpochRef.current) setIsSearchingMaps(false)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `pick` is present only when the click came from a ranked list. The
|
||||
* collection picker and the autocomplete detour reach this function with a
|
||||
@@ -440,7 +486,11 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
* worse than no row at all.
|
||||
*/
|
||||
const handleSelectMapsResult = (result, pick?: { mode: 'search' | 'autocomplete'; rank: number; count: number }) => {
|
||||
setForm(prev => mergeResult(prev, result, autoFilledRef.current))
|
||||
setForm(prev => {
|
||||
const merged = mergeResult(prev, result, autoFilledRef.current)
|
||||
if (prev.category_id && !categoryGuessedRef.current) return merged
|
||||
return { ...merged, category_id: guessedCategory(result) }
|
||||
})
|
||||
// The same name the row's badge carried. A suggestion's pick overrides it
|
||||
// with its own row's (handleSelectSuggestion); a saved place names none.
|
||||
setPickedSource(sourceLabel(result, pick?.mode === 'search' ? searchSource : ''))
|
||||
@@ -782,6 +832,10 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
sourceLabel,
|
||||
handleChange,
|
||||
handleMapsSearch,
|
||||
handleNearby,
|
||||
pin,
|
||||
nearbyList,
|
||||
distanceUnit,
|
||||
handleSelectMapsResult,
|
||||
handleSelectSuggestion,
|
||||
handleSearchKeyDown,
|
||||
@@ -837,6 +891,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
mapsSearch, setMapsSearch, mapsResults, isSearchingMaps, acSuggestions, setAcSuggestions, acSource,
|
||||
searchSource, acHighlight, setAcHighlight, t, language, googleAnswers, placesEnrichEnabled,
|
||||
canUploadFiles, fetchSuggestions, sourceLabel, handleChange, handleMapsSearch, handleSelectMapsResult,
|
||||
handleNearby, pin, nearbyList, distanceUnit,
|
||||
handleSelectSuggestion, handleSearchKeyDown, hasTimeError, handleSubmit, isSaving, duplicateWarning,
|
||||
detailsSelection, serviceStop, serviceStopDuplicate,
|
||||
} = S
|
||||
@@ -910,6 +965,10 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
}}
|
||||
pickedSource={S.pickedSource}
|
||||
busy={isSearchingMaps}
|
||||
navPlace={form.lat && form.lng ? {
|
||||
name: form.name, address: form.address, lat: Number(form.lat), lng: Number(form.lng),
|
||||
google_place_id: form.google_place_id || null, google_ftid: form.google_ftid || null,
|
||||
} : null}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
@@ -956,6 +1015,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
/>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className={FORM_COLUMN}>
|
||||
|
||||
{/* Place search: typed-ahead suggestions, a full search, and a pasted map link. */}
|
||||
<div className={PANEL}>
|
||||
<EditorField label={t('common.search')} htmlFor={`${fieldId}-search`}>
|
||||
@@ -991,6 +1051,19 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
{isSearchingMaps ? '...' : <Search size={15} strokeWidth={2.2} aria-hidden="true" />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{pin && (
|
||||
<Tooltip label={t('places.nearby')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleNearby}
|
||||
disabled={isSearchingMaps}
|
||||
aria-label={t('places.nearby')}
|
||||
className={`${SIDE_BUTTON} border border-edge bg-surface-card text-content-secondary hover:bg-surface-hover`}
|
||||
>
|
||||
<LocateFixed size={15} strokeWidth={2.2} aria-hidden="true" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Autocomplete dropdown. Capped and scrolling, because plugin rows can
|
||||
@@ -1035,6 +1108,9 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
<span className="block truncate font-medium text-content" style={fs(13, 'body')}>{result.name}</span>
|
||||
{result.address && <span className="block truncate text-content-muted" style={fs(11.5)}>{result.address}</span>}
|
||||
</span>
|
||||
{nearbyList && typeof result.distance_m === 'number' && (
|
||||
<SoftPill>{formatDistance(result.distance_m / 1000, distanceUnit)}</SoftPill>
|
||||
)}
|
||||
<SourceBadge label={sourceLabel(result, searchSource)} />
|
||||
</button>
|
||||
))}
|
||||
@@ -1045,7 +1121,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
quiet line under the list sends the same query there, on an instance
|
||||
where Google holds the key slot and for a list Google did not
|
||||
already produce. */}
|
||||
{mapsResults.length > 0 && offersGoogleRetry(searchSource, googleAnswers) && (
|
||||
{mapsResults.length > 0 && !nearbyList && offersGoogleRetry(searchSource, googleAnswers) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleMapsSearch('google')}
|
||||
@@ -1124,6 +1200,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
{/* The day in context: its times and its own note. Both live on the
|
||||
day-assignment, not on the pool place (#2163), so they are only shown
|
||||
when a single assignment is in context (itinerary edit, or a
|
||||
@@ -1238,7 +1315,7 @@ interface NewCategoryRow {
|
||||
* place of both. Then where the picked place came from, and a spinner while a
|
||||
* pick is still being looked up.
|
||||
*/
|
||||
function HeaderPills({ kind, categories, categoryId, onCategory, newCategory, pickedSource, busy, t }: {
|
||||
function HeaderPills({ kind, categories, categoryId, onCategory, newCategory, pickedSource, busy, navPlace, t }: {
|
||||
kind?: StopKind
|
||||
categories: Category[] | null
|
||||
categoryId: string
|
||||
@@ -1246,6 +1323,8 @@ function HeaderPills({ kind, categories, categoryId, onCategory, newCategory, pi
|
||||
newCategory: NewCategoryRow
|
||||
pickedSource: string | null
|
||||
busy: boolean
|
||||
/** The place as the form holds it, once it has a position: opens it in a map app (#2178). */
|
||||
navPlace: NavigablePlace | null
|
||||
t: Translate
|
||||
}) {
|
||||
// When the new-category field closes, the field or the button that closed it
|
||||
@@ -1299,6 +1378,7 @@ function HeaderPills({ kind, categories, categoryId, onCategory, newCategory, pi
|
||||
{pickedSource}
|
||||
</span>
|
||||
)}
|
||||
{navPlace && <OpenInMapsPill place={navPlace} t={t} />}
|
||||
{busy && (
|
||||
<span className={PILL} role="status" aria-label={t('places.loadingDetails')}>
|
||||
<Loader2 size={13} className="animate-spin text-content-faint" aria-hidden="true" />
|
||||
@@ -1309,6 +1389,33 @@ function HeaderPills({ kind, categories, categoryId, onCategory, newCategory, pi
|
||||
)
|
||||
}
|
||||
|
||||
type NavigablePlace = Pick<Place, 'name' | 'address' | 'lat' | 'lng' | 'google_place_id' | 'google_ftid'>
|
||||
|
||||
/**
|
||||
* A look at the picked place in a real map before it is saved (#2178): its reviews, its
|
||||
* photos, whether it is the right branch. The same apps the inspector offers, one tap
|
||||
* straight away when only one applies.
|
||||
*/
|
||||
function OpenInMapsPill({ place, t }: { place: NavigablePlace; t: Translate }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const anchorRef = useRef<HTMLSpanElement>(null)
|
||||
const targets = getNavigationTargets(place)
|
||||
if (targets.length === 0) return null
|
||||
return (
|
||||
<span ref={anchorRef} className="inline-flex">
|
||||
<Tooltip label={t('places.openInMaps')}>
|
||||
<button type="button" aria-label={t('places.openInMaps')} aria-haspopup={targets.length > 1 ? 'menu' : undefined}
|
||||
aria-expanded={targets.length > 1 ? open : undefined}
|
||||
onClick={() => { if (targets.length === 1) openNavigationTarget(targets[0]); else setOpen(o => !o) }}
|
||||
className={ROUND_PILL_BUTTON}>
|
||||
<Navigation size={13} strokeWidth={2.2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{open && <NavigationMenu targets={targets} anchor={anchorRef.current} onClose={() => setOpen(false)} />}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** The new category's name, typed where the category pill was, with its OK and Cancel beside it. */
|
||||
function NewCategoryField({ inputId, name, setName, create, setOpen, t }: NewCategoryRow & { t: Translate }) {
|
||||
return (
|
||||
|
||||
@@ -8,7 +8,7 @@ import remarkBreaks from 'remark-breaks'
|
||||
import { markdownLinkComponents } from '../shared/markdownLink'
|
||||
import { X, Clock, MapPin, ExternalLink, Phone, Banknote, Pencil, Plus, Minus, ChevronDown, ChevronUp, ChevronRight, FileText, Upload, File, FileImage, Star, Navigation, Mountain, Bookmark, BookmarkCheck, Copy } from 'lucide-react'
|
||||
import PlaceAvatar from '../shared/PlaceAvatar'
|
||||
import PlaceAvatarUpload from '../shared/PlaceAvatarUpload'
|
||||
import PlaceAvatarUpload, { pickableImages } from '../shared/PlaceAvatarUpload'
|
||||
import { BlurredCode } from '../shared/BookingCode'
|
||||
import PlaceRating from '../shared/StarRating'
|
||||
import TrackColorPicker from '../shared/TrackColorPicker'
|
||||
@@ -33,7 +33,7 @@ import { splitReservationDateTime, formatTime, formatMoney } from '../../utils/f
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { formatDistance, formatElevation } from '../../utils/units'
|
||||
import { getNavigationTargets, openNavigationTarget } from './placeNavigation'
|
||||
import { navigationTargetLabel, getNavigationTargets, openNavigationTarget } from './placeNavigation'
|
||||
import { TRANSPORT_TYPES, getAssignmentReservations } from '../../utils/dayMerge'
|
||||
import { NavigationMenu } from '../shared/NavigationMenu'
|
||||
import { resolveOpenNow, resolvePlaceTimeZone, placeWeekdayIndex, type OpeningPeriod } from './placeOpenState'
|
||||
@@ -44,6 +44,7 @@ import { DialogButton, DialogSection, DeleteButton, FooterSpacer, NEUTRAL_TINT,
|
||||
import { BOX, Field, TypeTile, toneOf, toneTint, useOpenFile } from './bookings/bookingParts'
|
||||
import { parseMeta } from './bookings/bookingsModel'
|
||||
import { SoftPill, TimePill, tintOf } from './planParts'
|
||||
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage'
|
||||
|
||||
const detailsCache = new Map()
|
||||
|
||||
@@ -189,6 +190,8 @@ interface PlaceInspectorProps {
|
||||
onUpdatePlace?: (placeId: number, data: Partial<Place>) => void
|
||||
/** Upload a custom thumbnail (#1136); enables the click-to-change avatar in trip mode. */
|
||||
onUploadImage?: (placeId: number, file: File) => Promise<void>
|
||||
/** Takes a picture already attached to the place as its image (#1242). */
|
||||
onImageFromFile?: (placeId: number, fileId: number) => Promise<void>
|
||||
/** Cast/clear the current user's star vote (#1435); enables the rating row. */
|
||||
onRate?: (placeId: number, rating: number | null) => Promise<void> | void
|
||||
leftWidth?: number
|
||||
@@ -213,7 +216,7 @@ export default function PlaceInspector({
|
||||
place, categories, mode = 'trip', days = [], selectedDayId = null, selectedAssignmentId = null,
|
||||
assignments = {}, reservations = [], onEditTransport, onEditReservation, onOpenBooking,
|
||||
onClose, onEdit: editPlace, onDelete: deletePlace, onAssignToDay, onRemoveAssignment,
|
||||
files = [], onFileUpload, tripMembers = [], onSetParticipants, onUpdatePlace: updatePlace, onUploadImage, onRate,
|
||||
files = [], onFileUpload, tripMembers = [], onSetParticipants, onUpdatePlace: updatePlace, onUploadImage, onImageFromFile, onRate,
|
||||
leftWidth = 0, rightWidth = 0,
|
||||
collectionStatus, onCopyToTrip, onSetStatus, onRemoveFromList, roadtripEndDay, roadtripStay, roadtripActive,
|
||||
}: PlaceInspectorProps) {
|
||||
@@ -245,6 +248,7 @@ export default function PlaceInspector({
|
||||
return () => { cancelled = true }
|
||||
}, [placeIdForDetails])
|
||||
const { t, locale, language } = useTranslation()
|
||||
const placeLang = usePlaceLanguage()
|
||||
// Currency-less prices mean "the trip's currency"; null in collection mode (EUR fallback below).
|
||||
const tripCurrency = useTripStore(s => s.trip?.currency)
|
||||
// The day list handed in is the one the planner shows, and in the day view that
|
||||
@@ -267,7 +271,7 @@ export default function PlaceInspector({
|
||||
const [nameValue, setNameValue] = useState('')
|
||||
const nameInputRef = useRef<HTMLInputElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const googleDetails = usePlaceDetails(place?.google_place_id, place?.osm_id, language)
|
||||
const googleDetails = usePlaceDetails(place?.google_place_id, place?.osm_id, placeLang)
|
||||
|
||||
// Library-wide "is this place already saved anywhere I can see?" indicator for
|
||||
// the trip-planner footer bookmark. Re-checks when the place changes or after
|
||||
@@ -391,7 +395,7 @@ export default function PlaceInspector({
|
||||
place ? { ...place, google_ftid: place.google_ftid || googleDetails?.google_ftid || null } : null,
|
||||
googleDetails?.google_maps_url,
|
||||
)
|
||||
const navigationLabel = navigationTargets.length === 1 ? navigationTargets[0].label : t('inspector.navigation')
|
||||
const navigationLabel = navigationTargets.length === 1 ? navigationTargetLabel(navigationTargets[0], t) : t('inspector.navigation')
|
||||
const selectedDay = days?.find(d => d.id === selectedDayId)
|
||||
const weekdayIndex = getWeekdayIndex(selectedDay?.date, placeTimeZone)
|
||||
|
||||
@@ -424,6 +428,8 @@ export default function PlaceInspector({
|
||||
commitNameEdit={commitNameEdit} handleNameKeyDown={handleNameKeyDown} startNameEdit={startNameEdit}
|
||||
onUpdatePlace={onUpdatePlace}
|
||||
onUploadImage={mode === 'trip' && onUpdatePlace ? onUploadImage : undefined}
|
||||
attachedImages={pickableImages(placeFiles)}
|
||||
onImageFromFile={mode === 'trip' && onUpdatePlace ? onImageFromFile : undefined}
|
||||
onClose={onClose} />
|
||||
|
||||
{/* The body scrolls inside the capped card; each block keeps its natural height (#1195). */}
|
||||
@@ -626,6 +632,8 @@ interface InspectorHeadProps {
|
||||
startNameEdit: () => void
|
||||
onUpdatePlace?: (placeId: number, data: Partial<Place>) => void
|
||||
onUploadImage?: (placeId: number, file: File) => Promise<void>
|
||||
attachedImages: TripFile[]
|
||||
onImageFromFile?: (placeId: number, fileId: number) => Promise<void>
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
@@ -634,7 +642,7 @@ interface InspectorHeadProps {
|
||||
* name (a double-click renames it), the address, and the facts as pills.
|
||||
*/
|
||||
function InspectorHead({ place, category, openNow, phone, rating, ratingCount, price, time, editingName, nameInputRef,
|
||||
nameValue, setNameValue, commitNameEdit, handleNameKeyDown, startNameEdit, onUpdatePlace, onUploadImage, onClose }: InspectorHeadProps) {
|
||||
nameValue, setNameValue, commitNameEdit, handleNameKeyDown, startNameEdit, onUpdatePlace, onUploadImage, attachedImages, onImageFromFile, onClose }: InspectorHeadProps) {
|
||||
const { t, locale } = useTranslation()
|
||||
const ring = openNow === true ? 'bg-success' : openNow === false ? 'bg-danger' : 'bg-surface-card shadow-sm'
|
||||
const hasCoords = !!(place.lat && place.lng)
|
||||
@@ -647,7 +655,9 @@ function InspectorHead({ place, category, openNow, phone, rating, ratingCount, p
|
||||
{onUploadImage
|
||||
? <PlaceAvatarUpload place={place} category={category} size={52}
|
||||
onUpload={(file: File) => onUploadImage(place.id, file)}
|
||||
onRemove={() => onUpdatePlace(place.id, { image_url: null })} />
|
||||
onRemove={() => onUpdatePlace(place.id, { image_url: null })}
|
||||
attachedImages={attachedImages}
|
||||
onPickAttached={onImageFromFile ? (fileId: number) => onImageFromFile(place.id, fileId) : undefined} />
|
||||
: <PlaceAvatar place={place} category={category} size={52} />}
|
||||
</div>
|
||||
<PhotoCredit imageUrl={place.image_url} />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState, type MouseEvent as ReactMouseEvent, type ReactNode } from 'react'
|
||||
import { Search, Plus, X, Upload, FileDown, ListPlus, Check, Star, CalendarPlus, CalendarDays, ChevronDown, Tag } from 'lucide-react'
|
||||
import { Search, Plus, X, Upload, FileDown, ListPlus, Check, Star, CalendarPlus, CalendarDays, ChevronDown, Tag, Globe2 } from 'lucide-react'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { ContextMenu, useContextMenu } from '../shared/ContextMenu'
|
||||
import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
|
||||
@@ -90,6 +90,7 @@ export function PlacesHeader(S: SidebarState) {
|
||||
<ShowDropdown {...S} />
|
||||
<CategoryFilter {...S} />
|
||||
<RatingFilter {...S} />
|
||||
<LocalityFilterDropdown {...S} />
|
||||
</div>
|
||||
<ActiveFilterChips {...S} />
|
||||
</div>
|
||||
@@ -325,6 +326,47 @@ function RatingFilter(S: SidebarState) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Country, or one region in it, from each place's resolved position (#2537). Shown once
|
||||
* the trip spans more than one country or region; a single one has nothing to narrow.
|
||||
*/
|
||||
function LocalityFilterDropdown(S: SidebarState) {
|
||||
const { t, localities, localityFilter, setLocalityFilter } = S
|
||||
const [open, setOpen] = useState(false)
|
||||
const regionCount = localities.reduce((n, g) => n + g.regions.length, 0)
|
||||
if (localities.length < 2 && regionCount < 2) return null
|
||||
const pick = (country: string, region: string | null) => { setLocalityFilter({ country, region }); setOpen(false) }
|
||||
const row = (key: string, label: string, count: number, on: boolean, onClick: () => void, indent: boolean) => (
|
||||
<button type="button" key={key} onClick={onClick} aria-pressed={on}
|
||||
className={`flex w-full items-center gap-2 rounded-[9px] py-1.5 pr-2 text-left transition-colors ${indent ? 'pl-5' : 'pl-2'} ${on ? 'bg-surface-tertiary' : 'hover:bg-surface-hover'}`}
|
||||
style={fs(indent ? 12 : 12.5, 'body')}>
|
||||
<span className={`min-w-0 flex-1 truncate ${indent ? 'text-content-secondary' : 'font-semibold text-content'}`}>{label}</span>
|
||||
<span className="rounded-full bg-surface-secondary px-1.5 font-geist tabular-nums text-content-faint" style={fs(10.5)}>{count}</span>
|
||||
<span className="grid w-3.5 flex-none place-items-center">{on && <Check size={13} strokeWidth={2.4} className="text-content-muted" />}</span>
|
||||
</button>
|
||||
)
|
||||
const label = localityFilter ? (localityFilter.region ?? localityFilter.country) : t('places.allLocations')
|
||||
return (
|
||||
<FilterDropdown name={t('places.filterByLocation')} label={label} active={!!localityFilter} badge={1}
|
||||
icon={<Globe2 size={14} strokeWidth={2} />} open={open} setOpen={setOpen}>
|
||||
{localities.map(g => (
|
||||
<div key={g.country} className="flex flex-col gap-px">
|
||||
{row(`c:${g.country}`, g.country, g.count, localityFilter?.country === g.country && localityFilter.region == null, () => pick(g.country, null), false)}
|
||||
{g.regions.map(r => row(`c:${g.country}:${r.region}`, r.region, r.count, localityFilter?.country === g.country && localityFilter.region === r.region, () => pick(g.country, r.region), true))}
|
||||
</div>
|
||||
))}
|
||||
{localityFilter && (
|
||||
<button type="button" onClick={() => { setLocalityFilter(null); setOpen(false) }}
|
||||
className="mt-1 flex w-full items-center gap-1.5 rounded-[9px] border-t border-edge-faint px-1.5 pb-1 pt-2 text-left font-semibold text-content-muted hover:text-content"
|
||||
style={fs(12, 'body')}>
|
||||
<X size={12} strokeWidth={2.4} />
|
||||
{t('places.clearFilter')}
|
||||
</button>
|
||||
)}
|
||||
</FilterDropdown>
|
||||
)
|
||||
}
|
||||
|
||||
function AddRow(S: SidebarState) {
|
||||
const { onAddPlace, onAddPlaceToSelectedDay, selectedDayId, t, setFileImportOpen, setListImportOpen, hasMultipleListImportProviders } = S
|
||||
const dayOpen = selectedDayId != null
|
||||
|
||||
@@ -22,6 +22,8 @@ import BookingsTimeline from './bookings/BookingsTimeline'
|
||||
import BookingDetailHost from './bookings/BookingDetailHost'
|
||||
import { useReservationDetailPlugins } from './bookings/useReservationDetailPlugins'
|
||||
import { useBookingActions } from './bookings/useBookingActions'
|
||||
import { bookingsCsv, bookingsFileName } from './bookings/bookingsExport'
|
||||
import { downloadBlob } from '../../utils/fileDownload'
|
||||
|
||||
interface ReservationsPanelProps {
|
||||
tripId: number
|
||||
@@ -94,6 +96,20 @@ export default function ReservationsPanel({
|
||||
[reservations, v.types, v.status, v.travelers, v.query, labelOf],
|
||||
)
|
||||
const sorted = useMemo(() => sortReservations(filtered, days, v.sort.by, v.sort.dir, labelOf, v.transitApart), [filtered, days, v.sort.by, v.sort.dir, labelOf, v.transitApart])
|
||||
// What is on screen, in its order, as a spreadsheet (#1360).
|
||||
const exportCsv = () => {
|
||||
const csv = bookingsCsv(sorted, {
|
||||
type: labelOf,
|
||||
status: s => (s === 'confirmed' ? t('reservations.confirmed') : s === 'pending' ? t('reservations.pending') : s),
|
||||
headers: {
|
||||
type: t('reservations.export.type'), title: t('reservations.export.title'), status: t('reservations.status'),
|
||||
start: t('reservations.export.start'), end: t('reservations.export.end'), from: t('reservations.export.from'),
|
||||
to: t('reservations.export.to'), location: t('reservations.export.location'),
|
||||
confirmation: t('reservations.export.confirmation'), notes: t('reservations.export.notes'),
|
||||
},
|
||||
})
|
||||
downloadBlob(new Blob([csv], { type: 'text/csv;charset=utf-8' }), bookingsFileName(trip?.title, kind))
|
||||
}
|
||||
const groups = useMemo(() => groupReservations(sorted, v.group, days, trip?.start_date, trip?.end_date, {
|
||||
confirmed: t('reservations.confirmed'), pending: t('reservations.pending'), transit: t('transit.sectionTitle'),
|
||||
before: t('reservations.group.before'), after: t('reservations.group.after'), undated: t('reservations.group.undated'),
|
||||
@@ -298,6 +314,7 @@ export default function ReservationsPanel({
|
||||
onTransitApart={v.view === 'cards' && v.group === 'status' && reservations.some(r => r.type === 'transit') ? v.toggleTransitApart : undefined}
|
||||
viewIsDefault={v.viewIsDefault}
|
||||
onResetView={v.resetView}
|
||||
onExport={exportCsv}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useAuthStore } from '../../store/authStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { buildUser, buildDay, buildPlace } from '../../../tests/helpers/factories'
|
||||
import type { Accommodation, Day } from '../../types'
|
||||
import TransitSearchPanel from './TransitSearchPanel'
|
||||
import TransitSearchPanel, { buildQuickPicks, dayBookingStops } from './TransitSearchPanel'
|
||||
|
||||
const { transitApiMock, toastErrors } = vi.hoisted(() => ({
|
||||
transitApiMock: { geocode: vi.fn(), plan: vi.fn() },
|
||||
@@ -663,3 +663,39 @@ describe('TransitSearchPanel', () => {
|
||||
expect(screen.getByText('Aachen, Bushof')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('quick picks from the bookings of the day (#1506)', () => {
|
||||
const day = buildDay({ id: 2, date: '2026-07-08' }) as Day
|
||||
const flight = {
|
||||
id: 5, type: 'flight', day_id: 2, end_day_id: 2, status: 'confirmed', title: 'LH 190',
|
||||
endpoints: [
|
||||
{ role: 'from', name: 'FRA', lat: 50.03, lng: 8.56, local_date: '2026-07-08', local_time: '09:00', sequence: 0 },
|
||||
{ role: 'to', name: 'BER Airport', lat: 52.36, lng: 13.5, local_date: '2026-07-08', local_time: '10:10', sequence: 1 },
|
||||
],
|
||||
}
|
||||
const nextDayTrain = {
|
||||
id: 6, type: 'train', day_id: 3, end_day_id: 3, status: 'confirmed', title: 'ICE',
|
||||
endpoints: [{ role: 'from', name: 'Berlin Hbf', lat: 52.52, lng: 13.37, local_date: '2026-07-09', local_time: null, sequence: 0 }],
|
||||
}
|
||||
const undatedFerry = {
|
||||
id: 7, type: 'ferry', day_id: 1, end_day_id: 2, status: 'confirmed', title: 'Ferry',
|
||||
endpoints: [
|
||||
{ role: 'from', name: 'Kiel', lat: 54.3, lng: 10.1, local_date: null, local_time: null, sequence: 0 },
|
||||
{ role: 'to', name: 'Oslo', lat: 59.9, lng: 10.7, local_date: null, local_time: null, sequence: 1 },
|
||||
],
|
||||
}
|
||||
const taxi = { id: 8, type: 'taxi', day_id: 2, status: 'confirmed', title: 'Taxi', endpoints: [{ role: 'from', name: 'Home', lat: 1, lng: 1, local_date: '2026-07-08', sequence: 0 }] }
|
||||
|
||||
it('FE-PLANNER-TRANSIT-031: the airports and stations of the day are offered, other days and non-carriers are not', () => {
|
||||
const stops = dayBookingStops(day, [flight, nextDayTrain, undatedFerry, taxi] as any)
|
||||
expect(stops.map(s => s.name)).toEqual(['FRA', 'BER Airport', 'Oslo'])
|
||||
})
|
||||
|
||||
it('FE-PLANNER-TRANSIT-032: they come right after the stays and are never cut by the cap', () => {
|
||||
const places = Array.from({ length: 12 }, (_, i) => buildPlace({ id: 100 + i, name: `P${i}`, lat: 52 + i / 100, lng: 13 }))
|
||||
const picks = buildQuickPicks(day, [day], places as any, [], dayBookingStops(day, [flight] as any))
|
||||
expect(picks.slice(0, 2).map(p => p.name)).toEqual(['FRA', 'BER Airport'])
|
||||
expect(picks).toHaveLength(2 + 8)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import tzlookup from 'tz-lookup'
|
||||
import { ArrowLeftRight, ArrowRight, Bus, CableCar, ChevronDown, ChevronUp, Clock, Footprints, MapPin, Sailboat, Search, TramFront, TrainFront, TrainFrontTunnel } from 'lucide-react'
|
||||
import CustomTimePicker from '../shared/CustomTimePicker'
|
||||
@@ -8,7 +9,9 @@ import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { getDayBookendHotels } from '../../utils/dayOrder'
|
||||
import type { Day, Place, Accommodation } from '../../types'
|
||||
import type { Day, Place, Accommodation, Reservation } from '../../types'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { isCarrierTransport } from '../../utils/dayMerge'
|
||||
import type { TransitProvider } from '@trek/shared'
|
||||
|
||||
/**
|
||||
@@ -110,13 +113,36 @@ function stayPick(a: Accommodation): PickedPlace | null {
|
||||
return a.place_lat != null && a.place_lng != null && a.place_name ? { name: a.place_name, lat: a.place_lat, lng: a.place_lng } : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The airports, stations and ports the day's flights, trains, buses and ferries leave
|
||||
* from or arrive at (#1506): the way to the hotel after landing starts at one of them.
|
||||
* An endpoint belongs to the day by its own local date, or, without one, by the leg's
|
||||
* day: departures on the booking's first day, arrivals on its last.
|
||||
*/
|
||||
export function dayBookingStops(day: Pick<Day, 'id' | 'date'>, reservations: Reservation[]): PickedPlace[] {
|
||||
const stops: PickedPlace[] = []
|
||||
for (const r of reservations) {
|
||||
if (!isCarrierTransport(r)) continue
|
||||
const endDay = r.end_day_id ?? r.day_id
|
||||
for (const ep of r.endpoints ?? []) {
|
||||
if (ep.lat == null || ep.lng == null || !ep.name) continue
|
||||
const onDay = ep.local_date
|
||||
? !!day.date && ep.local_date.slice(0, 10) === day.date.slice(0, 10)
|
||||
: (ep.role === 'from' && r.day_id === day.id) || (ep.role === 'to' && endDay === day.id)
|
||||
if (onDay) stops.push({ name: ep.name, lat: ep.lat, lng: ep.lng })
|
||||
}
|
||||
}
|
||||
return stops
|
||||
}
|
||||
|
||||
/**
|
||||
* What the from/to fields offer before anything is typed. The stay the day
|
||||
* starts in and the one it ends in come first and are never cut, since most
|
||||
* connections of a day begin or end there (#2538); then the day's own located
|
||||
* connections of a day begin or end there (#2538); the day's airports and
|
||||
* stations follow and are not cut either (#1506); then the day's own located
|
||||
* places and the trip's other stays, up to MAX_QUICK_PICKS.
|
||||
*/
|
||||
function buildQuickPicks(day: Day, days: Day[], places: Place[], accommodations: Accommodation[]): PickedPlace[] {
|
||||
export function buildQuickPicks(day: Day, days: Day[], places: Place[], accommodations: Accommodation[], bookingStops: PickedPlace[] = []): PickedPlace[] {
|
||||
const { morning, evening } = getDayBookendHotels(day, days, accommodations)
|
||||
const dayStays = [morning, evening].filter((a): a is Accommodation => a != null)
|
||||
|
||||
@@ -130,15 +156,55 @@ function buildQuickPicks(day: Day, days: Day[], places: Place[], accommodations:
|
||||
}
|
||||
|
||||
const stays = dayStays.map(stayPick).filter(unique)
|
||||
const stations = bookingStops.filter(unique)
|
||||
const rest = [
|
||||
...places.map(p => (p.lat != null && p.lng != null ? { name: p.name, lat: p.lat, lng: p.lng } : null)),
|
||||
...accommodations.filter(a => !dayStays.includes(a)).map(stayPick),
|
||||
].filter(unique)
|
||||
return [...stays, ...rest.slice(0, MAX_QUICK_PICKS)]
|
||||
return [...stays, ...stations, ...rest.slice(0, MAX_QUICK_PICKS)]
|
||||
}
|
||||
|
||||
// ── from/to stop picker ──────────────────────────────────────────────────────
|
||||
|
||||
const LIST_GAP = 4
|
||||
const LIST_MAX = 240
|
||||
const VIEW_EDGE = 12
|
||||
|
||||
/**
|
||||
* Where the suggestion list sits on screen: under the field, or above it when the
|
||||
* window has no room below. Measured again on scroll and resize while it is open.
|
||||
*/
|
||||
function useFloatingList(anchorRef: React.RefObject<HTMLElement | null>, open: boolean) {
|
||||
const [pos, setPos] = useState<{ left: number; width: number; top: number; bottom: number; above: boolean; maxHeight: number } | null>(null)
|
||||
useEffect(() => {
|
||||
if (!open) { setPos(null); return }
|
||||
const place = () => {
|
||||
const el = anchorRef.current
|
||||
if (!el) return
|
||||
const r = el.getBoundingClientRect()
|
||||
const below = window.innerHeight - r.bottom - VIEW_EDGE
|
||||
const aboveRoom = r.top - VIEW_EDGE
|
||||
const above = below < 160 && aboveRoom > below
|
||||
setPos({
|
||||
left: r.left,
|
||||
width: r.width,
|
||||
top: r.bottom + LIST_GAP,
|
||||
bottom: window.innerHeight - r.top + LIST_GAP,
|
||||
above,
|
||||
maxHeight: Math.max(120, Math.min(LIST_MAX, (above ? aboveRoom : below) - LIST_GAP)),
|
||||
})
|
||||
}
|
||||
place()
|
||||
window.addEventListener('resize', place)
|
||||
window.addEventListener('scroll', place, true)
|
||||
return () => {
|
||||
window.removeEventListener('resize', place)
|
||||
window.removeEventListener('scroll', place, true)
|
||||
}
|
||||
}, [open, anchorRef])
|
||||
return pos
|
||||
}
|
||||
|
||||
function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
label: string
|
||||
value: PickedPlace | null
|
||||
@@ -153,9 +219,15 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
const [open, setOpen] = useState(false)
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const fieldRef = useRef<HTMLDivElement>(null)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const listPos = useFloatingList(fieldRef, open)
|
||||
|
||||
useEffect(() => {
|
||||
const close = (e: MouseEvent) => { if (!rootRef.current?.contains(e.target as Node)) setOpen(false) }
|
||||
const close = (e: MouseEvent) => {
|
||||
const target = e.target as Node
|
||||
if (!rootRef.current?.contains(target) && !listRef.current?.contains(target)) setOpen(false)
|
||||
}
|
||||
document.addEventListener('mousedown', close)
|
||||
return () => document.removeEventListener('mousedown', close)
|
||||
}, [])
|
||||
@@ -179,7 +251,7 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
return (
|
||||
<div ref={rootRef} style={{ position: 'relative', flex: 1, minWidth: 0 }}>
|
||||
<label className="block text-[11px] font-semibold text-content-faint mb-[5px] uppercase tracking-[0.03em]">{label}</label>
|
||||
<div className="bg-surface-input border border-edge" style={{ display: 'flex', alignItems: 'center', gap: 7, borderRadius: 10, padding: '0 10px', height: 38 }}>
|
||||
<div ref={fieldRef} className="bg-surface-input border border-edge" style={{ display: 'flex', alignItems: 'center', gap: 7, borderRadius: 10, padding: '0 10px', height: 38 }}>
|
||||
<MapPin size={14} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<input
|
||||
value={display}
|
||||
@@ -190,8 +262,10 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
style={{ border: 0, background: 'none', outline: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', width: '100%', fontFamily: 'inherit' }}
|
||||
/>
|
||||
</div>
|
||||
{open && (results.length > 0 || (!value && text.trim().length < 2 && quickPicks.length > 0)) && (
|
||||
<div className="bg-surface-card border border-edge" style={{ position: 'absolute', top: '100%', left: 0, right: 0, marginTop: 4, borderRadius: 10, boxShadow: '0 8px 32px rgba(0,0,0,0.14)', zIndex: 30, overflow: 'hidden', maxHeight: 240, overflowY: 'auto' }}>
|
||||
{open && listPos && (results.length > 0 || (!value && text.trim().length < 2 && quickPicks.length > 0)) && createPortal(
|
||||
// On the page rather than inside the dialog, so a dialog that scrolls or clips
|
||||
// its content cannot cut the list off before anything is typed.
|
||||
<div ref={listRef} className="bg-surface-card border border-edge z-[var(--z-toast)]" style={{ position: 'fixed', left: listPos.left, width: listPos.width, ...(listPos.above ? { bottom: listPos.bottom } : { top: listPos.top }), borderRadius: 10, boxShadow: 'var(--shadow-dropdown)', overflow: 'hidden', maxHeight: listPos.maxHeight, overflowY: 'auto' }}>
|
||||
{results.length > 0
|
||||
? results.map((r, i) => (
|
||||
<button type="button" key={i} onClick={() => { onPick({ name: r.name, lat: r.lat, lng: r.lng }); setText(''); setResults([]); setOpen(false) }}
|
||||
@@ -202,7 +276,7 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.name}
|
||||
{r.area && <span className="text-content-faint"> · {r.area}</span>}
|
||||
{r.area && <span className="ml-1.5 text-content-faint">{r.area}</span>}
|
||||
</span>
|
||||
</button>
|
||||
))
|
||||
@@ -216,7 +290,8 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
@@ -402,7 +477,11 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
|
||||
const [addingIdx, setAddingIdx] = useState<number | null>(null)
|
||||
const [provider, setProvider] = useState<TransitProvider | null>(null)
|
||||
|
||||
const quickPicks = useMemo(() => buildQuickPicks(day, days, places, accommodations), [day, days, places, accommodations])
|
||||
const reservations = useTripStore(s => s.reservations)
|
||||
const quickPicks = useMemo(
|
||||
() => buildQuickPicks(day, days, places, accommodations, dayBookingStops(day, reservations)),
|
||||
[day, days, places, accommodations, reservations],
|
||||
)
|
||||
|
||||
const near = quickPicks.length > 0 ? `${quickPicks[0].lat},${quickPicks[0].lng}` : null
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useRef, useMemo, type ReactNode } from 'react'
|
||||
import { useParams } from 'react-router'
|
||||
import { Plane, Train, Car, Ship, Bus, Sailboat, Bike, CarTaxiFront, Route, X, Trash2, ChevronUp, ChevronDown, CalendarDays, type LucideIcon } from 'lucide-react'
|
||||
import { Plane, Train, Car, Ship, Bus, Sailboat, CableCar, Bike, CarTaxiFront, Route, X, Trash2, ChevronUp, ChevronDown, CalendarDays, type LucideIcon } from 'lucide-react'
|
||||
import ConfirmDialog from '../shared/ConfirmDialog'
|
||||
import CustomSelect from '../shared/CustomSelect'
|
||||
import { BookingCodeInput } from '../shared/BookingCode'
|
||||
@@ -31,7 +31,7 @@ import { fs, Eyebrow, type StatusTone } from './bookings/bookingParts'
|
||||
import { typeInfo } from './bookings/bookingsModel'
|
||||
import { typeToCostCategory } from '@trek/shared'
|
||||
|
||||
const TRANSPORT_TYPES = ['flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'transit', 'transport_other'] as const
|
||||
const TRANSPORT_TYPES = ['flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'cable_car', 'transit', 'transport_other'] as const
|
||||
type TransportType = typeof TRANSPORT_TYPES[number]
|
||||
|
||||
interface EndpointPick {
|
||||
@@ -142,6 +142,7 @@ const TYPE_OPTIONS: { value: TransportType; labelKey: string; Icon: LucideIcon }
|
||||
{ value: 'bicycle', labelKey: 'reservations.type.bicycle', Icon: Bike },
|
||||
{ value: 'cruise', labelKey: 'reservations.type.cruise', Icon: Ship },
|
||||
{ value: 'ferry', labelKey: 'reservations.type.ferry', Icon: Sailboat },
|
||||
{ value: 'cable_car', labelKey: 'reservations.type.cable_car', Icon: CableCar },
|
||||
{ value: 'transport_other', labelKey: 'reservations.type.transport_other', Icon: Route },
|
||||
]
|
||||
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
// FE-PLANNER-EXPORTMODAL-001 to FE-PLANNER-EXPORTMODAL-017
|
||||
// FE-PLANNER-EXPORTMODAL-001 to FE-PLANNER-EXPORTMODAL-018
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { downloadTripPDF } from '../PDF/TripPDF'
|
||||
import { buildDay, buildDayNote, buildTrip } from '../../../tests/helpers/factories'
|
||||
import { buildDay, buildDayNote, buildTrip, buildUser } from '../../../tests/helpers/factories'
|
||||
import { TripExportModal } from './TripExportModal'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import type { AssignmentsMap } from '../../types'
|
||||
|
||||
vi.mock('../PDF/TripPDF', () => ({ downloadTripPDF: vi.fn().mockResolvedValue(undefined) }))
|
||||
|
||||
@@ -274,4 +277,18 @@ describe('TripExportModal', () => {
|
||||
await user.click(screen.getByText('dayplan.gpxAll'))
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('dayplan.gpxFailed'))
|
||||
})
|
||||
|
||||
it('FE-PLANNER-EXPORTMODAL-018: "My plan" appears once people are assigned, and prints only mine (#2168)', async () => {
|
||||
const user = userEvent.setup()
|
||||
resetAllStores()
|
||||
seedStore(useAuthStore, { user: buildUser({ id: 7 }) })
|
||||
const { rerender } = render(<TripExportModal {...makeProps()} />)
|
||||
expect(screen.queryByText('dayplan.pdfMine')).toBeNull()
|
||||
|
||||
const assignments = { 10: [{ id: 1, participants: [{ user_id: 7, username: 'me' }] }] } as unknown as AssignmentsMap
|
||||
rerender(<TripExportModal {...makeProps({ assignments })} />)
|
||||
await user.click(screen.getByText('dayplan.pdfMine'))
|
||||
await waitFor(() => expect(downloadTripPDF).toHaveBeenCalledTimes(1))
|
||||
expect(vi.mocked(downloadTripPDF).mock.calls[0][0]).toMatchObject({ onlyUserId: 7 })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useId, useState } from 'react'
|
||||
import { CalendarDays, CalendarPlus, ChevronRight, Download, FileText, Loader2, MapPin, Route as RouteIcon } from 'lucide-react'
|
||||
import { CalendarDays, CalendarPlus, ChevronRight, Download, FileText, Loader2, MapPin, Route as RouteIcon, UserRound } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { DialogHeader, DialogSection, DialogShell, DialogTile, NEUTRAL_TINT, fs } from '../shared/DialogShell'
|
||||
import { IcsSubscribeModal } from './IcsSubscribeModal'
|
||||
@@ -8,6 +8,8 @@ import { useToast } from '../shared/Toast'
|
||||
import type { Trip, Day, Place, Category, AssignmentsMap, Reservation, DayNote } from '../../types'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { hasPersonalPlan } from '../PDF/pdfScope'
|
||||
|
||||
/**
|
||||
* What a GPX download can carry. Worded by what someone wants on their device
|
||||
@@ -81,9 +83,13 @@ export function TripExportModal({
|
||||
setTimeout(() => { URL.revokeObjectURL(url); a.remove() }, 100)
|
||||
}
|
||||
|
||||
const exportPdf = async () => {
|
||||
const myId = useAuthStore(s => s.user?.id)
|
||||
// "My plan" (#2168) only once somebody has been given a part of the trip.
|
||||
const offerMine = myId != null && hasPersonalPlan(assignments, reservations)
|
||||
|
||||
const exportPdf = async (mine = false) => {
|
||||
if (busy) return
|
||||
setBusy('pdf')
|
||||
setBusy(mine ? 'pdf:mine' : 'pdf')
|
||||
const flatNotes = Object.entries(dayNotes).flatMap(([dayId, notes]) =>
|
||||
notes.map(n => ({ ...n, day_id: Number(dayId) })),
|
||||
)
|
||||
@@ -93,7 +99,7 @@ export function TripExportModal({
|
||||
// exported. A missing chunk lands in the catch and shows the same error
|
||||
// the export already had.
|
||||
const { downloadTripPDF } = await import('../PDF/TripPDF')
|
||||
await downloadTripPDF({ trip, days, places, assignments, categories, dayNotes: flatNotes, reservations, t, locale, timeFormat, distanceUnit, showServiceStops })
|
||||
await downloadTripPDF({ trip, days, places, assignments, categories, dayNotes: flatNotes, reservations, t, locale, timeFormat, distanceUnit, showServiceStops, onlyUserId: mine ? myId : undefined })
|
||||
onClose()
|
||||
} catch (e) {
|
||||
console.error('PDF error:', e)
|
||||
@@ -154,14 +160,26 @@ export function TripExportModal({
|
||||
its own: one key press closes only the dialog in front. */}
|
||||
<DialogShell open={isOpen} onClose={onClose} labelledBy={titleId} width="narrow" blocked={subscribeOpen} header={header}>
|
||||
<DialogSection label={t('dayplan.exportDocument')}>
|
||||
<ExportRow
|
||||
icon={FileText}
|
||||
title={t('dayplan.pdf')}
|
||||
sub={t('dayplan.pdfTooltip')}
|
||||
busy={busy === 'pdf'}
|
||||
disabled={busy != null}
|
||||
onClick={exportPdf}
|
||||
/>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<ExportRow
|
||||
icon={FileText}
|
||||
title={t('dayplan.pdf')}
|
||||
sub={t('dayplan.pdfTooltip')}
|
||||
busy={busy === 'pdf'}
|
||||
disabled={busy != null}
|
||||
onClick={() => exportPdf()}
|
||||
/>
|
||||
{offerMine && (
|
||||
<ExportRow
|
||||
icon={UserRound}
|
||||
title={t('dayplan.pdfMine')}
|
||||
sub={t('dayplan.pdfMineSub')}
|
||||
busy={busy === 'pdf:mine'}
|
||||
disabled={busy != null}
|
||||
onClick={() => exportPdf(true)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</DialogSection>
|
||||
|
||||
<DialogSection label={t('dayplan.exportCalendar')}>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useRef, useState, type ReactNode } from 'react'
|
||||
import {
|
||||
ArrowDownUp, CalendarDays, Check, Download, Filter, GanttChart, Layers, LayoutGrid, Plane, Plus, RotateCcw, Rows3,
|
||||
ArrowDownUp, CalendarDays, Check, Download, FileSpreadsheet, Filter, GanttChart, Layers, LayoutGrid, Plane, Plus, RotateCcw, Rows3,
|
||||
Search, SlidersHorizontal, Tag, X,
|
||||
} from 'lucide-react'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
@@ -53,6 +53,8 @@ export interface BookingsHeaderProps {
|
||||
onTransitApart?: () => void
|
||||
viewIsDefault: boolean
|
||||
onResetView: () => void
|
||||
/** Downloads what is shown as a CSV (#1360). */
|
||||
onExport?: () => void
|
||||
}
|
||||
|
||||
/** A 36 px control on the bar, in the card colour so it reads on the bar's tint. */
|
||||
@@ -118,6 +120,11 @@ export default function BookingsHeader(p: BookingsHeaderProps) {
|
||||
))}
|
||||
</div>
|
||||
<ViewOptions {...p} />
|
||||
{p.onExport && (
|
||||
<Tooltip label={t('reservations.exportCsv')}>
|
||||
<button type="button" onClick={p.onExport} aria-label={t('reservations.exportCsv')} className={BAR_BTN}><FileSpreadsheet size={15} strokeWidth={2} /></button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// FE-BOOKINGS-EXPORT-001 to FE-BOOKINGS-EXPORT-003 (#1360)
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { Reservation } from '../../../types'
|
||||
import { bookingsCsv, bookingsFileName, csvCell } from './bookingsExport'
|
||||
|
||||
const labels = {
|
||||
type: (t: string) => `T:${t}`,
|
||||
status: (s: string) => `S:${s}`,
|
||||
headers: { type: 'Type', title: 'Title', status: 'Status', start: 'Start', end: 'End', from: 'From', to: 'To', location: 'Location', confirmation: 'Confirmation', notes: 'Notes' },
|
||||
}
|
||||
|
||||
describe('bookingsExport', () => {
|
||||
it('FE-BOOKINGS-EXPORT-001: quotes what needs it and defuses formulas', () => {
|
||||
expect(csvCell('plain')).toBe('plain')
|
||||
expect(csvCell('a;b')).toBe('"a;b"')
|
||||
expect(csvCell('say "hi"')).toBe('"say ""hi"""')
|
||||
expect(csvCell('=SUM(A1)')).toBe("'=SUM(A1)")
|
||||
expect(csvCell('-5')).toBe("'-5")
|
||||
expect(csvCell(null)).toBe('')
|
||||
})
|
||||
|
||||
it('FE-BOOKINGS-EXPORT-002: writes a header and one row per booking, route from its stops', () => {
|
||||
const rows = [
|
||||
{ id: 1, type: 'flight', title: 'LH 190', status: 'confirmed', reservation_time: '2026-07-07T09:15', reservation_end_time: '2026-07-07T10:25', location: null, confirmation_number: 'ABC123', notes: 'Window',
|
||||
endpoints: [{ sequence: 1, code: 'BER', name: 'Berlin' }, { sequence: 0, code: 'FRA', name: 'Frankfurt' }] },
|
||||
{ id: 2, type: 'hotel', title: 'Redo XXL', status: 'pending', reservation_time: null, reservation_end_time: null, location: 'Berlin', confirmation_number: null, notes: null },
|
||||
] as unknown as Reservation[]
|
||||
const csv = bookingsCsv(rows, labels)
|
||||
expect(csv.startsWith('\uFEFF')).toBe(true)
|
||||
const lines = csv.slice(1).trim().split('\r\n')
|
||||
expect(lines[0]).toBe('Type;Title;Status;Start;End;From;To;Location;Confirmation;Notes')
|
||||
expect(lines[1]).toBe('T:flight;LH 190;S:confirmed;2026-07-07T09:15;2026-07-07T10:25;FRA Frankfurt;BER Berlin;;ABC123;Window')
|
||||
expect(lines[2]).toBe('T:hotel;Redo XXL;S:pending;;;;;Berlin;;')
|
||||
})
|
||||
|
||||
it('FE-BOOKINGS-EXPORT-003: names the file after the trip', () => {
|
||||
expect(bookingsFileName('Berlin 2026', 'transports')).toBe('berlin-2026-transports.csv')
|
||||
expect(bookingsFileName('Zürich & Côte', 'bookings')).toBe('zurich-cote-bookings.csv')
|
||||
expect(bookingsFileName(undefined, 'bookings')).toBe('trip-bookings.csv')
|
||||
expect(bookingsFileName('!!!', 'bookings')).toBe('trip-bookings.csv')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { Reservation } from '../../../types'
|
||||
|
||||
interface ExportLabels {
|
||||
type: (type: string) => string
|
||||
status: (status: string) => string
|
||||
headers: {
|
||||
type: string; title: string; status: string; start: string; end: string
|
||||
from: string; to: string; location: string; confirmation: string; notes: string
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A spreadsheet cell: quoted when it holds a separator, a quote or a line break,
|
||||
* and prefixed with an apostrophe when it would otherwise open as a formula, so a
|
||||
* booking titled "=HYPERLINK(...)" stays text in Excel or Sheets.
|
||||
*/
|
||||
export function csvCell(value: string | null | undefined): string {
|
||||
let text = value ?? ''
|
||||
if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`
|
||||
return /[",;\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text
|
||||
}
|
||||
|
||||
/** Where a booking starts and ends, from its ordered stops when it has them (#1360). */
|
||||
function fromTo(r: Reservation): [string, string] {
|
||||
const stops = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
|
||||
if (stops.length < 2) return ['', '']
|
||||
const name = (s: (typeof stops)[number]) => [s.code, s.name].filter(Boolean).join(' ')
|
||||
return [name(stops[0]), name(stops[stops.length - 1])]
|
||||
}
|
||||
|
||||
/**
|
||||
* The bookings as a CSV for a spreadsheet (#1360), one row each in the order they
|
||||
* are shown, with a header row. Times stay as TREK stores them (ISO, local to the
|
||||
* booking), which every spreadsheet sorts correctly.
|
||||
*/
|
||||
export function bookingsCsv(reservations: Reservation[], labels: ExportLabels): string {
|
||||
const h = labels.headers
|
||||
const rows = [[h.type, h.title, h.status, h.start, h.end, h.from, h.to, h.location, h.confirmation, h.notes].map(csvCell).join(';')]
|
||||
for (const r of reservations) {
|
||||
const [from, to] = fromTo(r)
|
||||
rows.push([
|
||||
labels.type(r.type), r.title, labels.status(r.status), r.reservation_time, r.reservation_end_time,
|
||||
from, to, r.location, r.confirmation_number, r.notes,
|
||||
].map(v => csvCell(v)).join(';'))
|
||||
}
|
||||
// A byte order mark, so Excel reads the umlauts as UTF-8.
|
||||
return `\uFEFF${rows.join('\r\n')}\r\n`
|
||||
}
|
||||
|
||||
/** "berlin-2026-bookings.csv": the trip's name, made safe for a file name. */
|
||||
export function bookingsFileName(tripTitle: string | undefined, section: string): string {
|
||||
const slug = (tripTitle || 'trip').toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
|
||||
return `${slug || 'trip'}-${section}.csv`
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import {
|
||||
Plane, Hotel, Utensils, Train, Car, Ship, Bus, Sailboat, Bike, CarTaxiFront, Route, Ticket, FileText,
|
||||
Plane, Hotel, Utensils, Train, Car, Ship, Bus, Sailboat, CableCar, Bike, CarTaxiFront, Route, Ticket, FileText,
|
||||
TramFront, Users, ParkingSquare, type LucideIcon,
|
||||
} from 'lucide-react'
|
||||
import type { AssignmentsMap, Day, Reservation } from '../../../types'
|
||||
@@ -27,7 +27,7 @@ export interface ReservationTypeInfo {
|
||||
// models so the two shells can never drift apart on what a flight looks like.
|
||||
const TYPES: Record<string, { Icon: LucideIcon; chipKey?: string }> = {
|
||||
flight: { Icon: Plane }, train: { Icon: Train }, bus: { Icon: Bus }, car: { Icon: Car },
|
||||
taxi: { Icon: CarTaxiFront }, bicycle: { Icon: Bike }, cruise: { Icon: Ship }, ferry: { Icon: Sailboat },
|
||||
taxi: { Icon: CarTaxiFront }, bicycle: { Icon: Bike }, cruise: { Icon: Ship }, ferry: { Icon: Sailboat }, cable_car: { Icon: CableCar },
|
||||
transit: { Icon: TramFront, chipKey: 'reservations.typeShort.transit' }, transport_other: { Icon: Route },
|
||||
hotel: { Icon: Hotel }, restaurant: { Icon: Utensils }, event: { Icon: Ticket }, tour: { Icon: Users },
|
||||
parking: { Icon: ParkingSquare }, other: { Icon: FileText },
|
||||
@@ -45,7 +45,7 @@ export function typeInfo(type: string): ReservationTypeInfo {
|
||||
|
||||
/** The order the type pills appear in, whichever types a trip uses. */
|
||||
export const TYPE_ORDER = [
|
||||
'flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'transit', 'transport_other',
|
||||
'flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'cable_car', 'transit', 'transport_other',
|
||||
'hotel', 'restaurant', 'event', 'tour', 'parking', 'other',
|
||||
]
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ export function parsedItemToDraft(item: BookingImportPreviewItem): BookingReview
|
||||
}
|
||||
|
||||
/** Transport types route to the TransportModal; everything else to the ReservationModal. */
|
||||
const TRANSPORT_TYPES = new Set(['flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'transit', 'transport_other'])
|
||||
const TRANSPORT_TYPES = new Set(['flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'cable_car', 'transit', 'transport_other'])
|
||||
/** The types the booking form can express — its own chip list. */
|
||||
const BOOKING_TYPES = new Set(['hotel', 'restaurant', 'event', 'tour', 'activity', 'parking', 'other'])
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// FE-PLANNER-CATGUESS-001 to FE-PLANNER-CATGUESS-006
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { guessCategoryId, kindOfResult } from './placeCategoryGuess'
|
||||
|
||||
const seeded = [
|
||||
{ id: 1, name: 'Hotel', icon: '🏨' },
|
||||
{ id: 2, name: 'Restaurant', icon: '🍽️' },
|
||||
{ id: 3, name: 'Attraction', icon: '🏛️' },
|
||||
{ id: 4, name: 'Shopping', icon: '🛍️' },
|
||||
{ id: 5, name: 'Transport', icon: '🚌' },
|
||||
{ id: 6, name: 'Activity', icon: '🎯' },
|
||||
{ id: 7, name: 'Bar/Cafe', icon: '☕' },
|
||||
{ id: 8, name: 'Beach', icon: '🏖️' },
|
||||
{ id: 9, name: 'Nature', icon: '🌿' },
|
||||
{ id: 10, name: 'Other', icon: '📍' },
|
||||
]
|
||||
|
||||
describe('guessCategoryId', () => {
|
||||
it('FE-PLANNER-CATGUESS-001: an OSM hotel lands in the Hotel category', () => {
|
||||
expect(guessCategoryId({ category: 'hotel' }, seeded)).toBe(1)
|
||||
expect(guessCategoryId({ category: 'guest_house' }, seeded)).toBe(1)
|
||||
})
|
||||
|
||||
it('FE-PLANNER-CATGUESS-002: Google types are read in order, so a restaurant bar is still a bar', () => {
|
||||
expect(guessCategoryId({ types: ['restaurant', 'food', 'point_of_interest'] }, seeded)).toBe(2)
|
||||
expect(guessCategoryId({ types: ['bar', 'restaurant'] }, seeded)).toBe(7)
|
||||
expect(guessCategoryId({ types: ['museum', 'tourist_attraction'] }, seeded)).toBe(3)
|
||||
})
|
||||
|
||||
it('FE-PLANNER-CATGUESS-003: a shop and a station find their categories', () => {
|
||||
expect(guessCategoryId({ category: 'shop_bakery' }, seeded)).toBe(7)
|
||||
expect(guessCategoryId({ category: 'shop_clothes' }, seeded)).toBe(4)
|
||||
expect(guessCategoryId({ types: ['train_station', 'transit_station'] }, seeded)).toBe(5)
|
||||
})
|
||||
|
||||
it('FE-PLANNER-CATGUESS-004: renamed categories are still found, by a local name or their icon', () => {
|
||||
expect(guessCategoryId({ category: 'hotel' }, [{ id: 42, name: 'Unterkunft', icon: 'X' }])).toBe(42)
|
||||
expect(guessCategoryId({ category: 'hotel' }, [{ id: 43, name: 'Schlafen', icon: 'BedDouble' }])).toBe(43)
|
||||
})
|
||||
|
||||
it('FE-PLANNER-CATGUESS-005: nothing to go on, or nothing that fits, leaves the field empty', () => {
|
||||
expect(guessCategoryId({}, seeded)).toBeNull()
|
||||
expect(guessCategoryId({ types: ['point_of_interest'] }, seeded)).toBeNull()
|
||||
expect(guessCategoryId({ category: 'hotel' }, [{ id: 1, name: 'Food', icon: '🍴' }])).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-PLANNER-CATGUESS-006: the kind is read from any source vocabulary', () => {
|
||||
expect(kindOfResult({ category: 'italian_restaurant' })).toBe('food')
|
||||
expect(kindOfResult({ category: 'beach' })).toBe('beach')
|
||||
expect(kindOfResult({ types: ['park'] })).toBe('nature')
|
||||
expect(kindOfResult({ category: 'swimming_pool' })).toBe('activity')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { Category } from '../../types'
|
||||
|
||||
type Kind = 'lodging' | 'food' | 'drinks' | 'sight' | 'shopping' | 'transport' | 'beach' | 'nature' | 'activity'
|
||||
|
||||
/**
|
||||
* What a search result says it is, read from whichever vocabulary its source speaks:
|
||||
* Google `types`, the OpenStreetMap tag value, or the TREK Places (Overture) category.
|
||||
* Checked in order, first hit wins, so the specific kinds sit before the broad ones
|
||||
* ("bar" before "restaurant" would misfile a "restaurant_bar" otherwise).
|
||||
*/
|
||||
const KIND_TERMS: [Kind, string[]][] = [
|
||||
['lodging', ['hotel', 'hostel', 'motel', 'guest_house', 'lodging', 'resort', 'camp_site', 'campground', 'campsite', 'chalet', 'bed_and_breakfast', 'alpine_hut', 'apartment', 'caravan_site']],
|
||||
['beach', ['beach']],
|
||||
['drinks', ['cafe', 'coffee', 'bar', 'pub', 'biergarten', 'night_club', 'nightclub', 'bakery', 'ice_cream', 'wine_bar', 'brewery', 'tea_house']],
|
||||
['food', ['restaurant', 'fast_food', 'food', 'meal_', 'bistro', 'diner', 'pizzeria', 'steakhouse']],
|
||||
['transport', ['station', 'airport', 'aerodrome', 'ferry_terminal', 'bus_stop', 'terminal', 'car_rental', 'parking']],
|
||||
['shopping', ['shop', 'store', 'mall', 'supermarket', 'market', 'department_store', 'boutique']],
|
||||
['sight', ['museum', 'attraction', 'viewpoint', 'monument', 'memorial', 'castle', 'artwork', 'gallery', 'church', 'cathedral', 'place_of_worship', 'historic', 'ruins', 'landmark', 'zoo', 'aquarium', 'palace', 'tower']],
|
||||
['nature', ['park', 'nature_reserve', 'national_park', 'peak', 'waterfall', 'forest', 'garden', 'natural_feature', 'lake', 'hiking']],
|
||||
['activity', ['amusement_park', 'theme_park', 'stadium', 'sports', 'spa', 'gym', 'cinema', 'theatre', 'theater', 'bowling', 'swimming', 'golf', 'climbing', 'ski']],
|
||||
]
|
||||
|
||||
/** How a trip's category of that kind is recognised: words in its name, then its icon. */
|
||||
const KIND_CATEGORY: Record<Kind, { names: string[]; icons: string[] }> = {
|
||||
lodging: { names: ['hotel', 'accommodation', 'lodging', 'unterkunft', 'hébergement', 'alojamiento', 'alloggio', 'stay', 'hostel', 'camping'], icons: ['🏨', '🛏️', '🏠', 'BedDouble', 'Home', 'Tent'] },
|
||||
food: { names: ['restaurant', 'food', 'essen', 'ristorante', 'restaurante', 'eat'], icons: ['🍽️', '🍴', 'UtensilsCrossed', 'Utensils'] },
|
||||
drinks: { names: ['cafe', 'café', 'bar', 'coffee', 'kaffee', 'pub', 'drinks'], icons: ['☕', '🍺', '🍸', 'Coffee', 'Beer', 'Wine'] },
|
||||
sight: { names: ['attraction', 'sight', 'sehenswürdigkeit', 'museum', 'attraktion', 'culture', 'kultur'], icons: ['🏛️', '📸', 'Landmark', 'Library', 'Camera', 'Church'] },
|
||||
shopping: { names: ['shopping', 'shop', 'einkauf', 'store', 'markt'], icons: ['🛍️', 'ShoppingBag', 'Store'] },
|
||||
transport: { names: ['transport', 'verkehr', 'transit', 'station'], icons: ['🚌', '🚆', '✈️', 'Bus', 'Train', 'Plane'] },
|
||||
beach: { names: ['beach', 'strand', 'plage', 'playa', 'spiaggia'], icons: ['🏖️', 'Waves'] },
|
||||
nature: { names: ['nature', 'natur', 'park', 'outdoor', 'hiking', 'wandern'], icons: ['🌿', '🌲', '⛰️', 'TreePine', 'Leaf', 'Mountain'] },
|
||||
activity: { names: ['activity', 'aktivität', 'activité', 'actividad', 'attività', 'sport'], icons: ['🎯', 'Activity', 'Dumbbell', 'Ticket'] },
|
||||
}
|
||||
|
||||
/** The words a result carries about itself, lower-cased, whatever the source. */
|
||||
function resultTerms(result: Record<string, unknown>): string[] {
|
||||
const terms: string[] = []
|
||||
if (Array.isArray(result.types)) for (const t of result.types) if (typeof t === 'string') terms.push(t.toLowerCase())
|
||||
if (typeof result.category === 'string') terms.push(result.category.toLowerCase())
|
||||
return terms
|
||||
}
|
||||
|
||||
export function kindOfResult(result: Record<string, unknown>): Kind | null {
|
||||
const terms = resultTerms(result)
|
||||
if (terms.length === 0) return null
|
||||
for (const [kind, words] of KIND_TERMS) {
|
||||
if (terms.some(term => words.some(word => term.includes(word)))) return kind
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The trip category a picked search result most likely belongs in (#2282), or null.
|
||||
*
|
||||
* Categories are the admin's own, freely named and freely iconed, so there is no key to
|
||||
* look up; they are recognised by their name, then by their icon. When nothing matches
|
||||
* the answer is null and the field stays empty, because a wrong category that looks
|
||||
* deliberate is worse than none.
|
||||
*/
|
||||
export function guessCategoryId(result: Record<string, unknown>, categories: Pick<Category, 'id' | 'name' | 'icon'>[]): number | null {
|
||||
const kind = kindOfResult(result)
|
||||
if (!kind) return null
|
||||
const { names, icons } = KIND_CATEGORY[kind]
|
||||
const byName = categories.find(c => {
|
||||
const name = (c.name || '').toLowerCase()
|
||||
return names.some(word => name.includes(word))
|
||||
})
|
||||
if (byName) return byName.id
|
||||
const byIcon = categories.find(c => c.icon != null && icons.includes(c.icon))
|
||||
return byIcon ? byIcon.id : null
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// FE-PLANNER-LOCFILTER-001 to FE-PLANNER-LOCFILTER-002
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { localityGroups, matchesLocality } from './placeLocalityFilter'
|
||||
|
||||
describe('localityGroups', () => {
|
||||
it('FE-PLANNER-LOCFILTER-001: groups by country and region, most places first, unknown countries left out', () => {
|
||||
const groups = localityGroups([
|
||||
{ country: 'Germany', region: 'Berlin' },
|
||||
{ country: 'Germany', region: 'Berlin' },
|
||||
{ country: 'Germany', region: 'Brandenburg' },
|
||||
{ country: 'France', region: 'Île-de-France' },
|
||||
{ country: null, region: null },
|
||||
])
|
||||
expect(groups).toEqual([
|
||||
{ country: 'Germany', count: 3, regions: [{ region: 'Berlin', count: 2 }, { region: 'Brandenburg', count: 1 }] },
|
||||
{ country: 'France', count: 1, regions: [{ region: 'Île-de-France', count: 1 }] },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('matchesLocality', () => {
|
||||
it('FE-PLANNER-LOCFILTER-002: a country filter takes all its regions, a region filter only that one', () => {
|
||||
const berlin = { country: 'Germany', region: 'Berlin' }
|
||||
expect(matchesLocality(berlin, { country: 'Germany', region: null })).toBe(true)
|
||||
expect(matchesLocality(berlin, { country: 'Germany', region: 'Brandenburg' })).toBe(false)
|
||||
expect(matchesLocality(berlin, { country: 'France', region: null })).toBe(false)
|
||||
expect(matchesLocality(undefined, { country: 'Germany', region: null })).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { PlaceLocality } from '../../utils/placeLocality'
|
||||
|
||||
/** A country on its own, or one region in it. */
|
||||
export interface LocalityFilter {
|
||||
country: string
|
||||
region: string | null
|
||||
}
|
||||
|
||||
export interface LocalityGroup {
|
||||
country: string
|
||||
count: number
|
||||
regions: { region: string; count: number }[]
|
||||
}
|
||||
|
||||
/**
|
||||
* The trip's places by country and region, for the filter's list (#2537). Countries by
|
||||
* how many places they hold, then by name; the same for the regions inside each. Places
|
||||
* whose address names no country are left out, they have nothing to be filtered by.
|
||||
*/
|
||||
export function localityGroups(localities: PlaceLocality[]): LocalityGroup[] {
|
||||
const byCountry = new Map<string, { count: number; regions: Map<string, number> }>()
|
||||
for (const { country, region } of localities) {
|
||||
if (!country) continue
|
||||
const entry = byCountry.get(country) ?? { count: 0, regions: new Map<string, number>() }
|
||||
entry.count++
|
||||
if (region) entry.regions.set(region, (entry.regions.get(region) ?? 0) + 1)
|
||||
byCountry.set(country, entry)
|
||||
}
|
||||
const byCountThenName = <T extends { count: number }>(a: T, b: T, na: string, nb: string) => b.count - a.count || na.localeCompare(nb)
|
||||
return [...byCountry.entries()]
|
||||
.map(([country, { count, regions }]) => ({
|
||||
country,
|
||||
count,
|
||||
regions: [...regions.entries()].map(([region, n]) => ({ region, count: n })).sort((a, b) => byCountThenName(a, b, a.region, b.region)),
|
||||
}))
|
||||
.sort((a, b) => byCountThenName(a, b, a.country, b.country))
|
||||
}
|
||||
|
||||
export function matchesLocality(locality: PlaceLocality | undefined, filter: LocalityFilter): boolean {
|
||||
if (!locality || locality.country !== filter.country) return false
|
||||
return filter.region == null || locality.region === filter.region
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { getNavigationTargets, openNavigationTarget, showsAppleMaps } from './placeNavigation'
|
||||
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget, showsAppleMaps, showsGeoUri } from './placeNavigation'
|
||||
import type { Place } from '../../types'
|
||||
|
||||
// FE-PLANNER-NAV-001 to FE-PLANNER-NAV-008
|
||||
@@ -58,7 +58,7 @@ describe('getNavigationTargets', () => {
|
||||
it('FE-PLANNER-NAV-004b: an Android phone does not, because nobody there wants it', () => {
|
||||
const restore = withUserAgent('Mozilla/5.0 (Linux; Android 15; Pixel 9)')
|
||||
try {
|
||||
expect(getNavigationTargets(place()).map(t => t.id)).toEqual(['google', 'waze', 'osm', 'comaps'])
|
||||
expect(getNavigationTargets(place()).map(t => t.id)).toEqual(['google', 'waze', 'osm', 'comaps', 'geo'])
|
||||
} finally { restore() }
|
||||
})
|
||||
|
||||
@@ -94,6 +94,25 @@ describe('getNavigationTargets', () => {
|
||||
expect(targets.map(t => t.id)).not.toContain('comaps')
|
||||
})
|
||||
|
||||
it('FE-PLANNER-NAV-104: Android gets a geo: link for any installed map app, labeled in the UI language (#1406)', () => {
|
||||
const restore = withUserAgent('Mozilla/5.0 (Linux; Android 15; Pixel 9)')
|
||||
try {
|
||||
expect(showsGeoUri()).toBe(true)
|
||||
const geo = getNavigationTargets(place()).find(t => t.id === 'geo')!
|
||||
expect(geo.url).toBe('geo:48.2038,16.3616?q=48.2038,16.3616(Stephansdom)')
|
||||
expect(navigationTargetLabel(geo, key => `t:${key}`)).toBe('t:inspector.otherMapApp')
|
||||
} finally { restore() }
|
||||
})
|
||||
|
||||
it('FE-PLANNER-NAV-105: no geo: entry where nothing would answer it', () => {
|
||||
const restore = withUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)')
|
||||
try {
|
||||
expect(getNavigationTargets(place()).map(t => t.id)).not.toContain('geo')
|
||||
const google = getNavigationTargets(place())[0]
|
||||
expect(navigationTargetLabel(google, key => `t:${key}`)).toBe('Google Maps')
|
||||
} finally { restore() }
|
||||
})
|
||||
|
||||
it('FE-PLANNER-NAV-008: no place at all yields nothing', () => {
|
||||
expect(getNavigationTargets(null)).toEqual([])
|
||||
expect(getNavigationTargets(place({ lat: null, lng: null, name: '' }))).toEqual([])
|
||||
|
||||
@@ -7,15 +7,34 @@ import { getOpenStreetMapUrlForPlace } from './placeOpenStreetMap'
|
||||
|
||||
type PlaceLike = Pick<Place | AssignmentPlace, 'name' | 'address' | 'lat' | 'lng' | 'google_place_id' | 'google_ftid'>
|
||||
|
||||
export type NavigationAppId = 'google' | 'waze' | 'apple' | 'osm' | 'comaps' | 'amap'
|
||||
export type NavigationAppId = 'google' | 'waze' | 'apple' | 'osm' | 'comaps' | 'amap' | 'geo'
|
||||
|
||||
export interface NavigationTarget {
|
||||
id: NavigationAppId
|
||||
/** Product name. Not translated in any language, so it carries no i18n key. */
|
||||
label: string
|
||||
/** Set for the one entry that is no product (#1406): its label is this key's translation. */
|
||||
labelKey?: string
|
||||
url: string
|
||||
}
|
||||
|
||||
type Translate = (key: string) => string
|
||||
|
||||
/** What a target is called on screen: its product name, or the translated name of the generic entry. */
|
||||
export function navigationTargetLabel(target: NavigationTarget, t: Translate): string {
|
||||
return target.labelKey ? t(target.labelKey) : target.label
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the generic `geo:` link is worth offering (#1406). Android hands it to
|
||||
* whichever map app the traveller installed (OsmAnd, Organic Maps, Magic Earth…);
|
||||
* desktop browsers and iOS have no handler, so there the entry would lead nowhere.
|
||||
*/
|
||||
export function showsGeoUri(): boolean {
|
||||
if (typeof navigator === 'undefined') return false
|
||||
return /Android/i.test(navigator.userAgent)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Apple Maps is worth offering.
|
||||
*
|
||||
@@ -105,6 +124,16 @@ export function getNavigationTargets(
|
||||
if (amapUrl) targets.push({ id: 'amap', label: '高德地图', url: amapUrl })
|
||||
}
|
||||
|
||||
if (place.lat != null && place.lng != null && showsGeoUri()) {
|
||||
const label = name ? `(${encodeURIComponent(name)})` : ''
|
||||
targets.push({
|
||||
id: 'geo',
|
||||
label: 'geo:',
|
||||
labelKey: 'inspector.otherMapApp',
|
||||
url: `geo:${place.lat},${place.lng}?q=${place.lat},${place.lng}${label}`,
|
||||
})
|
||||
}
|
||||
|
||||
return targets
|
||||
}
|
||||
|
||||
@@ -120,7 +149,8 @@ export function getNavigationTargets(
|
||||
* shell was never replaced by the time the platform switched away.
|
||||
*/
|
||||
export function openNavigationTarget(target: NavigationTarget): void {
|
||||
if (isInstalledApp()) window.location.href = target.url
|
||||
// A geo: link is handed to the system, which asks for the app; a new tab would stay blank.
|
||||
if (target.id === 'geo' || isInstalledApp()) window.location.href = target.url
|
||||
else window.open(target.url, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useMemo } from 'react'
|
||||
import { Bike, Car, Footprints, Zap, type LucideIcon } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { usePluginStore } from '../../store/pluginStore'
|
||||
|
||||
export interface RouteModeOption {
|
||||
key: string
|
||||
label: string
|
||||
}
|
||||
|
||||
/** The icon a route profile key is drawn with, wherever a leg or a day names its mode. */
|
||||
export function routeModeIcon(mode: string | null | undefined): LucideIcon {
|
||||
if (mode === 'walking') return Footprints
|
||||
if (mode === 'cycling') return Bike
|
||||
if (mode?.startsWith('plugin:')) return Zap
|
||||
return Car
|
||||
}
|
||||
|
||||
/**
|
||||
* Every mode a day or a single leg can be given: the three built-in profiles plus
|
||||
* each profile a granted routeProvider plugin declared, keyed 'plugin:<id>/<profile>'
|
||||
* and labeled by the plugin's manifest.
|
||||
*/
|
||||
export function useRouteModeOptions(): RouteModeOption[] {
|
||||
const { t } = useTranslation()
|
||||
const activePlugins = usePluginStore(s => s.plugins)
|
||||
return useMemo(() => {
|
||||
const opts: RouteModeOption[] = [
|
||||
{ key: 'driving', label: t('mobileTrip.profileDriving') },
|
||||
{ key: 'walking', label: t('mobileTrip.profileWalking') },
|
||||
{ key: 'cycling', label: t('mobileTrip.profileCycling') },
|
||||
]
|
||||
for (const p of activePlugins) {
|
||||
for (const prof of p.routeProfiles ?? []) opts.push({ key: `plugin:${p.id}/${prof.id}`, label: prof.label })
|
||||
}
|
||||
return opts
|
||||
}, [activePlugins, t])
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// FE-PLANNER-STAYTIMES-001 to FE-PLANNER-STAYTIMES-004
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { stayDayTimes } from './stayDayTimes'
|
||||
|
||||
const stay = { start_day_id: 1, end_day_id: 3, check_in: '15:00', check_out: '10:00' }
|
||||
|
||||
describe('stayDayTimes', () => {
|
||||
it('FE-PLANNER-STAYTIMES-001: the arrival day keeps only the check-in', () => {
|
||||
expect(stayDayTimes(stay, 1)).toEqual({ checkIn: true, checkOut: false })
|
||||
})
|
||||
|
||||
it('FE-PLANNER-STAYTIMES-002: the departure day keeps only the check-out', () => {
|
||||
expect(stayDayTimes(stay, 3)).toEqual({ checkIn: false, checkOut: true })
|
||||
})
|
||||
|
||||
it('FE-PLANNER-STAYTIMES-003: a night in the middle shows neither time', () => {
|
||||
expect(stayDayTimes(stay, 2)).toEqual({ checkIn: false, checkOut: false })
|
||||
})
|
||||
|
||||
it('FE-PLANNER-STAYTIMES-004: a stay within one day shows both, and an unset time never shows', () => {
|
||||
expect(stayDayTimes({ ...stay, end_day_id: 1 }, 1)).toEqual({ checkIn: true, checkOut: true })
|
||||
expect(stayDayTimes({ ...stay, check_in: null }, 1)).toEqual({ checkIn: false, checkOut: false })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
interface StayRange {
|
||||
start_day_id: number | null
|
||||
end_day_id: number | null
|
||||
check_in?: string | null
|
||||
check_out?: string | null
|
||||
}
|
||||
|
||||
export interface StayDayTimes {
|
||||
/** The check-in time belongs on this day: it is the arrival day and a time is set. */
|
||||
checkIn: boolean
|
||||
/** The check-out time belongs on this day: it is the departure day and a time is set. */
|
||||
checkOut: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of a stay's two times matter on a given day (#2393). The arrival day shows the
|
||||
* check-in, the departure day the check-out, a one-night stop on a single day both; a
|
||||
* night in the middle of the stay shows neither, since nothing happens at the desk then.
|
||||
*/
|
||||
export function stayDayTimes(stay: StayRange, dayId: number): StayDayTimes {
|
||||
return {
|
||||
checkIn: stay.start_day_id === dayId && !!stay.check_in,
|
||||
checkOut: stay.end_day_id === dayId && !!stay.check_out,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import type React from 'react'
|
||||
import { placeLocality } from '../../utils/placeLocality'
|
||||
import { localityGroups, matchesLocality, type LocalityFilter } from './placeLocalityFilter'
|
||||
import { useState, useMemo, useEffect, useLayoutEffect, useRef, useCallback } from 'react'
|
||||
import { Pencil, Trash2, ExternalLink, Navigation, CalendarDays, Bookmark } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -73,7 +75,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
tripId, places, assignments, selectedDayId, days, accommodations = NO_ACCOMMODATIONS,
|
||||
pushUndo, initialScrollTop, onScrollTopChange, onEditPlace, onAssignToDay, onDeletePlace,
|
||||
} = props
|
||||
const { t } = useTranslation()
|
||||
const { t, language } = useTranslation()
|
||||
const toast = useToast()
|
||||
const ctxMenu = useContextMenu()
|
||||
const trip = useTripStore((s) => s.trip)
|
||||
@@ -184,6 +186,11 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
// which put the best first but still left everything else on the list — no
|
||||
// help at all when the point is to see only what the group actually rated.
|
||||
const [ratingFilter, setRatingFilter] = useState<number | 'all'>('all')
|
||||
// Country, or country and region, from each place's resolved position (#2537). List-only,
|
||||
// like the rating floor.
|
||||
const [localityFilter, setLocalityFilter] = useState<LocalityFilter | null>(null)
|
||||
const localityOf = useMemo(() => new Map(places.map(p => [p.id, placeLocality(p, language)])), [places, language])
|
||||
const localities = useMemo(() => localityGroups(places.map(p => localityOf.get(p.id)!)), [places, localityOf])
|
||||
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
|
||||
const [pendingDeleteIds, setPendingDeleteIds] = useState<number[] | null>(null)
|
||||
const [categoryPickerOpen, setCategoryPickerOpen] = useState(false)
|
||||
@@ -286,10 +293,11 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
if (search && !p.name.toLowerCase().includes(search.toLowerCase()) &&
|
||||
!(p.address || '').toLowerCase().includes(search.toLowerCase())) return false
|
||||
if (ratingFilter !== 'all' && (p.rating_avg == null || p.rating_avg < ratingFilter)) return false
|
||||
if (localityFilter && !matchesLocality(localityOf.get(p.id), localityFilter)) return false
|
||||
return true
|
||||
})
|
||||
return list
|
||||
}, [places, filter, categoryFilters, search, plannedIds, plannedFilterIds, ratingFilter])
|
||||
}, [places, filter, categoryFilters, search, plannedIds, plannedFilterIds, ratingFilter, localityFilter, localityOf])
|
||||
|
||||
/**
|
||||
* How many places each "show" choice would leave, under the category and search
|
||||
@@ -399,6 +407,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
search, setSearch, filter, setFilter, pickFilter, filterCounts,
|
||||
categoryFilters, setCategoryFilters,
|
||||
ratingFilter, setRatingFilter,
|
||||
localityFilter, setLocalityFilter, localities,
|
||||
selectMode, setSelectMode, selectedIds, setSelectedIds, pendingDeleteIds, setPendingDeleteIds,
|
||||
categoryPickerOpen, setCategoryPickerOpen,
|
||||
saveToListOpen, setSaveToListOpen, collectionsEnabled, tripId,
|
||||
|
||||
Reference in New Issue
Block a user