refactor(collections): share the add place to list logic between desktop and phone

useAddPlaceToCollection holds the maps search, the pick and the save
that AddPlaceToCollectionModal and MCollAddSheet each carried, with the
pure helpers in addPlaceModel.

The differences stay as variants. The desktop resets and stays open
after an add, sends links and typed coordinates and shows the error's
own text. The phone closes, takes coordinates only from the picked hit,
ignores a second search or save while one is running and shows the
fallback text.
This commit is contained in:
Maurice
2026-10-08 21:09:18 +00:00
parent bbe3da7722
commit b2fd0ae5aa
6 changed files with 791 additions and 213 deletions
@@ -1,22 +1,12 @@
import { useEffect, useState } from 'react'
import { Check, Loader2, MapPin, Search, X } from 'lucide-react'
import type { CollectionStatus } from '@trek/shared'
import type { Category, TranslationFn } from '../../../types'
import { mapsApi } from '../../../api/client'
import { collectionsApi } from '../../../api/collections'
import { useTranslation } from '../../../i18n'
import { useToast } from '../../../components/shared/Toast'
import { getApiErrorMessage } from '../../../utils/apiError'
import { STATUS_ORDER } from '../../../pages/collections/collectionsModel'
import MSheet from '../../components/MSheet'
import MCollCategoryPicker from './MCollCategoryPicker'
import { STATUS_SPEC } from './collectionsMobileModel'
import { CancelPill, Eyebrow, INPUT_CLS, PrimaryPill, SheetFooter, SheetHeader, TEXTAREA_CLS } from './MCollSheetKit'
import { usePlaceLanguage } from '../../../hooks/usePlaceLanguage'
type MapsPlace = Record<string, unknown>
const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)
const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : typeof v === 'string' && v !== '' ? Number(v) : undefined)
import { str } from '../../../components/Collections/addPlaceModel'
import { useAddPlaceToCollection } from '../../../components/Collections/useAddPlaceToCollection'
interface MCollAddSheetProps {
open: boolean
@@ -36,91 +26,10 @@ interface MCollAddSheetProps {
* reported by the server and surfaced as a toast).
*/
export default function MCollAddSheet({ open, collectionId, collectionName, lists, categories, onClose, onAdded, t }: MCollAddSheetProps) {
const { language } = useTranslation()
const placeLang = usePlaceLanguage()
const toast = useToast()
const [query, setQuery] = useState('')
const [results, setResults] = useState<MapsPlace[]>([])
const [searching, setSearching] = useState(false)
const [picked, setPicked] = useState<MapsPlace | null>(null)
const [name, setName] = useState('')
const [address, setAddress] = useState('')
const [categoryId, setCategoryId] = useState<number | null>(null)
const [status, setStatus] = useState<CollectionStatus>('idea')
const [description, setDescription] = useState('')
const [saving, setSaving] = useState(false)
const [targetId, setTargetId] = useState<number | null>(collectionId)
useEffect(() => {
if (open) return
setQuery(''); setResults([]); setPicked(null); setName(''); setAddress(''); setCategoryId(null); setStatus('idea'); setDescription('')
setTargetId(null)
}, [open])
// Opened from a specific list → target is fixed; from "All Saved" (no active
// list) → default to the sole list if there is one, else pick it in-sheet.
// The lists may still be loading when the sheet opens, so the default is
// applied again once they arrive — without overruling a pick already made.
useEffect(() => {
if (!open) return
if (collectionId != null) { setTargetId(collectionId); return }
setTargetId(prev => (prev != null && lists.some(l => l.id === prev) ? prev : (lists.length === 1 ? lists[0].id : null)))
}, [open, collectionId, lists])
const search = async () => {
if (!query.trim() || searching) return
setSearching(true)
try {
const res = await mapsApi.search(query, placeLang)
setResults((res.places as MapsPlace[]) || [])
} catch (err) {
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
} finally {
setSearching(false)
}
}
const pick = (r: MapsPlace) => {
setPicked(r)
setName(str(r.name) ?? '')
setAddress(str(r.address) ?? '')
setResults([])
setQuery(str(r.name) ?? query)
}
const save = async () => {
const cleanName = name.trim()
if (!cleanName || targetId == null || saving) return
setSaving(true)
try {
const res = await collectionsApi.savePlace({
collection_id: targetId,
name: cleanName,
address: address.trim() || null,
lat: (picked && num(picked.lat)) ?? null,
lng: (picked && num(picked.lng)) ?? null,
google_place_id: (picked && str(picked.google_place_id)) ?? null,
google_ftid: (picked && str(picked.google_ftid)) ?? null,
osm_id: (picked && str(picked.osm_id)) ?? null,
website: (picked && str(picked.website)) ?? null,
phone: (picked && str(picked.phone)) ?? null,
category_id: categoryId,
description: description.trim() || null,
status,
force: true,
})
if (res.duplicate) toast.info(t('collections.duplicateWarning'))
else {
toast.success(t('collections.addedToList', { name: lists.find(l => l.id === targetId)?.name ?? collectionName }))
onAdded()
}
onClose()
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
} finally {
setSaving(false)
}
}
const {
query, setQuery, results, setResults, searching, name, setName, address, setAddress, categoryId, setCategoryId,
status, setStatus, description, setDescription, saving, targetId, setTargetId, search, pick, save,
} = useAddPlaceToCollection({ variant: 'sheet', open, collectionId, collectionName, lists, t, onClose, onAdded })
return (
<MSheet open={open} onClose={onClose} material="opaque" ariaLabel={t('collections.addPlace')}>