mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 09:22:15 +00:00
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:
@@ -3,10 +3,15 @@ import { MapPin } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import {
|
||||
DEFAULT_FORM,
|
||||
endsBeforeStart,
|
||||
mergeResult,
|
||||
parseCoordinatePair,
|
||||
placeEditForm,
|
||||
placeFormPayload,
|
||||
prefillForm,
|
||||
type PlaceFormData,
|
||||
type ResultField,
|
||||
} from '../../../../components/Planner/PlaceFormModal.helpers'
|
||||
import { usePlaceForm } from '../../../../components/Planner/usePlaceForm'
|
||||
import { Eyebrow, FIELD_AREA_CLS, FIELD_CLS, FormSheetFooter, FormSheetHeader } from './PlSheetChrome'
|
||||
import { useAddonStore } from '../../../../store/addonStore'
|
||||
import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'
|
||||
@@ -15,7 +20,7 @@ import PlCategoryPicker from './PlCategoryPicker'
|
||||
import PlTimeFields from './PlTimeFields'
|
||||
import PlFileAttach from './PlFileAttach'
|
||||
import MLinkedCosts from './MLinkedCosts'
|
||||
import PlaceDetailsColumn, { type PlaceDetailsSelection } from '../../../../components/Planner/PlaceDetailsColumn'
|
||||
import PlaceDetailsColumn from '../../../../components/Planner/PlaceDetailsColumn'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import { useAuthStore } from '../../../../store/authStore'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
@@ -29,30 +34,6 @@ export interface MPlaceEditSheetProps {
|
||||
onOpenExpense: (req: BookingExpenseRequest) => void
|
||||
}
|
||||
|
||||
// #1152: same duplicate heuristic as the desktop form — shared Google Place ID,
|
||||
// case-insensitive name match, or near-identical coordinates (~11 m).
|
||||
const DUP_COORD_TOLERANCE = 0.0001
|
||||
|
||||
function findDuplicateName(
|
||||
form: PlaceFormData,
|
||||
places: { name?: string | null; lat?: number | string | null; lng?: number | string | null; google_place_id?: string | null }[],
|
||||
): string | null {
|
||||
const name = form.name.trim().toLowerCase()
|
||||
const gid = (form.google_place_id || '').trim()
|
||||
const lat = form.lat ? Number.parseFloat(form.lat) : null
|
||||
const lng = form.lng ? Number.parseFloat(form.lng) : null
|
||||
for (const p of places || []) {
|
||||
if (gid && p.google_place_id && p.google_place_id === gid) return p.name || form.name
|
||||
if (name && p.name && p.name.trim().toLowerCase() === name) return p.name
|
||||
if (
|
||||
lat != null && lng != null && p.lat != null && p.lng != null &&
|
||||
Math.abs(Number(p.lat) - lat) <= DUP_COORD_TOLERANCE &&
|
||||
Math.abs(Number(p.lng) - lng) <= DUP_COORD_TOLERANCE
|
||||
) return p.name || form.name
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The visit the editor was opened on, looked up in the planner's STORED list.
|
||||
*
|
||||
@@ -86,13 +67,14 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
handleSavePlace, setDeletePlaceId, confirmDeletePlace,
|
||||
} = planner
|
||||
|
||||
const [form, setForm] = useState<PlaceFormData>(DEFAULT_FORM)
|
||||
// Which fields the last picked search result wrote. See mergeResult.
|
||||
const autoFilledRef = useRef<Set<ResultField>>(new Set())
|
||||
const [pendingFiles, setPendingFiles] = useState<File[]>([])
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
// The fields, which of them the last picked search result wrote (see mergeResult), the
|
||||
// pending files and the details block follow the same rules as the desktop dialog.
|
||||
const {
|
||||
form, setForm, autoFilledRef, pendingFiles, addFiles, removeFile, handlePaste, isSaving, setIsSaving,
|
||||
duplicateWarning, detailsSelection, setDetailsSelection, openForm, handleChange, pickImage, adoptDescription,
|
||||
warnIfDuplicate,
|
||||
} = usePlaceForm({ t, toast, canUploadFiles })
|
||||
const [resolvingPick, setResolvingPick] = useState(false)
|
||||
const [duplicateWarning, setDuplicateWarning] = useState<string | null>(null)
|
||||
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
// Set right before submit: the place has to exist before an expense can point
|
||||
// at it, exactly like MReservationSheet does it.
|
||||
@@ -104,10 +86,6 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
const [sheetPlace, setSheetPlace] = useState<Place | null>(null)
|
||||
const [sheetAssignmentId, setSheetAssignmentId] = useState<number | null>(null)
|
||||
|
||||
// The details block under the search field follows the same selection rules
|
||||
// as the desktop dialog's left column: the picked search result, else the
|
||||
// place being edited, else whatever a map POI prefilled.
|
||||
const [detailsSelection, setDetailsSelection] = useState<PlaceDetailsSelection | null>(null)
|
||||
const placesEnrichEnabled = useAuthStore(s => s.placesEnrichEnabled)
|
||||
const { language, locale } = useTranslation()
|
||||
const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
|
||||
@@ -130,76 +108,18 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
}, [sheetPlace, assignments, ctxAssignment])
|
||||
|
||||
// Prefill on open — same source order as the desktop form: editing place
|
||||
// (times off the in-context assignment), map/POI prefill coords, blank.
|
||||
// (times off the in-context assignment), map/POI prefill coords, blank. The
|
||||
// details block follows the same order, so it never keeps showing the previous
|
||||
// sheet's place.
|
||||
useEffect(() => {
|
||||
if (!showPlaceForm) return
|
||||
setSheetPlace(editingPlace)
|
||||
setSheetAssignmentId(editingAssignmentId)
|
||||
if (editingPlace) {
|
||||
const assignment = findVisit(storedAssignments, editingAssignmentId)
|
||||
const timeSource = assignment?.place ?? editingPlace
|
||||
setForm({
|
||||
name: editingPlace.name || '',
|
||||
description: editingPlace.description || '',
|
||||
address: editingPlace.address || '',
|
||||
lat: editingPlace.lat != null ? String(editingPlace.lat) : '',
|
||||
lng: editingPlace.lng != null ? String(editingPlace.lng) : '',
|
||||
category_id: editingPlace.category_id != null ? String(editingPlace.category_id) : '',
|
||||
place_time: timeSource.place_time || '',
|
||||
end_time: timeSource.end_time || '',
|
||||
notes: editingPlace.notes || '',
|
||||
transport_mode: editingPlace.transport_mode || 'walking',
|
||||
website: editingPlace.website || '',
|
||||
// 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,
|
||||
})
|
||||
} else {
|
||||
setForm(DEFAULT_FORM)
|
||||
}
|
||||
// Same source order as the desktop dialog: an existing place's provider id
|
||||
// and coordinates, a map POI's prefill, or nothing. Without this the block
|
||||
// would keep showing the previous sheet's place.
|
||||
if (editingPlace && editingPlace.lat != null && editingPlace.lng != null) {
|
||||
setDetailsSelection({
|
||||
placeId: editingPlace.google_place_id || editingPlace.amap_poi_id || editingPlace.osm_id || undefined,
|
||||
lat: Number(editingPlace.lat),
|
||||
lng: Number(editingPlace.lng),
|
||||
name: editingPlace.name || '',
|
||||
})
|
||||
} else if (prefillCoords) {
|
||||
setDetailsSelection({
|
||||
placeId: prefillCoords.osm_id || undefined,
|
||||
lat: prefillCoords.lat,
|
||||
lng: prefillCoords.lng,
|
||||
name: prefillCoords.name || '',
|
||||
})
|
||||
} else {
|
||||
setDetailsSelection(null)
|
||||
}
|
||||
// A fresh sheet owns nothing yet; one opened on a map POI owns whatever
|
||||
// that POI filled in. An existing place being edited owns nothing either —
|
||||
// everything on that form came out of the database.
|
||||
autoFilledRef.current = new Set(
|
||||
!editingPlace && prefillCoords
|
||||
? (['name', 'address', 'lat', 'lng', 'website', 'phone', 'osm_id'] as ResultField[]).filter(
|
||||
(field) => !!prefillCoords[field as keyof typeof prefillCoords],
|
||||
)
|
||||
: [],
|
||||
)
|
||||
setPendingFiles([])
|
||||
setDuplicateWarning(null)
|
||||
let next: PlaceFormData
|
||||
if (editingPlace) next = placeEditForm(editingPlace, findVisit(storedAssignments, editingAssignmentId))
|
||||
else if (prefillCoords) next = prefillForm(prefillCoords)
|
||||
else next = DEFAULT_FORM
|
||||
openForm(next, editingPlace, prefillCoords)
|
||||
setDeleteArmed(false)
|
||||
// storedAssignments is a fresh map each load, so it is read at open time only.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -210,12 +130,6 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
// while it still fits inside one region.
|
||||
const { box: locationBias } = useLocationBias()
|
||||
|
||||
const handleChange = (field: keyof PlaceFormData, value: string) => {
|
||||
// Typed by hand, so the next pick must leave it alone.
|
||||
autoFilledRef.current.delete(field as ResultField)
|
||||
setForm(prev => ({ ...prev, [field]: value }))
|
||||
}
|
||||
|
||||
// Same fix as the desktop dialog, same helper. `?? prev.X` cannot tell a
|
||||
// value the user typed from one the previous pick wrote, so searching an
|
||||
// airport and then a station left the airport's website in the field.
|
||||
@@ -248,37 +162,16 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
}
|
||||
|
||||
const handleCoordPaste = (e: ClipboardEvent<HTMLInputElement>) => {
|
||||
const text = e.clipboardData.getData('text').trim()
|
||||
// Same grammar as before, spelled without the overlapping quantifiers pasted text
|
||||
// could make backtrack: the separator is either a comma/semicolon with optional
|
||||
// padding or pure whitespace, and a decimal is digits with an optional ".digits".
|
||||
const match = text.match(/^(-?\d+(?:\.\d*)?)(?:\s*[,;]\s*|\s+)(-?\d+(?:\.\d*)?)$/)
|
||||
if (match) {
|
||||
const pair = parseCoordinatePair(e.clipboardData.getData('text'))
|
||||
if (pair) {
|
||||
e.preventDefault()
|
||||
setForm(prev => ({ ...prev, lat: match[1], lng: match[2] }))
|
||||
}
|
||||
}
|
||||
|
||||
// Clipboard images/PDFs from any focused field become pending attachments.
|
||||
const handlePaste = (e: ClipboardEvent) => {
|
||||
if (!canUploadFiles) return
|
||||
for (const item of Array.from(e.clipboardData?.items || [])) {
|
||||
if (item.type.startsWith('image/') || item.type === 'application/pdf') {
|
||||
e.preventDefault()
|
||||
const file = item.getAsFile()
|
||||
if (file) setPendingFiles(prev => [...prev, file])
|
||||
return
|
||||
}
|
||||
setForm(prev => ({ ...prev, lat: pair[0], lng: pair[1] }))
|
||||
}
|
||||
}
|
||||
|
||||
// End before start blocks the save — tied to the values, not to which entry
|
||||
// point opened the sheet.
|
||||
const hasTimeError = Boolean(
|
||||
form.place_time && form.end_time &&
|
||||
form.place_time.length >= 5 && form.end_time.length >= 5 &&
|
||||
form.end_time <= form.place_time,
|
||||
)
|
||||
const hasTimeError = endsBeforeStart(form.place_time, form.end_time)
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!form.name.trim()) {
|
||||
@@ -287,32 +180,12 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
}
|
||||
// #1152: first save of a new place warns on likely duplicates; a second
|
||||
// tap with the warning showing is the explicit "add anyway".
|
||||
if (!sheetPlace && !duplicateWarning) {
|
||||
const dup = findDuplicateName(form, places)
|
||||
if (dup) {
|
||||
setDuplicateWarning(dup)
|
||||
toast.warning(t('places.duplicateExists', { name: dup }))
|
||||
return
|
||||
}
|
||||
}
|
||||
if (!sheetPlace && !duplicateWarning && warnIfDuplicate(places)) return
|
||||
const withExpense = expenseIntentRef.current
|
||||
expenseIntentRef.current = false
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const payload = {
|
||||
...form,
|
||||
lat: form.lat ? Number.parseFloat(form.lat) : null,
|
||||
lng: form.lng ? Number.parseFloat(form.lng) : null,
|
||||
category_id: form.category_id || null,
|
||||
_pendingFiles: pendingFiles.length > 0 ? pendingFiles : undefined,
|
||||
}
|
||||
// #2163: the per-assignment note only travels when an assignment is in
|
||||
// context AND the value actually changed — same dirty-check as the
|
||||
// desktop form, so an untouched note never produces a PUT.
|
||||
if (!ctxAssignment || (form.assignment_notes ?? '') === (ctxAssignment.notes ?? '')) {
|
||||
delete payload.assignment_notes
|
||||
}
|
||||
const saved = await handleSavePlace(payload)
|
||||
const saved = await handleSavePlace(placeFormPayload(form, pendingFiles, ctxAssignment))
|
||||
const savedId = saved?.id ?? sheetPlace?.id ?? null
|
||||
if (withExpense && savedId) {
|
||||
onOpenExpense({ prefill: { placeId: savedId, name: form.name.trim(), category: 'activities' } })
|
||||
@@ -371,8 +244,8 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
<PlaceDetailsColumn
|
||||
selection={detailsSelection}
|
||||
selectedImageUrl={form.image_url}
|
||||
onPickImage={(url) => setForm(prev => ({ ...prev, image_url: url ?? undefined }))}
|
||||
onAdoptDescription={(text) => setForm(prev => ({ ...prev, description: text }))}
|
||||
onPickImage={pickImage}
|
||||
onAdoptDescription={adoptDescription}
|
||||
hasDescription={!!form.description.trim()}
|
||||
language={language}
|
||||
timeFormat={timeFormat}
|
||||
@@ -479,8 +352,8 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
<PlFileAttach
|
||||
planner={planner}
|
||||
files={pendingFiles}
|
||||
onAdd={files => setPendingFiles(prev => [...prev, ...files])}
|
||||
onRemove={idx => setPendingFiles(prev => prev.filter((_, i) => i !== idx))}
|
||||
onAdd={addFiles}
|
||||
onRemove={removeFile}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { Ban, Check, Plus } from 'lucide-react'
|
||||
import { getCategoryIcon } from '../../../../components/shared/categoryIcons'
|
||||
import { useNewCategory } from '../../../../components/Planner/usePlaceForm'
|
||||
import { FIELD_CLS } from './PlSheetChrome'
|
||||
import type { Category } from '../../../../types'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
|
||||
interface PlCategoryPickerProps {
|
||||
@@ -22,24 +21,9 @@ const PILL_BASE =
|
||||
*/
|
||||
export default function PlCategoryPicker({ planner, value, onChange }: PlCategoryPickerProps) {
|
||||
const { t, toast, categories, tripActions } = planner
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [newName, setNewName] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!newName.trim() || saving) return
|
||||
setSaving(true)
|
||||
try {
|
||||
const created: Category = await tripActions.addCategory({ name: newName.trim(), color: '#6366f1', icon: 'MapPin' })
|
||||
onChange(String(created.id))
|
||||
setNewName('')
|
||||
setCreating(false)
|
||||
} catch {
|
||||
toast.error(t('places.categoryCreateError'))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
const {
|
||||
open: creating, setOpen: setCreating, name: newName, setName: setNewName, saving, submit: handleCreate,
|
||||
} = useNewCategory({ variant: 'sheet', create: tripActions.addCategory, onCreated: onChange, t, toast })
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
|
||||
@@ -1,17 +1,8 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Loader2, RotateCcw, Search } from 'lucide-react'
|
||||
import { mapsApi } from '../../../../api/client'
|
||||
import { useAuthStore } from '../../../../store/authStore'
|
||||
import { corePickRank, offersGoogleRetry, selectGoogleHoldsSlot } from '../../../../utils/placeSource'
|
||||
import { recordPlacePick } from '../../../../api/placeShadow'
|
||||
import { PlacesSession } from '../../../../utils/placesSession'
|
||||
import { isMapUrl } from '../../../../components/Planner/PlaceFormModal.helpers'
|
||||
import { getApiErrorMessage } from '../../../../utils/apiError'
|
||||
import { pointFromBox } from '../../../../hooks/useLocationBias'
|
||||
import { usePlaceSuggestions } from '../../../../hooks/usePlaceSuggestions'
|
||||
import { offersGoogleRetry } from '../../../../utils/placeSource'
|
||||
import { usePlaceSearch, type MapsPlace } from '../../../../components/Planner/usePlaceSearch'
|
||||
import { FIELD_CLS } from './PlSheetChrome'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
import { usePlaceLanguage } from '../../../../hooks/usePlaceLanguage'
|
||||
|
||||
/** Fields a search pick can contribute to the place form. */
|
||||
export interface PlSearchPick {
|
||||
@@ -34,20 +25,6 @@ export interface PlSearchPick {
|
||||
details?: MapsPlace
|
||||
}
|
||||
|
||||
interface Suggestion {
|
||||
placeId: string
|
||||
mainText: string
|
||||
secondaryText: string
|
||||
/** Which of the two indexes this row came from, when the list is both. */
|
||||
source?: string
|
||||
lat?: number
|
||||
lng?: number
|
||||
/** Only on a plugin's row: its whole place, since no details lookup knows a plugin id. */
|
||||
place?: MapsPlace
|
||||
}
|
||||
|
||||
type MapsPlace = Record<string, unknown>
|
||||
|
||||
/** The same mark the desktop form shows, in the sheet's own tokens. */
|
||||
function SourceMark({ label }: { label: string | null }) {
|
||||
if (!label) return null
|
||||
@@ -67,9 +44,6 @@ interface PlPlaceSearchProps {
|
||||
onResolvingChange?: (resolving: boolean) => void
|
||||
}
|
||||
|
||||
/** "48.8566, 2.3522" (also ; or whitespace separated) → direct coordinates. */
|
||||
const COORD_RE = /^(-?\d+(?:\.\d*)?)(?:\s*[,;]\s*|\s+)(-?\d+(?:\.\d*)?)$/
|
||||
|
||||
function placeToPick(place: MapsPlace): PlSearchPick {
|
||||
const s = (v: unknown) => (v == null ? undefined : String(v))
|
||||
return {
|
||||
@@ -90,206 +64,31 @@ function placeToPick(place: MapsPlace): PlSearchPick {
|
||||
/**
|
||||
* Search row of the place form: Google/OSM text search biased on the trip
|
||||
* centre, autocomplete dropdown, plus Google-Maps-URL and "lat, lng" paste
|
||||
* detection — the mobile counterpart of PlaceFormModal's search block.
|
||||
* detection — the mobile counterpart of PlaceFormModal's search block, on the
|
||||
* same search logic (usePlaceSearch).
|
||||
*/
|
||||
export default function PlPlaceSearch({ planner, locationBias, onPick, onResolvingChange }: PlPlaceSearchProps) {
|
||||
const { t, toast } = planner
|
||||
// Place names in the language the user picked for them, the app's otherwise (#1799).
|
||||
const language = usePlaceLanguage()
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState<MapsPlace[]>([])
|
||||
const [suggestions, setSuggestions] = useState<Suggestion[]>([])
|
||||
const [searching, setSearching] = useState(false)
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
// One Google billing session per search (see utils/placesSession).
|
||||
const placesSessionRef = useRef(new PlacesSession())
|
||||
// What produced the list on screen, for the shadow log. Refs, because a pick
|
||||
// has to read the values that belonged to that list. Mirrors PlaceFormModal.
|
||||
const searchMetaRef = useRef<{ query: string; source: string } | null>(null)
|
||||
const acMetaRef = useRef<{ query: string; source: string } | null>(null)
|
||||
// The name the whole list carries, for rows that do not name their own index.
|
||||
const [acSource, setAcSource] = useState('')
|
||||
// What answered the last full search, for the line that offers Google instead.
|
||||
const [searchSource, setSearchSource] = useState('')
|
||||
const googleAnswers = useAuthStore(selectGoogleHoldsSlot)
|
||||
const { autocomplete, sourceLabel } = usePlaceSuggestions()
|
||||
|
||||
const setResolving = useCallback(
|
||||
(v: boolean) => {
|
||||
setSearching(v)
|
||||
onResolvingChange?.(v)
|
||||
},
|
||||
[onResolvingChange],
|
||||
)
|
||||
|
||||
const fetchSuggestions = useCallback(
|
||||
async (input: string) => {
|
||||
abortRef.current?.abort()
|
||||
const controller = new AbortController()
|
||||
abortRef.current = controller
|
||||
try {
|
||||
const result = await autocomplete(input, language, locationBias, controller.signal, placesSessionRef.current.current())
|
||||
acMetaRef.current = { query: input, source: result.source || 'unknown' }
|
||||
setAcSource(result.source || '')
|
||||
setSuggestions(result.suggestions || [])
|
||||
} catch (err: unknown) {
|
||||
// Superseded request — axios rejects an aborted call with CanceledError.
|
||||
if (err instanceof Error && err.name === 'CanceledError') return
|
||||
setSuggestions([])
|
||||
}
|
||||
},
|
||||
[autocomplete, language, locationBias],
|
||||
)
|
||||
|
||||
// Debounced autocomplete — URLs and coordinate pastes go to the search button.
|
||||
useEffect(() => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
const trimmed = query.trim()
|
||||
if (trimmed.length < 2 || isMapUrl(trimmed) || COORD_RE.test(trimmed)) {
|
||||
// A list still on its way belongs to a query that is gone.
|
||||
abortRef.current?.abort()
|
||||
setSuggestions([])
|
||||
return
|
||||
}
|
||||
debounceRef.current = setTimeout(() => fetchSuggestions(trimmed), 300)
|
||||
return () => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
}
|
||||
}, [query, fetchSuggestions])
|
||||
|
||||
/**
|
||||
* `pick` is present only when the place came out of a ranked list, so a
|
||||
* coordinate paste or a resolved Google URL contributes no row.
|
||||
*/
|
||||
const applyPlace = (place: MapsPlace, pick?: { mode: 'search' | 'autocomplete'; rank: number; count: number }) => {
|
||||
onPick(placeToPick(place))
|
||||
if (pick) {
|
||||
const meta = pick.mode === 'search' ? searchMetaRef.current : acMetaRef.current
|
||||
const lat = Number(place.lat)
|
||||
const lng = Number(place.lng)
|
||||
if (meta && Number.isFinite(lat) && Number.isFinite(lng)) {
|
||||
recordPlacePick({
|
||||
query: meta.query,
|
||||
lang: language,
|
||||
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: String(place.name ?? ''),
|
||||
pickedLat: lat,
|
||||
pickedLng: lng,
|
||||
pickedPlaceId: (place.google_place_id as string) || (place.amap_poi_id as string) || (place.osm_id as string) || null,
|
||||
})
|
||||
}
|
||||
}
|
||||
setResults([])
|
||||
setSuggestions([])
|
||||
setQuery('')
|
||||
}
|
||||
|
||||
const handleSearch = async (provider?: 'google') => {
|
||||
// The retry sends the query the list came from, as the desktop form does:
|
||||
// the list stays on screen while the field is edited or cleared.
|
||||
const trimmed = provider ? (searchMetaRef.current?.query ?? '') : query.trim()
|
||||
if (!trimmed) return
|
||||
setSuggestions([])
|
||||
|
||||
// "lat, lng" paste → straight to coordinates, no lookup needed.
|
||||
const coords = trimmed.match(COORD_RE)
|
||||
if (coords) {
|
||||
onPick({ lat: coords[1], lng: coords[2] })
|
||||
setQuery('')
|
||||
return
|
||||
}
|
||||
|
||||
setResolving(true)
|
||||
try {
|
||||
if (!provider && isMapUrl(trimmed)) {
|
||||
const resolved = await mapsApi.resolveUrl(trimmed)
|
||||
if (resolved.lat && resolved.lng) {
|
||||
onPick({
|
||||
name: resolved.name || undefined,
|
||||
address: resolved.address || undefined,
|
||||
lat: String(resolved.lat),
|
||||
lng: String(resolved.lng),
|
||||
google_ftid: resolved.google_ftid || undefined,
|
||||
})
|
||||
setQuery('')
|
||||
toast.success(t('places.urlResolved'))
|
||||
return
|
||||
}
|
||||
}
|
||||
// Derselbe Hinweis, den die Vervollstaendigung schon bekommt: die Suche
|
||||
// braucht ihn genauso, nur als Punkt statt als Kasten.
|
||||
const result = await mapsApi.search(trimmed, language, pointFromBox(locationBias), provider)
|
||||
searchMetaRef.current = { query: trimmed, source: result.source || 'unknown' }
|
||||
setResults(result.places || [])
|
||||
setSearchSource(result.source || '')
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
|
||||
} finally {
|
||||
setResolving(false)
|
||||
placesSessionRef.current.end()
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectSuggestion = async (suggestion: Suggestion) => {
|
||||
// Read before the list is cleared: this is the rank the user saw.
|
||||
const acPick = corePickRank(suggestions, suggestion)
|
||||
abortRef.current?.abort()
|
||||
setSuggestions([])
|
||||
const previousQuery = query
|
||||
setQuery('')
|
||||
onPick({ name: suggestion.mainText })
|
||||
setResolving(true)
|
||||
try {
|
||||
// Details are a fragile second hop (kill-switch, Overpass load) — fall
|
||||
// back to the text-search path so suggestions never dead-end. (#1192)
|
||||
let place: MapsPlace | null = suggestion.place ?? null
|
||||
if (!place) {
|
||||
try {
|
||||
// Spends the session the suggestions opened.
|
||||
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 {
|
||||
// fall through to text search
|
||||
}
|
||||
}
|
||||
if (!place && suggestion.source === 'openstreetmap' && suggestion.lat != null && suggestion.lng != null) {
|
||||
// The layer's second line is the local name, not an address, so joining
|
||||
// the two makes a query nobody typed — and its first answer would be
|
||||
// silently taken as the place the user picked. The row already knows
|
||||
// where it is.
|
||||
place = {
|
||||
name: suggestion.mainText,
|
||||
address: '',
|
||||
lat: suggestion.lat,
|
||||
lng: suggestion.lng,
|
||||
osm_id: suggestion.placeId,
|
||||
source: 'openstreetmap',
|
||||
}
|
||||
}
|
||||
if (!place) {
|
||||
const fullQuery = [suggestion.mainText, suggestion.secondaryText].filter(Boolean).join(', ')
|
||||
const search = await mapsApi.search(fullQuery, language, pointFromBox(locationBias))
|
||||
place = (search.places?.[0] as MapsPlace | undefined) ?? null
|
||||
}
|
||||
if (place) {
|
||||
applyPlace(place, acPick && { mode: 'autocomplete', ...acPick })
|
||||
} else {
|
||||
setQuery(previousQuery)
|
||||
toast.error(t('places.mapsSearchError'))
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
setQuery(previousQuery)
|
||||
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
|
||||
} finally {
|
||||
setResolving(false)
|
||||
placesSessionRef.current.end()
|
||||
}
|
||||
}
|
||||
const {
|
||||
query, setQuery, results, suggestions, setSuggestions, acSource, searchSource, searching, googleAnswers,
|
||||
sourceLabel, runSearch: handleSearch, pickPlace: applyPlace, selectSuggestion: handleSelectSuggestion,
|
||||
} = usePlaceSearch({
|
||||
variant: 'sheet',
|
||||
locationBias,
|
||||
t,
|
||||
toast,
|
||||
onPlace: place => onPick(placeToPick(place)),
|
||||
onSuggestionName: name => onPick({ name }),
|
||||
onMapLink: resolved => onPick({
|
||||
name: resolved.name || undefined,
|
||||
address: resolved.address || undefined,
|
||||
lat: String(resolved.lat),
|
||||
lng: String(resolved.lng),
|
||||
google_ftid: resolved.google_ftid || undefined,
|
||||
}),
|
||||
onCoordinates: (lat, lng) => onPick({ lat, lng }),
|
||||
onResolvingChange,
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useMemo } from 'react'
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import { Eyebrow } from './PlSheetChrome'
|
||||
import CustomTimePicker from '../../../../components/shared/CustomTimePicker'
|
||||
import { timeCollisions } from '../../../../components/Planner/PlaceFormModal.helpers'
|
||||
import type { Assignment } from '../../../../types'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
|
||||
@@ -33,23 +34,11 @@ export default function PlTimeFields({
|
||||
// The plan tab reads the day as Days does, and there End stays a plain label.
|
||||
const endIsLeave = planner.activeTab === 'roadtrip'
|
||||
|
||||
const collisions = useMemo(() => {
|
||||
if (!startTime || startTime.length < 5) return []
|
||||
const current = dayAssignments.find(a => a.id === assignmentId)
|
||||
if (!current) return []
|
||||
const myEnd = endTime && endTime.length >= 5 ? endTime : null
|
||||
return dayAssignments.filter(a => {
|
||||
if (a.id === assignmentId || a.day_id !== current.day_id) return false
|
||||
const otherStart = a.place?.place_time
|
||||
const otherEnd = a.place?.end_time
|
||||
if (!otherStart) return false
|
||||
const s1 = startTime
|
||||
const e1 = myEnd || startTime
|
||||
const s2 = otherStart
|
||||
const e2 = otherEnd || otherStart
|
||||
return s1 < (e2 || '23:59') && s2 < (e1 || '23:59') && s1 !== e2 && s2 !== e1
|
||||
})
|
||||
}, [assignmentId, dayAssignments, startTime, endTime])
|
||||
// The other visits of the same day whose times overlap this one's, as the desktop form warns.
|
||||
const collisions = useMemo(
|
||||
() => timeCollisions(assignmentId, dayAssignments, startTime, endTime),
|
||||
[assignmentId, dayAssignments, startTime, endTime],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="mt-3">
|
||||
|
||||
Reference in New Issue
Block a user