mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 07:30:04 +00:00
586 lines
28 KiB
TypeScript
586 lines
28 KiB
TypeScript
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
import { useNavigate, useParams, useSearchParams } from 'react-router'
|
|
import { useTranslation } from '../../i18n'
|
|
import { useElementSize } from '../../hooks/useElementSize'
|
|
import { useElementRect } from '../../hooks/useElementRect'
|
|
import { useSettingsStore } from '../../store/settingsStore'
|
|
import { useAuthStore } from '../../store/authStore'
|
|
import { useToast } from '../../components/shared/Toast'
|
|
import { collectionsApi } from '../../api/collections'
|
|
import { downloadCollectionFile, downloadCollectionGpx, type CollectionExportFormat } from '../../components/Collections/collectionFile'
|
|
import { getApiErrorMessage } from '../../types'
|
|
import { canAddToCollection, canRemoveFromCollection, collectionRoleOf } from '../../utils/collectionAccess'
|
|
import { addListener, removeListener } from '../../api/websocket'
|
|
import { useCollectionStore, ALL_SAVED } from '../../store/collectionStore'
|
|
import type { ActiveCollectionId } from '../../store/collectionStore'
|
|
import { categoriesApi } from '../../api/client'
|
|
import type { Collection, CollectionStatus, CollectionFile } from '@trek/shared'
|
|
import type { Category, Place } from '../../types'
|
|
import { filterPlaces, sortPlaces, statusCounts, mappablePlaces, presentCategories, presentLabels } from './collectionsModel'
|
|
import type { CollectionLabelUpdateRequest } from '@trek/shared'
|
|
|
|
/** Quiet time after the last collections:* event before the page reloads. */
|
|
const WS_RELOAD_SETTLE_MS = 400
|
|
|
|
/**
|
|
* Collections page logic — owns the page-local UI state (new/edit-list forms,
|
|
* mobile rail drawer), pulls the collection store, wires the WebSocket live sync
|
|
* (incl. collections:deleted clearing the active list) and keeps the route param
|
|
* (/collections/:id) in sync with the active list. CollectionsPage stays a pure
|
|
* wiring container around the rail + toolbar + view JSX.
|
|
*/
|
|
export function useCollections() {
|
|
const { t, language } = useTranslation()
|
|
const navigate = useNavigate()
|
|
const { id: routeId } = useParams<{ id: string }>()
|
|
const toast = useToast()
|
|
|
|
const dm = useSettingsStore(s => s.settings.dark_mode)
|
|
const dark = dm === true || dm === 'dark' || (dm === 'auto' && typeof window !== 'undefined' && window.matchMedia('(prefers-color-scheme: dark)').matches)
|
|
|
|
// Desktop breakpoint for the list+map split (list view only). Below it the
|
|
// list stays single-column and the map is its own view.
|
|
const [isWide, setIsWide] = useState(() => typeof window !== 'undefined' && window.matchMedia('(min-width: 1024px)').matches)
|
|
useEffect(() => {
|
|
const mq = window.matchMedia('(min-width: 1024px)')
|
|
const on = () => setIsWide(mq.matches)
|
|
mq.addEventListener('change', on)
|
|
return () => mq.removeEventListener('change', on)
|
|
}, [])
|
|
|
|
// Measure the hero so the list rail can be kept at least as tall as it.
|
|
const hero = useElementSize<HTMLDivElement>()
|
|
// Measure the split's list column so the place-detail sheet can dock over it.
|
|
const listCol = useElementRect<HTMLDivElement>()
|
|
|
|
const store = useCollectionStore()
|
|
const {
|
|
collections, activeId, places, members, labels, incomingInvites,
|
|
view, statusFilter, categoryFilter, ratingFilter, labelFilter, sortMode, search, selectedPlaceId, selectMode, selectedIds,
|
|
loading, placesLoading,
|
|
loadAll, setActive, refreshActive, loadCollection,
|
|
deleteCollection,
|
|
setStatus, updatePlace, uploadPlaceImage, ratePlace, deletePlace, deleteMany, copyToTrip, clearSelection,
|
|
moveToList, duplicateToList, setSelectedIds,
|
|
createLabel, updateLabel, deleteLabel, assignLabels,
|
|
acceptInvite, declineInvite,
|
|
setView, setStatusFilter, setCategoryFilter, setRatingFilter, setLabelFilter, setSortMode, setSearch, setSelectedPlaceId, setSelectMode, toggleSelect,
|
|
} = store
|
|
|
|
// ── Page-local UI state ─────────────────────────────────────────────
|
|
// The list editor modal: null = closed, 'new' = create, a Collection = edit it.
|
|
const [editorTarget, setEditorTarget] = useState<Collection | 'new' | null>(null)
|
|
const [confirmDeleteList, setConfirmDeleteList] = useState<number | null>(null)
|
|
const [mobileRailOpen, setMobileRailOpen] = useState(false)
|
|
const [showShare, setShowShare] = useState(false)
|
|
const [showAddPlace, setShowAddPlace] = useState(false)
|
|
const [showImport, setShowImport] = useState(false)
|
|
// Export / import as a file (#2198) — distinct from showImport above, which
|
|
// is the "pull places out of one of my trips" dialog.
|
|
const [exporting, setExporting] = useState(false)
|
|
const [showImportFile, setShowImportFile] = useState(false)
|
|
// The place ids the Copy-to-trip modal is open for (null = closed). Single
|
|
// place from the detail panel, or the select-mode set for a bulk copy.
|
|
const [copyIds, setCopyIds] = useState<number[] | null>(null)
|
|
|
|
// Initial load. listsLoaded says the rail is fresh from this visit, which
|
|
// the route check below waits for before it calls a list id unknown. A load
|
|
// that fails leaves it off, so an offline page never drops the route.
|
|
const [listsLoaded, setListsLoaded] = useState(false)
|
|
useEffect(() => { loadAll().then(() => setListsLoaded(true), () => setListsLoaded(false)) }, [])
|
|
|
|
// Central admin-defined categories, for assigning a category to a saved place.
|
|
const [categories, setCategories] = useState<Category[]>([])
|
|
useEffect(() => { categoriesApi.list().then((d: { categories: Category[] }) => setCategories(d.categories ?? [])).catch(() => {}) }, [])
|
|
|
|
// When the list↔map split toggles, its grid columns animate; keep nudging the
|
|
// mounted map to re-layout during the transition (Leaflet's trackResize hooks
|
|
// window resize; MapLibre observes its own box). Skip the initial mount — the
|
|
// map already sizes itself there, and nudging would fight its first fit.
|
|
const firstViewRun = useRef(true)
|
|
useEffect(() => {
|
|
if (firstViewRun.current) { firstViewRun.current = false; return }
|
|
if (!isWide) return
|
|
const start = performance.now()
|
|
let raf = 0
|
|
const tick = () => {
|
|
window.dispatchEvent(new Event('resize'))
|
|
if (performance.now() - start < 440) raf = requestAnimationFrame(tick)
|
|
}
|
|
raf = requestAnimationFrame(tick)
|
|
return () => cancelAnimationFrame(raf)
|
|
}, [view, isWide])
|
|
|
|
// The invite notification links to /collections/:id, a list the invitee
|
|
// cannot read before they accept (#2645). When the route is such an invite
|
|
// the page offers it instead of opening the list, and lists it first.
|
|
const routeInvite = useMemo(() => {
|
|
if (!routeId) return null
|
|
const id = Number(routeId)
|
|
return incomingInvites.find(inv => inv.collection_id === id) ?? null
|
|
}, [routeId, incomingInvites])
|
|
const orderedInvites = useMemo(
|
|
() => (routeInvite ? [routeInvite, ...incomingInvites.filter(inv => inv !== routeInvite)] : incomingInvites),
|
|
[routeInvite, incomingInvites],
|
|
)
|
|
|
|
// Keep the active list in sync with the URL (/collections/:id, or the
|
|
// "All saved" union at /collections). A pending invite on the route shows
|
|
// the union behind its card.
|
|
useEffect(() => {
|
|
const next: ActiveCollectionId = routeId && !routeInvite ? Number(routeId) : ALL_SAVED
|
|
if (Number.isNaN(next as number)) return
|
|
if (next !== activeId) setActive(next)
|
|
// Only re-run when the route, the loaded list set or the invite on it changes.
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [routeId, collections.length, routeInvite])
|
|
|
|
// A route id that is neither one of the lists nor a pending invite is a link
|
|
// to something gone: a declined or withdrawn invite, a deleted list, one the
|
|
// person was removed from. Drop it once the lists are in, rather than leave
|
|
// the URL on a list the page cannot show.
|
|
useEffect(() => {
|
|
if (!listsLoaded || loading || !routeId) return
|
|
const id = Number(routeId)
|
|
if (Number.isNaN(id)) return
|
|
if (collections.some(l => l.id === id) || incomingInvites.some(inv => inv.collection_id === id)) return
|
|
navigate('/collections', { replace: true })
|
|
}, [listsLoaded, loading, routeId, collections, incomingInvites, navigate])
|
|
|
|
// A link to one saved place (/collections/:id?place=<id>, the assistant's
|
|
// "Open in Collections") opens it once the list on the route holds it, and
|
|
// then drops the param, so a reload or the back button does not reopen it.
|
|
// A list that has loaded without the place (deleted or moved since) drops
|
|
// the param too, rather than leave the URL on a place the page cannot show.
|
|
const [searchParams, setSearchParams] = useSearchParams()
|
|
const linkedPlaceId = Number(searchParams.get('place'))
|
|
useEffect(() => {
|
|
if (!Number.isInteger(linkedPlaceId) || linkedPlaceId <= 0 || placesLoading) return
|
|
if (typeof activeId !== 'number' || String(activeId) !== routeId) return
|
|
const held = places.some(p => p.id === linkedPlaceId && p.collection_id === activeId)
|
|
if (!held && places.some(p => p.collection_id !== activeId)) return
|
|
if (held) setSelectedPlaceId(linkedPlaceId)
|
|
setSearchParams(prev => {
|
|
const next = new URLSearchParams(prev)
|
|
next.delete('place')
|
|
return next
|
|
}, { replace: true })
|
|
}, [linkedPlaceId, placesLoading, activeId, routeId, places, setSelectedPlaceId, setSearchParams])
|
|
|
|
// Live sync via WebSocket. collections:deleted / :removed must bounce a member
|
|
// off a list that was removed (or that they were kicked from) under them.
|
|
const wsReloadTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
|
const activeIdRef = useRef(activeId)
|
|
useEffect(() => { activeIdRef.current = activeId }, [activeId])
|
|
const handleWsMessage = useCallback((msg: { type: string; collectionId?: number }) => {
|
|
if (!msg.type?.startsWith('collections:')) return
|
|
if (msg.type === 'collections:deleted' || msg.type === 'collections:removed') {
|
|
if (msg.collectionId != null && activeId === msg.collectionId) {
|
|
navigate('/collections')
|
|
}
|
|
loadAll()
|
|
return
|
|
}
|
|
if (msg.type === 'collections:invite') {
|
|
toast.info(t('collections.invites.received'))
|
|
}
|
|
// invite / accepted / declined / cancelled / left / updated → refresh the
|
|
// rail, and refresh the active list WITHOUT clearing the current selection or
|
|
// select-mode (setActive would reset selectedPlaceId → close the open detail).
|
|
// An agent saving places one by one over MCP sends one event per place, so
|
|
// the reload waits until they stop instead of re-reading every list per event
|
|
// (#2559), and then reads whatever list is open by that time.
|
|
if (wsReloadTimer.current !== null) clearTimeout(wsReloadTimer.current)
|
|
wsReloadTimer.current = setTimeout(() => {
|
|
wsReloadTimer.current = null
|
|
loadAll()
|
|
const current = activeIdRef.current
|
|
if (typeof current === 'number') loadCollection(current)
|
|
else if (current === ALL_SAVED) refreshActive()
|
|
}, WS_RELOAD_SETTLE_MS)
|
|
}, [activeId])
|
|
|
|
useEffect(() => {
|
|
addListener(handleWsMessage)
|
|
return () => removeListener(handleWsMessage)
|
|
}, [handleWsMessage])
|
|
useEffect(() => () => {
|
|
if (wsReloadTimer.current !== null) clearTimeout(wsReloadTimer.current)
|
|
}, [])
|
|
|
|
// ── Derived ─────────────────────────────────────────────────────────
|
|
const activeCollection = useMemo(
|
|
() => (typeof activeId === 'number' ? collections.find(c => c.id === activeId) ?? null : null),
|
|
[collections, activeId],
|
|
)
|
|
const isAllSaved = activeId === ALL_SAVED
|
|
const isOwner = activeCollection?.is_owner ?? false
|
|
|
|
// The current user's permission on the active list drives what the UI offers.
|
|
// "All saved" spans many lists (each enforced per-place on the server), so it
|
|
// stays permissive on the client; a viewer of a shared list loses add/edit/delete.
|
|
const currentUserId = useAuthStore(s => s.user?.id)
|
|
const myRole = useMemo(() => collectionRoleOf(isOwner, members, currentUserId), [isOwner, members, currentUserId])
|
|
const canEdit = isAllSaved || myRole === 'owner' || myRole === 'admin' || myRole === 'editor'
|
|
const canDelete = isAllSaved || canRemoveFromCollection(myRole)
|
|
|
|
// Sharing is offered on any real (non "All saved") list the user can see. The
|
|
// badge counts everyone but the owner — accepted collaborators + pending invites.
|
|
const canShare = typeof activeId === 'number' && activeCollection != null
|
|
const shareMemberCount = useMemo(() => members.filter(m => !m.is_owner).length, [members])
|
|
|
|
// Close the share modal if the active list changes out from under it.
|
|
useEffect(() => { setShowShare(false) }, [activeId])
|
|
|
|
const ownedLists = useMemo(() => collections.filter(c => c.is_owner !== false), [collections])
|
|
/**
|
|
* Lists a file may be added to: the person's own, plus a shared one where
|
|
* they are an editor or an admin. Same rule the server applies on the way in,
|
|
* so the import dialog never offers a list the import would refuse.
|
|
*/
|
|
const writableLists = useMemo(
|
|
() => collections.filter(c => canAddToCollection(c, currentUserId)),
|
|
[collections, currentUserId],
|
|
)
|
|
const sharedLists = useMemo(() => collections.filter(c => c.is_owner === false), [collections])
|
|
|
|
// Labels are per-collection, so never apply them on the "All saved" union.
|
|
const visiblePlaces = useMemo(
|
|
() => sortPlaces(filterPlaces(places, statusFilter, search, categoryFilter, isAllSaved ? [] : labelFilter, ratingFilter), sortMode),
|
|
[places, statusFilter, search, categoryFilter, isAllSaved, labelFilter, ratingFilter, sortMode],
|
|
)
|
|
// Categories actually present in this list, for the category filter dropdown.
|
|
const categoryOptions = useMemo(() => presentCategories(places), [places])
|
|
// The active list's labels (with per-label counts) for the filter + manager.
|
|
const labelOptions = useMemo(() => presentLabels(labels, places), [labels, places])
|
|
// Stable reference so the map doesn't tear down + rebuild every marker on each
|
|
// unrelated re-render (which would swallow marker clicks mid-rebuild).
|
|
const mappable = useMemo(() => mappablePlaces(visiblePlaces), [visiblePlaces])
|
|
// Whether this list has anything mappable AT ALL, filters aside. The layout
|
|
// hangs off this rather than off `mappable`: a label with no places left the
|
|
// filtered set empty, which tore the map out and reflowed the page to full
|
|
// width. The filter should empty the map, not remove it.
|
|
const hasMappable = useMemo(() => mappablePlaces(places).length > 0, [places])
|
|
const counts = useMemo(() => statusCounts(places), [places])
|
|
|
|
// ── Handlers ────────────────────────────────────────────────────────
|
|
const handleSelectList = useCallback((id: ActiveCollectionId) => {
|
|
setMobileRailOpen(false)
|
|
navigate(id === ALL_SAVED || id === null ? '/collections' : `/collections/${id}`)
|
|
}, [navigate])
|
|
|
|
// The editor modal owns its own form + create/update/upload calls; the hook
|
|
// just opens it and navigates to a freshly created list.
|
|
const handleEditorCreated = useCallback((id: number) => {
|
|
navigate(`/collections/${id}`)
|
|
}, [navigate])
|
|
|
|
const handlePlaceAdded = useCallback(() => { refreshActive() }, [refreshActive])
|
|
|
|
/**
|
|
* Download the active list as a file, in the format picked from the menu.
|
|
*
|
|
* The file is fetched rather than built from what this page holds: the page
|
|
* has the places for display, the server decides what may leave the instance.
|
|
* A GPX holds only places with coordinates, so the rest are counted and the
|
|
* count is said; a list with none at all gets no empty file (#2301).
|
|
*/
|
|
const handleExportList = useCallback(async (format: CollectionExportFormat = 'trek') => {
|
|
if (typeof activeId !== 'number') return
|
|
setExporting(true)
|
|
try {
|
|
if (format === 'trek') {
|
|
downloadCollectionFile(await collectionsApi.exportFile(activeId))
|
|
return
|
|
}
|
|
const result = await collectionsApi.exportGpx(activeId)
|
|
if (result.waypoints === 0) {
|
|
toast.warning(t('collections.file.gpxNothing'))
|
|
return
|
|
}
|
|
downloadCollectionGpx(result.name, result.gpx)
|
|
if (result.omitted > 0) toast.info(t('collections.file.gpxOmitted', { count: result.omitted }))
|
|
} catch (err) {
|
|
toast.error(getApiErrorMessage(err, t('common.error')))
|
|
} finally {
|
|
setExporting(false)
|
|
}
|
|
}, [activeId, toast, t])
|
|
|
|
/** A GPX read into a list file for the import dialog to show. The server does the parsing. */
|
|
const handleReadGpx = useCallback(
|
|
(gpx: string, fileName: string) => collectionsApi.readGpx({ gpx, file_name: fileName }),
|
|
[],
|
|
)
|
|
|
|
/**
|
|
* Read a chosen file and create the list it describes.
|
|
*
|
|
* Lands on the new list, because that is the thing the person was after and
|
|
* an import that leaves you where you were reads as one that did nothing.
|
|
*/
|
|
const handleImportFile = useCallback(async (file: CollectionFile, name?: string) => {
|
|
const result = await collectionsApi.importFile({ file, name })
|
|
await loadAll()
|
|
const created = result.collection as Collection
|
|
navigate(`/collections/${created.id}`)
|
|
if (result.skipped > 0) {
|
|
toast.info(t('collections.file.doneSkipped', { count: result.imported, skipped: result.skipped }))
|
|
} else {
|
|
toast.success(t('collections.file.done', { count: result.imported }))
|
|
}
|
|
setShowImportFile(false)
|
|
}, [loadAll, navigate, toast, t])
|
|
|
|
/**
|
|
* Read a chosen file into a list that is already there.
|
|
*
|
|
* Lands on that list, for the same reason a new one does. Nothing in it is
|
|
* overwritten: the server counts the places it already had and leaves them,
|
|
* and the toast says so rather than letting a file quietly do less than it
|
|
* looked like it would.
|
|
*/
|
|
const handleImportFileInto = useCallback(async (file: CollectionFile, collectionId: number) => {
|
|
const result = await collectionsApi.importFileInto(collectionId, { file })
|
|
const name = (result.collection as Collection).name
|
|
const duplicates = result.duplicates ?? 0
|
|
await loadAll()
|
|
if (activeId === collectionId) refreshActive()
|
|
else navigate(`/collections/${collectionId}`)
|
|
if (result.imported === 0 && duplicates > 0) {
|
|
toast.info(t('collections.file.doneIntoNothing', { name }))
|
|
} else if (duplicates > 0) {
|
|
toast.success(t('collections.file.doneIntoDuplicates', { count: result.imported, duplicates, name }))
|
|
} else if (result.skipped > 0) {
|
|
toast.info(t('collections.file.doneSkipped', { count: result.imported, skipped: result.skipped }))
|
|
} else {
|
|
toast.success(t('collections.file.doneInto', { count: result.imported, name }))
|
|
}
|
|
setShowImportFile(false)
|
|
}, [activeId, loadAll, refreshActive, navigate, toast, t])
|
|
|
|
const handleDeleteList = useCallback(async () => {
|
|
if (confirmDeleteList == null) return
|
|
const id = confirmDeleteList
|
|
setConfirmDeleteList(null)
|
|
try {
|
|
await deleteCollection(id)
|
|
if (activeId === id) navigate('/collections')
|
|
} catch (err) {
|
|
toast.error(getApiErrorMessage(err, t('common.error')))
|
|
}
|
|
}, [confirmDeleteList, deleteCollection, activeId, navigate, toast, t])
|
|
|
|
const handleStatusChange = useCallback(async (placeId: number, status: CollectionStatus) => {
|
|
try {
|
|
await setStatus(placeId, status)
|
|
} catch (err) {
|
|
toast.error(getApiErrorMessage(err, t('common.error')))
|
|
}
|
|
}, [setStatus, toast, t])
|
|
|
|
const handleDeletePlace = useCallback(async (placeId: number) => {
|
|
try {
|
|
await deletePlace(placeId)
|
|
} catch (err) {
|
|
toast.error(getApiErrorMessage(err, t('common.error')))
|
|
}
|
|
}, [deletePlace, toast, t])
|
|
|
|
const handleRatePlace = useCallback(async (placeId: number, rating: number | null) => {
|
|
try {
|
|
await ratePlace(placeId, rating)
|
|
} catch (err) {
|
|
toast.error(getApiErrorMessage(err, t('common.error')))
|
|
}
|
|
}, [ratePlace, toast, t])
|
|
|
|
const handleDeleteSelected = useCallback(async () => {
|
|
if (selectedIds.length === 0) return
|
|
try {
|
|
await deleteMany(selectedIds)
|
|
} catch (err) {
|
|
toast.error(getApiErrorMessage(err, t('common.error')))
|
|
}
|
|
}, [selectedIds, deleteMany, toast, t])
|
|
|
|
// Select-all toggles between every visible place and none.
|
|
const allVisibleSelected = visiblePlaces.length > 0 && visiblePlaces.every(p => selectedIds.includes(p.id))
|
|
const handleSelectAll = useCallback(() => {
|
|
setSelectedIds(allVisibleSelected ? [] : visiblePlaces.map(p => p.id))
|
|
}, [allVisibleSelected, visiblePlaces, setSelectedIds])
|
|
|
|
// Move / duplicate the selection into another list (a list-picker modal).
|
|
const [listPickerMode, setListPickerMode] = useState<'move' | 'copy' | null>(null)
|
|
const handleMoveToList = useCallback(async (targetId: number) => {
|
|
if (selectedIds.length === 0) return
|
|
try {
|
|
await moveToList(selectedIds, targetId)
|
|
toast.success(t('collections.movedCount', { count: selectedIds.length }))
|
|
setListPickerMode(null)
|
|
} catch (err) {
|
|
toast.error(getApiErrorMessage(err, t('common.error')))
|
|
}
|
|
}, [selectedIds, moveToList, toast, t])
|
|
const handleDuplicateToList = useCallback(async (targetId: number) => {
|
|
if (selectedIds.length === 0) return
|
|
try {
|
|
await duplicateToList(selectedIds, targetId)
|
|
toast.success(t('collections.duplicatedCount', { count: selectedIds.length }))
|
|
setListPickerMode(null)
|
|
} catch (err) {
|
|
toast.error(getApiErrorMessage(err, t('common.error')))
|
|
}
|
|
}, [selectedIds, duplicateToList, toast, t])
|
|
|
|
// ── Labels ──────────────────────────────────────────────────────────
|
|
const [showLabelManager, setShowLabelManager] = useState(false)
|
|
const [labelPickerOpen, setLabelPickerOpen] = useState(false)
|
|
|
|
const handleCreateLabel = useCallback(async (name: string, color?: string) => {
|
|
try { await createLabel(name, color) }
|
|
catch (err) { toast.error(getApiErrorMessage(err, t('common.error'))) }
|
|
}, [createLabel, toast, t])
|
|
|
|
const handleUpdateLabel = useCallback(async (labelId: number, body: CollectionLabelUpdateRequest) => {
|
|
try { await updateLabel(labelId, body) }
|
|
catch (err) { toast.error(getApiErrorMessage(err, t('common.error'))) }
|
|
}, [updateLabel, toast, t])
|
|
|
|
const handleDeleteLabel = useCallback(async (labelId: number) => {
|
|
try { await deleteLabel(labelId) }
|
|
catch (err) { toast.error(getApiErrorMessage(err, t('common.error'))) }
|
|
}, [deleteLabel, toast, t])
|
|
|
|
// Bulk-assign one or more labels to the current selection.
|
|
const handleBulkAssignLabels = useCallback(async (labelIds: number[]) => {
|
|
if (selectedIds.length === 0 || labelIds.length === 0) return
|
|
try {
|
|
await assignLabels(labelIds, selectedIds)
|
|
toast.success(t('collections.labels.assignedCount', { count: selectedIds.length }))
|
|
setLabelPickerOpen(false)
|
|
} catch (err) {
|
|
toast.error(getApiErrorMessage(err, t('common.error')))
|
|
}
|
|
}, [assignLabels, selectedIds, toast, t])
|
|
|
|
// Replace a single place's labels (from the detail sheet chips).
|
|
const handleAssignPlaceLabels = useCallback(async (placeId: number, labelIds: number[]) => {
|
|
try { await updatePlace(placeId, { label_ids: labelIds }) }
|
|
catch (err) { toast.error(getApiErrorMessage(err, t('common.error'))) }
|
|
}, [updatePlace, toast, t])
|
|
|
|
const handleAcceptInvite = useCallback(async (collectionId: number) => {
|
|
try {
|
|
await acceptInvite(collectionId)
|
|
navigate(`/collections/${collectionId}`)
|
|
} catch (err) {
|
|
toast.error(getApiErrorMessage(err, t('common.error')))
|
|
}
|
|
}, [acceptInvite, navigate, toast, t])
|
|
|
|
const handleDeclineInvite = useCallback(async (collectionId: number) => {
|
|
try {
|
|
await declineInvite(collectionId)
|
|
} catch (err) {
|
|
toast.error(getApiErrorMessage(err, t('common.error')))
|
|
}
|
|
}, [declineInvite, toast, t])
|
|
|
|
// Member left the active shared list — the store already cleared it; bounce to
|
|
// the rail and close the share modal. Errors are surfaced inside the modal.
|
|
const handleAfterLeave = useCallback(() => {
|
|
setShowShare(false)
|
|
navigate('/collections')
|
|
}, [navigate])
|
|
|
|
// ── Detail panel (re-pointed PlaceInspector in collection mode) ──────
|
|
const selectedPlace = useMemo(
|
|
() => places.find(p => p.id === selectedPlaceId) ?? null,
|
|
[places, selectedPlaceId],
|
|
)
|
|
|
|
// PlaceInspector expects a trip Place; the collection place lacks trip_id, so
|
|
// shim it (collection mode guards every trip-only sub-panel anyway).
|
|
const detailPlace = useMemo<Place | null>(
|
|
() => (selectedPlace ? ({ ...selectedPlace, trip_id: selectedPlace.source_trip_id ?? 0 } as unknown as Place) : null),
|
|
[selectedPlace],
|
|
)
|
|
|
|
// A single-entry categories array so the inspector header can show the chip.
|
|
const detailCategories = useMemo<Category[]>(
|
|
() => (selectedPlace?.category ? ([selectedPlace.category] as unknown as Category[]) : []),
|
|
[selectedPlace],
|
|
)
|
|
|
|
const handleCloseDetail = useCallback(() => setSelectedPlaceId(null), [setSelectedPlaceId])
|
|
|
|
const handleDetailStatus = useCallback((status: CollectionStatus) => {
|
|
if (selectedPlaceId != null) handleStatusChange(selectedPlaceId, status)
|
|
}, [selectedPlaceId, handleStatusChange])
|
|
|
|
const handleDetailRemove = useCallback(async () => {
|
|
if (selectedPlaceId == null) return
|
|
await handleDeletePlace(selectedPlaceId)
|
|
setSelectedPlaceId(null)
|
|
}, [selectedPlaceId, handleDeletePlace, setSelectedPlaceId])
|
|
|
|
// ── Copy to trip ────────────────────────────────────────────────────
|
|
const openCopyForSelectedPlace = useCallback(() => {
|
|
if (selectedPlaceId != null) setCopyIds([selectedPlaceId])
|
|
}, [selectedPlaceId])
|
|
|
|
const openCopyForSelection = useCallback(() => {
|
|
if (selectedIds.length > 0) setCopyIds([...selectedIds])
|
|
}, [selectedIds])
|
|
|
|
const closeCopy = useCallback(() => setCopyIds(null), [])
|
|
|
|
const handleCopyToTrip = useCallback(async (tripId: number) => {
|
|
const ids = copyIds ?? []
|
|
const res = await copyToTrip(tripId, ids)
|
|
if (selectMode) clearSelection()
|
|
return res
|
|
}, [copyIds, copyToTrip, selectMode, clearSelection])
|
|
|
|
return {
|
|
t, language, dark, navigate,
|
|
isWide, heroRef: hero.ref, heroHeight: hero.height,
|
|
listColRef: listCol.ref, listColRect: listCol.rect, categories,
|
|
// store data
|
|
collections, ownedLists, sharedLists, activeCollection, isAllSaved, isOwner,
|
|
myRole, canEdit, canDelete,
|
|
canShare, shareMemberCount,
|
|
activeId, places, visiblePlaces, mappable, hasMappable, members, incomingInvites, routeInvite, orderedInvites, counts,
|
|
view, statusFilter, categoryFilter, categoryOptions, ratingFilter, sortMode, search, selectedPlaceId, selectMode, selectedIds,
|
|
labels, labelFilter, labelOptions,
|
|
loading, placesLoading,
|
|
// store setters
|
|
setView, setStatusFilter, setCategoryFilter, setRatingFilter, setLabelFilter, setSortMode, setSearch, setSelectedPlaceId, setSelectMode, toggleSelect,
|
|
updatePlace, uploadPlaceImage,
|
|
// labels
|
|
showLabelManager, setShowLabelManager, labelPickerOpen, setLabelPickerOpen,
|
|
handleCreateLabel, handleUpdateLabel, handleDeleteLabel, handleBulkAssignLabels, handleAssignPlaceLabels,
|
|
// local UI state
|
|
editorTarget, setEditorTarget, handleEditorCreated,
|
|
showAddPlace, setShowAddPlace, handlePlaceAdded,
|
|
showImport, setShowImport,
|
|
exporting, handleExportList,
|
|
showImportFile, setShowImportFile, handleImportFile, handleImportFileInto, handleReadGpx,
|
|
writableLists,
|
|
confirmDeleteList, setConfirmDeleteList,
|
|
mobileRailOpen, setMobileRailOpen,
|
|
showShare, setShowShare, handleAfterLeave,
|
|
// detail panel + copy-to-trip
|
|
selectedPlace, detailPlace, detailCategories, handleCloseDetail,
|
|
handleDetailStatus, handleDetailRemove,
|
|
copyIds, openCopyForSelectedPlace, openCopyForSelection, closeCopy, handleCopyToTrip,
|
|
// handlers
|
|
handleSelectList, handleDeleteList,
|
|
handleStatusChange, handleRatePlace, handleDeletePlace, handleDeleteSelected,
|
|
handleAcceptInvite, handleDeclineInvite,
|
|
allVisibleSelected, handleSelectAll,
|
|
listPickerMode, setListPickerMode, handleMoveToList, handleDuplicateToList,
|
|
}
|
|
}
|