refactor(places): share the place form and the maps search between desktop and phone

usePlaceForm and usePlaceSearch take the form state, the prefill, the
opening hours selection, the duplicate name check, the payload and the
maps search out of PlaceFormModal. MPlaceEditSheet, PlPlaceSearch and
PlCategoryPicker run on the same hooks, and PlTimeFields uses the shared
timeCollisions.

Where the two shells behaved differently the hooks take a dialog or a
sheet variant: the coordinate pair rule, abort and console handling,
when the billing session ends, whether a pick clears the suggestions,
the empty search cue, whether a map link clears the results, and how a
new category is trimmed and guarded. The open effect and the submit flow
stay per shell, because service stops, expense intents and delete arming
differ too much to share.
This commit is contained in:
Maurice
2026-10-09 07:16:39 +00:00
parent b2fd0ae5aa
commit 71289ba43e
11 changed files with 1857 additions and 980 deletions
+141 -558
View File
@@ -1,15 +1,13 @@
import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNode } from 'react'
import type { RoadtripStopType } from '@trek/shared'
import NoteFormatToolbar from '../shared/NoteFormatToolbar'
import { mapsApi } from '../../api/client'
import { recordPlacePick } from '../../api/placeShadow'
import { useAuthStore } from '../../store/authStore'
import { useAddonStore } from '../../store/addonStore'
import { useCanDo } from '../../store/permissionsStore'
import { useTripStore } from '../../store/tripStore'
import { useSettingsStore } from '../../store/settingsStore'
import CollectionPicker from '../Collections/CollectionPicker'
import PlaceDetailsColumn, { type PlaceDetailsSelection } from './PlaceDetailsColumn'
import PlaceDetailsColumn from './PlaceDetailsColumn'
import { useToast } from '../shared/Toast'
import { Tooltip } from '../shared/Tooltip'
import { Search, Paperclip, X, AlertTriangle, Loader2, Plus, RotateCcw, MapPin, Navigation, LocateFixed, PencilLine } from 'lucide-react'
@@ -19,23 +17,22 @@ import { PlaceContactFields } from './PlaceContactFields'
import { weekFromPeriods } from './placeHours'
import type { PlaceOpeningHours } from '@trek/shared'
import {
DEFAULT_FORM, endsBeforeStart, findDuplicatePlace, formPin, isMapUrl, mergeResult, parseCoordinatePair, timeCollisions,
type PlaceFormData, type ResultField,
DEFAULT_FORM, endsBeforeStart, findDuplicatePlace, formPin, mergeResult, parseCoordinatePair, placeEditForm, placeFormPayload,
prefillForm, timeCollisions, type PlaceFormData,
} from './PlaceFormModal.helpers'
import { useNewCategory, usePlaceForm } from './usePlaceForm'
import { usePlaceSearch } from './usePlaceSearch'
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 { offersGoogleRetry } from '../../utils/placeSource'
import { safeHexColor } from '../../utils/safeColor'
import { useLocationBias } from '../../hooks/useLocationBias'
import { usePlaceSuggestions } from '../../hooks/usePlaceSuggestions'
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'
import { STOP_KIND_BY_KEY, type StopKind } from '../Roadtrip/stopKinds'
@@ -46,7 +43,6 @@ 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.
@@ -92,24 +88,6 @@ interface PlaceFormModalProps {
}
/**
* One row of the typed-ahead list, as the server sends it.
*
* `source`, `lat` and `lng` are optional because not every index fills them:
* Google answers with neither, and the mark falls back to the name the whole
* list carries. `place` is only on a plugin's row, which brings its whole place
* along because no details lookup knows a plugin id (#2221).
*/
type Suggestion = {
placeId: string
mainText: string
secondaryText: string
source?: string
lat?: number
lng?: number
place?: Record<string, unknown>
}
/** The mark itself. Quiet on purpose: it answers a question, it does not advertise. */
function SourceBadge({ label }: { label: string | null }) {
if (!label) return null
@@ -127,36 +105,25 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
} = props
// Hidden while the addon is off, because the kinds only mean anything to the road trip
// rail: on an instance without it they would be six labels that change nothing.
const [form, setForm] = useState(DEFAULT_FORM)
const [mapsSearch, setMapsSearch] = useState('')
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
* state because nothing renders from it and a pick must read the value that
* belonged to the list, not a value a re-render replaced.
*/
const searchMetaRef = useRef<{ query: string; source: string } | null>(null)
const acMetaRef = useRef<{ query: string; source: string } | null>(null)
const [isSearchingMaps, setIsSearchingMaps] = useState(false)
const [newCategoryName, setNewCategoryName] = useState('')
const [showNewCategory, setShowNewCategory] = useState(false)
const [isSaving, setIsSaving] = useState(false)
const [duplicateWarning, setDuplicateWarning] = useState<string | null>(null)
const toast = useToast()
const { t, locale } = useTranslation()
const { placesEnrichEnabled } = useAuthStore()
const can = useCanDo()
const timeFormat = useSettingsStore((s) => s.settings.time_format) || '24h'
const tripObj = useTripStore((s) => s.trip)
const canUploadFiles = can('file_upload', tripObj)
const collectionsEnabled = useAddonStore((s) => s.isEnabled('collections'))
const isBudgetEnabled = useAddonStore((s) => s.isEnabled('budget'))
const deleteBudgetItem = useTripStore((s) => s.deleteBudgetItem)
const {
form, setForm, autoFilledRef, pendingFiles, addFilesFromInput, removeFile, handlePaste, isSaving, setIsSaving,
duplicateWarning, detailsSelection, setDetailsSelection, openForm, handleChange: changeField, pickImage,
adoptDescription, warnIfDuplicate,
} = usePlaceForm({ t, toast, canUploadFiles })
// The index the picked place came from, as its row named it, shown as a pill
// in the head band. Null for a place typed by hand or taken from the saved list.
const [pickedSource, setPickedSource] = useState<string | null>(null)
// What the detail column is describing. Null until the user picks a result.
const [detailsSelection, setDetailsSelection] = useState<PlaceDetailsSelection | null>(null)
// Which fields the last picked search result wrote. Anything in here belongs
// 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)
@@ -165,10 +132,6 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
categoryGuessedRef.current = id != null
return id != null ? String(id) : ''
}
const [pendingFiles, setPendingFiles] = useState([])
// The query the last full search found nothing for (#2472): the cue to add the
// place by hand instead of a silent empty list.
const [emptySearch, setEmptySearch] = useState<string | null>(null)
// The hours the details column looked up, as a week the contact block can take over (#2472).
const [detailsHours, setDetailsHours] = useState<PlaceOpeningHours | null>(null)
/**
@@ -178,58 +141,23 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
*/
const [serviceStopLeg, setServiceStopLeg] = useState('')
const fileRef = useRef(null)
const [acSuggestions, setAcSuggestions] = useState<Suggestion[]>([])
// Which index answered the last keystroke, for the rows that do not say so
// themselves. Google and the OpenStreetMap fallback each answer from one
// place; the index path answers from two at once and marks every row.
const [acSource, setAcSource] = useState<string>('')
const [acHighlight, setAcHighlight] = useState(-1)
const acDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const acAbortRef = useRef<AbortController | null>(null)
// Counts the closings of this dialog, so an answer still on its way when it
// closed can tell that the opening it was asked for is over. A counter rather
// than an abort, because the full search takes no signal.
const searchEpochRef = useRef(0)
// Ties one search's keystrokes and its details lookup into a single Google
// billing session (see utils/placesSession).
const placesSessionRef = useRef(new PlacesSession())
const toast = useToast()
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()
const timeFormat = useSettingsStore((s) => s.settings.time_format) || '24h'
const tripObj = useTripStore((s) => s.trip)
const canUploadFiles = can('file_upload', tripObj)
const collectionsEnabled = useAddonStore((s) => s.isEnabled('collections'))
const isBudgetEnabled = useAddonStore((s) => s.isEnabled('budget'))
const deleteBudgetItem = useTripStore((s) => s.deleteBudgetItem)
// Set right before submit when the user clicked create/edit expense — the
// place has to exist before an expense can point at it (see ReservationModal).
const expenseIntentRef = useRef<{ editItem?: BudgetItem; create?: boolean } | null>(null)
const newCategory = useNewCategory({
variant: 'dialog',
create: category => onCategoryCreated?.(category),
onCreated: categoryId => setForm(prev => ({ ...prev, category_id: categoryId })),
t,
toast,
})
useEffect(() => {
categoryGuessedRef.current = false
let next: PlaceFormData
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
// edit) read the times off its embedded place; fall back to the place prop.
const assignment = assignmentId ? dayAssignments.find(a => a.id === assignmentId) : null
const timeSource = assignment?.place ?? place
setForm({
name: place.name || '',
description: place.description || '',
address: place.address || '',
lat: place.lat != null ? String(place.lat) : '',
lng: place.lng != null ? String(place.lng) : '',
category_id: place.category_id != null ? String(place.category_id) : '',
place_time: timeSource.place_time || '',
end_time: timeSource.end_time || '',
notes: place.notes || '',
transport_mode: place.transport_mode || 'walking',
website: place.website || '',
next = placeEditForm(place, assignment, {
// Shown in the contact block now (#2472), so an edit carries what is there.
phone: place.phone || '',
email: place.email || '',
@@ -239,20 +167,9 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
// duration_minutes deliberately stays out: how long a stay takes belongs to the
// rail's own dialog, and sending it from here would overwrite what was set there.
stop_type: place.stop_type ?? null,
// The day-specific note rides only with an assignment in context (#2163);
// otherwise the key stays absent so submit never sends a notes write.
...(assignment ? { assignment_notes: assignment.notes || '' } : {}),
})
} else if (prefillCoords) {
setForm({
...DEFAULT_FORM,
lat: String(prefillCoords.lat),
lng: String(prefillCoords.lng),
name: prefillCoords.name || '',
address: prefillCoords.address || '',
website: prefillCoords.website || '',
phone: prefillCoords.phone || '',
osm_id: prefillCoords.osm_id,
next = prefillForm(prefillCoords, {
category_id: guessedCategory(prefillCoords),
stop_type: prefillCoords.stop_type ?? null,
duration_minutes: prefillCoords.duration_minutes,
@@ -269,29 +186,19 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
// nothing selected falls back to the constant. The dwell follows the kind, the
// same way picking one by hand moves it.
const kind = serviceStop.defaultKind ?? DEFAULT_SERVICE_KIND
setForm({
next = {
...DEFAULT_FORM,
stop_type: kind,
duration_minutes: STOP_KIND_BY_KEY[kind].defaultMinutes,
})
}
} else {
setForm(DEFAULT_FORM)
next = DEFAULT_FORM
}
// A fresh dialog owns nothing yet. The exception is a POI tapped on the map
// or a right-click place: those arrive prefilled from a place, so the same
// fields belong to it and a later search pick may clear them. An existing
// place being edited is the opposite — everything on that form came out of
// the database and none of it is a search result's to drop.
autoFilledRef.current = new Set(
!place && prefillCoords
? (['name', 'address', 'lat', 'lng', 'website', 'phone', 'osm_id'] as ResultField[]).filter(
(field) => !!prefillCoords[field as keyof typeof prefillCoords],
)
: [],
)
setPendingFiles([])
// The column follows whatever the dialog was opened with, not only a search
// pick: a POI tapped on the map and a right-click place arrive as
// prefillCoords, and editing an existing place arrives as `place`.
openForm(next, place, prefillCoords)
setServiceStopLeg('')
setDuplicateWarning(null)
setPickedSource(null)
// A fresh dialog owns no intention either. The ref is armed by a click on the Costs
// section and spent by the save that follows it; a save that never happened leaves it
@@ -299,64 +206,72 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
// to. In service-stop mode that opening has no Costs section at all, so the editor
// would arrive out of nowhere, on a petrol stop, filed as an activity.
expenseIntentRef.current = null
// The column follows whatever the dialog was opened with, not only a search
// pick: a POI tapped on the map and a right-click place arrive as
// prefillCoords, and editing an existing place arrives as `place`. Without
// this the column kept showing the previous place's pictures and facts,
// because only handleSelectMapsResult ever set it.
if (place && place.lat != null && place.lng != null) {
setDetailsSelection({
placeId: place.google_place_id || place.amap_poi_id || place.osm_id || undefined,
lat: Number(place.lat),
lng: Number(place.lng),
name: place.name || '',
})
} else if (prefillCoords) {
setDetailsSelection({
placeId: prefillCoords.osm_id || undefined,
lat: prefillCoords.lat,
lng: prefillCoords.lng,
name: prefillCoords.name || '',
})
} else {
setDetailsSelection(null)
}
// dayAssignments is a fresh array each render; read it at open-time only and
// re-run on identity changes (place/assignmentId/open), not on every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [place, prefillCoords, isOpen, assignmentId])
// The planner keeps this dialog mounted while it is closed (the shell only
// stops drawing it), so everything the search block holds would greet the next
// opening: the last query, its list, the Google line offering that list's
// query again, suggestions still on their way. A pick from that list writes
// over the place being edited, whichever place that is by then. Reset when
// it closes, in an effect of its own: the one above also reruns while the
// dialog is open, when a right-click's reverse lookup fills prefillCoords,
// and must not wipe a search the user has started since.
useEffect(() => {
if (isOpen) return
searchEpochRef.current += 1
if (acDebounceRef.current) clearTimeout(acDebounceRef.current)
acAbortRef.current?.abort()
placesSessionRef.current.end()
searchMetaRef.current = null
acMetaRef.current = null
setMapsSearch('')
setMapsResults([])
setSearchSource('')
setAcSuggestions([])
setAcSource('')
setAcHighlight(-1)
setIsSearchingMaps(false)
}, [isOpen])
const places = useTripStore((s) => s.places)
// Where the trip is happening — the hint that tells the search which of a
// thousand identically named places is meant. Autocomplete wants a box, the
// search wants a point; useLocationBias derives both from the same places.
const { box: locationBias, point: locationBiasPoint } = useLocationBias()
const { autocomplete, sourceLabel } = usePlaceSuggestions()
// search wants a point; both are derived from the same places.
const { box: locationBias } = useLocationBias()
/**
* The one point every pick flows through, so the detail column hangs here: a
* search row, a suggestion's place, or a place from the saved-place picker.
* `label` is the name the picked row's badge carried; a saved place names none.
*/
const applyPickedPlace = (result: Record<string, unknown>, label: string | null) => {
setForm(prev => {
const merged = mergeResult(prev, result, autoFilledRef.current)
if (prev.category_id && !categoryGuessedRef.current) return merged
return { ...merged, category_id: guessedCategory(result) }
})
setPickedSource(label)
// A new pick drops whatever hero image belonged to the previous place.
const lat = Number(result.lat)
const lng = Number(result.lng)
if (Number.isFinite(lat) && Number.isFinite(lng)) {
setDetailsSelection({
placeId: (result.google_place_id || result.amap_poi_id || result.osm_id || undefined) as string | undefined,
lat,
lng,
name: (result.name as string) || '',
// Hand the record along: the server needs the same OSM tags, and
// looking them up again costs an Overpass round trip it can skip.
details: result,
})
setForm(prev => ({ ...prev, image_url: undefined }))
}
}
const search = usePlaceSearch({
variant: 'dialog',
locationBias,
t,
toast,
// The planner keeps this dialog mounted while it is closed (the shell only
// stops drawing it), so the search block is reset when it closes, apart from
// the opening effect above: that one also reruns while the dialog is open, when
// a right-click's reverse lookup fills prefillCoords, and must not wipe a
// search the user has started since.
open: isOpen,
onPlace: applyPickedPlace,
onSuggestionName: name => setForm(prev => ({ ...prev, name })),
onMapLink: resolved => {
setForm(prev => ({
...prev,
name: resolved.name || prev.name,
address: resolved.address || prev.address,
lat: String(resolved.lat),
lng: String(resolved.lng),
google_ftid: resolved.google_ftid || prev.google_ftid,
}))
// The fields are the link's now, not the last picked result's.
setPickedSource(null)
},
})
/**
* What a stop on a drive might be a second copy of, said while the form is being filled.
@@ -371,290 +286,14 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
return findDuplicatePlace(form, places, { byName: false, byOsmId: true })?.name ?? null
}, [serviceStop, place, form, places])
// Autocomplete fetch — aborts any in-flight request before starting a new one
const fetchSuggestions = useCallback(async (query: string) => {
if (query.length < 2 || isMapUrl(query)) {
setAcSuggestions([])
setAcHighlight(-1)
return
}
acAbortRef.current?.abort()
const controller = new AbortController()
acAbortRef.current = controller
try {
const result = await autocomplete(query, language, locationBias, controller.signal, placesSessionRef.current.current())
acMetaRef.current = { query, source: result.source || 'unknown' }
setAcSuggestions(result.suggestions || [])
setAcSource(result.source || '')
setAcHighlight(-1)
} catch (err: unknown) {
if (err instanceof Error && err.name === 'AbortError') return
if (err instanceof Error && err.name === 'CanceledError') return // axios abort
console.error('Autocomplete failed:', err)
setAcSuggestions([])
}
}, [autocomplete, language, locationBias])
// Debounce effect — only watches mapsSearch
useEffect(() => {
if (acDebounceRef.current) clearTimeout(acDebounceRef.current)
const trimmed = mapsSearch.trim()
if (trimmed.length < 2 || isMapUrl(trimmed)) {
// A list still on its way belongs to a query that is gone.
acAbortRef.current?.abort()
setAcSuggestions([])
setAcHighlight(-1)
placesSessionRef.current.end()
return
}
acDebounceRef.current = setTimeout(() => fetchSuggestions(trimmed), 300)
return () => {
if (acDebounceRef.current) clearTimeout(acDebounceRef.current)
}
}, [mapsSearch, fetchSuggestions])
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 }))
changeField(field, value)
}
const handleMapsSearch = async (provider?: 'google') => {
// The retry sends the query the list came from, not the field: the list
// stays on screen while the field is edited or cleared, and the line under
// it promises the same query.
const trimmed = provider ? (searchMetaRef.current?.query ?? '') : mapsSearch.trim()
if (!trimmed) return
const epoch = searchEpochRef.current
setIsSearchingMaps(true)
try {
// A pasted Google Maps or Amap link resolves server-side into a place
if (!provider && isMapUrl(trimmed)) {
const resolved = await mapsApi.resolveUrl(trimmed)
if (epoch !== searchEpochRef.current) return
if (resolved.lat && resolved.lng) {
setForm(prev => ({
...prev,
name: resolved.name || prev.name,
address: resolved.address || prev.address,
lat: String(resolved.lat),
lng: String(resolved.lng),
google_ftid: resolved.google_ftid || prev.google_ftid,
}))
setMapsResults([])
setMapsSearch('')
// The fields are the link's now, not the last picked result's.
setPickedSource(null)
toast.success(t('places.urlResolved'))
return
}
}
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 || [])
setEmptySearch((result.places || []).length === 0 ? trimmed : null)
setSearchSource(result.source || '')
} catch (err: unknown) {
if (epoch !== searchEpochRef.current) return
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
} finally {
if (epoch === searchEpochRef.current) setIsSearchingMaps(false)
}
}
// 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.
// What is around the pin the form holds (#976).
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
* place that was never ranked against a query, and a made-up rank would be
* worse than no row at all.
*/
const handleSelectMapsResult = (result, pick?: { mode: 'search' | 'autocomplete'; rank: number; count: number }) => {
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 : ''))
// The one point every pick flows through, so the detail column hangs here.
// A new pick drops whatever hero image belonged to the previous place.
const lat = Number(result.lat)
const lng = Number(result.lng)
if (Number.isFinite(lat) && Number.isFinite(lng)) {
setDetailsSelection({
placeId: result.google_place_id || result.amap_poi_id || result.osm_id || undefined,
lat,
lng,
name: result.name || '',
// Hand the record along: the server needs the same OSM tags, and
// looking them up again costs an Overpass round trip it can skip.
details: result,
})
setForm(prev => ({ ...prev, image_url: undefined }))
if (pick) {
const meta = pick.mode === 'search' ? searchMetaRef.current : acMetaRef.current
if (meta) {
recordPlacePick({
query: meta.query,
lang: language,
// The bias the search actually ran under is a box around the trip's
// existing places; the corpus stores its centre, which is what an
// evaluation needs to bias its own index the same way.
biasLat: locationBias ? (locationBias.low.lat + locationBias.high.lat) / 2 : undefined,
biasLng: locationBias ? (locationBias.low.lng + locationBias.high.lng) / 2 : undefined,
source: `${pick.mode}:${meta.source}`,
liveRank: pick.rank,
liveCount: pick.count,
pickedName: result.name || '',
pickedLat: lat,
pickedLng: lng,
pickedPlaceId: result.google_place_id || result.amap_poi_id || result.osm_id || null,
})
}
}
}
setMapsResults([])
setMapsSearch('')
}
const handleSelectSuggestion = async (suggestion: Suggestion) => {
// Read before the list is cleared: this is the rank the user saw.
const acPick = corePickRank(acSuggestions, suggestion)
acAbortRef.current?.abort()
setAcSuggestions([])
setAcHighlight(-1)
const previousSearch = mapsSearch
const epoch = searchEpochRef.current
setMapsSearch('')
setForm(prev => ({ ...prev, name: suggestion.mainText }))
setIsSearchingMaps(true)
try {
// The details lookup is a fragile second hop — it can fail when the
// details kill-switch is off, when the OSM Overpass mirror is overloaded,
// or on any upstream error. Treat a missing/coordinate-less place as a
// miss and fall back to the reliable text-search path the search button
// uses (its results already carry coordinates), so dropdown items stay
// clickable instead of dead-ending on "Place search failed". (#1192)
let place: Record<string, unknown> | null = suggestion.place ?? null
if (!place) {
try {
// Spends the session the suggestions opened, so Google bills the search
// once rather than per keystroke.
const result = await mapsApi.details(suggestion.placeId, language, placesSessionRef.current.peek())
if (result.place && result.place.lat != null && result.place.lng != null) {
place = result.place
}
} catch (err) {
console.error('Failed to fetch place details:', err)
}
}
// Closed while the details were on their way: the pick belongs to an
// opening that is over, and the fallback search below is not worth a
// request nobody will see.
if (epoch !== searchEpochRef.current) return
if (!place && suggestion.source === 'openstreetmap' && suggestion.lat != null && suggestion.lng != null) {
// The layer's rows carry no address; their second line is the name
// written on the building. Searching for "Tokio Hauptbahnhof, 東京駅"
// is not a question anybody asked, and its first answer would be
// whatever the index made of it — a different place, chosen silently.
// The suggestion already knows where it is, so use that.
place = {
name: suggestion.mainText,
address: '',
lat: suggestion.lat,
lng: suggestion.lng,
osm_id: suggestion.placeId,
source: 'openstreetmap',
}
}
if (!place) {
const query = [suggestion.mainText, suggestion.secondaryText].filter(Boolean).join(', ')
const search = await mapsApi.search(query, language, locationBiasPoint)
if (epoch !== searchEpochRef.current) return
place = search.places?.[0] ?? null
}
if (place) {
handleSelectMapsResult(place, acPick && { mode: 'autocomplete', ...acPick })
// Named after the row that was clicked, whatever the lookup behind it answered from.
setPickedSource(sourceLabel(suggestion, acSource))
} else {
setMapsSearch(previousSearch)
toast.error(t('places.mapsSearchError'))
}
} catch (err) {
if (epoch !== searchEpochRef.current) return
console.error('Place suggestion lookup failed:', err)
setMapsSearch(previousSearch)
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
} finally {
// Closing already ended this session; ending it again here would cut off
// the one a new opening may have started meanwhile.
if (epoch === searchEpochRef.current) {
setIsSearchingMaps(false)
placesSessionRef.current.end()
}
}
}
const handleSearchKeyDown = (e: React.KeyboardEvent) => {
if (acSuggestions.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault()
setAcHighlight(prev => (prev + 1) % acSuggestions.length)
} else if (e.key === 'ArrowUp') {
e.preventDefault()
setAcHighlight(prev => (prev <= 0 ? acSuggestions.length - 1 : prev - 1))
} else if (e.key === 'Enter') {
e.preventDefault()
if (acHighlight >= 0) {
void handleSelectSuggestion(acSuggestions[acHighlight])
} else {
setAcSuggestions([])
void handleMapsSearch()
}
} else if (e.key === 'Escape') {
// Spent on the list: the dialog leaves an Escape that was already
// handled alone, so only the next one closes it.
e.preventDefault()
setAcSuggestions([])
setAcHighlight(-1)
}
} else if (e.key === 'Enter') {
e.preventDefault()
void handleMapsSearch()
}
}
const handleNearby = () => search.searchNearby(pin)
/**
* The kind of stop, and with it how long that kind usually takes.
@@ -665,48 +304,11 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
*/
const handleStopKind = useCallback((kind: RoadtripStopType) => {
setForm(prev => ({ ...prev, stop_type: kind, duration_minutes: STOP_KIND_BY_KEY[kind].defaultMinutes }))
}, [])
}, [setForm])
const handleStopMinutes = useCallback((minutes: number) => {
setForm(prev => ({ ...prev, duration_minutes: minutes }))
}, [])
const handleCreateCategory = async () => {
if (!newCategoryName.trim()) return
try {
const cat = await onCategoryCreated?.({ name: newCategoryName, color: '#6366f1', icon: 'MapPin' }) // theme-lint-disable: the stored default of a new category, not a colour of this dialog
if (cat) setForm(prev => ({ ...prev, category_id: String(cat.id) }))
setNewCategoryName('')
setShowNewCategory(false)
} catch {
toast.error(t('places.categoryCreateError'))
}
}
const handleFileAdd = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || [])
setPendingFiles(prev => [...prev, ...files])
e.target.value = ''
}
const handleRemoveFile = (idx: number) => {
setPendingFiles(prev => prev.filter((_, i) => i !== idx))
}
// Paste support for files/images, anywhere in the dialog
const handlePaste = (e: React.ClipboardEvent) => {
if (!canUploadFiles) return
const items = e.clipboardData?.items
if (!items) return
for (const item of Array.from(items)) {
if (item.type.startsWith('image/') || item.type === 'application/pdf') {
e.preventDefault()
const file = item.getAsFile()
if (file) setPendingFiles(prev => [...prev, file])
return
}
}
}
}, [setForm])
const hasTimeError = !!place && endsBeforeStart(form.place_time, form.end_time)
@@ -729,27 +331,16 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
// save on it, only noted it. So the note is shown beside the name while the form is
// being filled (see serviceStopDuplicate), which is the earlier word anyway, and the
// press that saves is the press that saves.
if (!place && !serviceStop && !duplicateWarning) {
const dup = findDuplicatePlace(form, places)
if (dup) {
const dupName = dup.name || form.name
setDuplicateWarning(dupName)
toast.warning(t('places.duplicateExists', { name: dupName }))
// Nothing was saved, so an expense intent from a previous click is stale, and
// the next plain Save would otherwise open a Costs editor out of nowhere.
expenseIntentRef.current = null
return
}
if (!place && !serviceStop && !duplicateWarning && warnIfDuplicate(places)) {
// Nothing was saved, so an expense intent from a previous click is stale, and
// the next plain Save would otherwise open a Costs editor out of nowhere.
expenseIntentRef.current = null
return
}
setIsSaving(true)
try {
const lat = form.lat ? Number.parseFloat(form.lat) : null
const lng = form.lng ? Number.parseFloat(form.lng) : null
const payload = {
...form,
lat,
lng,
category_id: form.category_id || null,
const ctxAssignment = assignmentId ? dayAssignments.find(a => a.id === assignmentId) : null
const payload = placeFormPayload(form, pendingFiles, ctxAssignment, (lat, lng) => ({
// An explicit null is how a stop stops being a fuel stop; the service reads it
// that way rather than as "leave alone", which is what a missing key means.
stop_type: form.stop_type || null,
@@ -765,16 +356,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
...(serviceStop
? { _serviceStop: serviceStopChoice(serviceStop, lat, lng, serviceStopLeg).placement }
: {}),
_pendingFiles: pendingFiles.length > 0 ? pendingFiles : undefined,
}
// #2163: the per-assignment note only travels when an assignment is in
// context AND the value actually changed — an untouched note must not
// produce a PUT (a legacy note longer than the textarea would otherwise
// be re-sent on every unrelated save).
const ctxAssignment = assignmentId ? dayAssignments.find(a => a.id === assignmentId) : null
if (!ctxAssignment || (form.assignment_notes ?? '') === (ctxAssignment.notes ?? '')) {
delete payload.assignment_notes
}
}))
const saved = await onSave(payload)
// Open the Costs editor for the saved place when the user asked to
// create/edit its linked expense — gated on an id, so a create that the
@@ -815,49 +397,50 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
isMobile,
collectionsEnabled,
form,
setForm,
mapsSearch,
setMapsSearch,
mapsResults,
isSearchingMaps,
newCategoryName,
setNewCategoryName,
showNewCategory,
setShowNewCategory,
mapsSearch: search.query,
setMapsSearch: search.setQuery,
mapsResults: search.results,
isSearchingMaps: search.searching,
newCategoryName: newCategory.name,
setNewCategoryName: newCategory.setName,
showNewCategory: newCategory.open,
setShowNewCategory: newCategory.setOpen,
isSaving,
pendingFiles,
emptySearch, setEmptySearch,
emptySearch: search.emptySearch, setEmptySearch: search.setEmptySearch,
detailsHours, setDetailsHours,
fileRef,
acSuggestions,
setAcSuggestions,
acSource,
searchSource,
acHighlight,
setAcHighlight,
acSuggestions: search.suggestions,
setAcSuggestions: search.setSuggestions,
acSource: search.acSource,
searchSource: search.searchSource,
acHighlight: search.highlight,
setAcHighlight: search.setHighlight,
t,
language,
language: search.language,
locale,
timeFormat,
googleAnswers,
googleAnswers: search.googleAnswers,
placesEnrichEnabled,
canUploadFiles,
locationBias,
fetchSuggestions,
sourceLabel,
fetchSuggestions: search.fetchSuggestions,
sourceLabel: search.sourceLabel,
handleChange,
handleMapsSearch,
handleMapsSearch: search.runSearch,
handleNearby,
pin,
nearbyList,
nearbyList: search.nearbyList,
distanceUnit,
handleSelectMapsResult,
handleSelectSuggestion,
handleSearchKeyDown,
handleCreateCategory,
handleFileAdd,
handleRemoveFile,
handleSelectMapsResult: search.pickPlace,
handleSelectSuggestion: search.selectSuggestion,
handleSearchKeyDown: search.handleKeyDown,
handleCreateCategory: newCategory.submit,
handleFileAdd: addFilesFromInput,
handleRemoveFile: removeFile,
handlePaste,
pickImage,
adoptDescription,
hasTimeError,
handleSubmit,
duplicateWarning,
@@ -902,7 +485,7 @@ type Translate = (key: string, params?: Record<string, string | number>) => stri
export default function PlaceFormModal(props: PlaceFormModalProps) {
const S = usePlaceFormModal(props)
const {
isOpen, onClose, place, prefillCoords, categories, isMobile, collectionsEnabled, form, setForm,
isOpen, onClose, place, prefillCoords, categories, isMobile, collectionsEnabled, form,
mapsSearch, setMapsSearch, mapsResults, isSearchingMaps, acSuggestions, setAcSuggestions, acSource,
searchSource, acHighlight, setAcHighlight, t, language, googleAnswers, placesEnrichEnabled,
canUploadFiles, fetchSuggestions, sourceLabel, handleChange, handleMapsSearch, handleSelectMapsResult,
@@ -1021,8 +604,8 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
<PlaceDetailsColumn
selection={detailsSelection}
selectedImageUrl={form.image_url}
onPickImage={(url) => setForm(prev => ({ ...prev, image_url: url ?? undefined }))}
onAdoptDescription={(text) => setForm(prev => ({ ...prev, description: text }))}
onPickImage={S.pickImage}
onAdoptDescription={S.adoptDescription}
onHours={(hours) => S.setDetailsHours(weekFromPeriods(hours.periods))}
hasDescription={!!form.description.trim()}
language={language}