feat(collections): own order, KML/KMZ import, copy options, position search, place names on the trip map

- A list keeps its own order: drag a place by its grip (desktop and phone) or
  move it with the arrow keys. Reordering is off while a search or filter hides
  places and the list says why. New PUT /collections/:id/places/reorder and the
  MCP tool reorder_collection_places; new places go to the end. Client and
  server now order ties the same way (sort_order, oldest first, id).
- Copying saved places into a trip no longer takes their notes and tags along
  unasked. The picker offers both; a tag taken along becomes a trip tag (a trip
  tag of the same name is reused), never someone's personal tag.
- The source trip and place a saved place names are only kept when the user can
  open that trip and the place belongs to it.
- A KML or KMZ map can be read into a list: the dialog lists every placemark to
  keep or leave out and says which entries were skipped and why
  (POST /collections/map/read writes nothing; the import does).
- A saved place without coordinates says so and can be looked up on the map
  from its edit form, on the phone too, where a missing position could not be
  added at all. A typed address without a pick says it will not be on the map.
- The trip map can show the place names beside the pins (desktop and phone,
  both renderers). Names that would cover another pin or a control give way,
  the selected place and the planned stops first.
This commit is contained in:
Maurice
2026-11-29 14:57:00 +01:00
parent 177a0febe2
commit 82165855c7
148 changed files with 4219 additions and 321 deletions
@@ -1,4 +1,4 @@
// FE-COMP-ADDPLACECOL-001 to FE-COMP-ADDPLACECOL-028
// FE-COMP-ADDPLACECOL-001 to FE-COMP-ADDPLACECOL-029
import React from 'react'
import type { Mock } from 'vitest'
import { http, HttpResponse } from 'msw'
@@ -424,4 +424,15 @@ describe('AddPlaceToCollectionModal', () => {
await waitFor(() => expect(addToast).toHaveBeenCalledWith('List is full', 'error', undefined))
expect(nameField).toHaveFocus()
})
it('FE-COMP-ADDPLACECOL-029: a typed address without coordinates says the place will not be on the map (#2837)', () => {
setup()
const hint = /will not show on the map/
expect(screen.queryByText(hint)).toBeNull()
fireEvent.change(screen.getByPlaceholderText('Street, City, Country'), { target: { value: 'Shibuya, Tokyo' } })
expect(screen.getByText(hint)).toBeInTheDocument()
fireEvent.change(screen.getByPlaceholderText('Latitude (e.g. 48.8566)'), { target: { value: '35.66' } })
fireEvent.change(screen.getByPlaceholderText('Longitude (e.g. 2.3522)'), { target: { value: '0' } })
expect(screen.queryByText(hint)).toBeNull()
})
})
@@ -4,8 +4,7 @@ import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
import { Bookmark, Search, MapPin, MapPinned, Loader2, Trash2, Check, X } from 'lucide-react'
import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { AddRowButton, EditorField, GRID_2, INPUT, PANEL, Segmented, TEXTAREA } from '../shared/dialogParts'
import { NumericInput } from '../shared/NumericInput'
import { AddRowButton, EditorField, INPUT, Segmented, TEXTAREA } from '../shared/dialogParts'
import NoteFormatToolbar from '../shared/NoteFormatToolbar'
import { Tooltip } from '../shared/Tooltip'
import { getCategoryIcon } from '../shared/categoryIcons'
@@ -14,6 +13,7 @@ import type { Category, TranslationFn } from '../../types'
import type { CollectionStatus } from '@trek/shared'
import { str } from './addPlaceModel'
import { useAddPlaceToCollection } from './useAddPlaceToCollection'
import { PlaceFormLocation } from '../Planner/PlaceFormLocation'
/**
* The search row, pinned to the top of the scrolling body. The dialog stays open
@@ -50,7 +50,7 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
const {
query, setQuery, results, searching, noResults, setNoResults, dismissResults, name, setName, address, setAddress,
lat, setLat, lng, setLng, categoryId, setCategoryId, description, setDescription, links, setLinks, setLink,
status, setStatus, saving, search, pick, coordPaste, save,
status, setStatus, saving, search, pick, save,
} = useAddPlaceToCollection({
variant: 'dialog', open: isOpen, collectionId, collectionName, t, onClose, onAdded, normalizeLinkUrl,
// The dialog stays open for the next place, so hand the caret back to the
@@ -159,26 +159,12 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
{/* Where it is: filled in by a picked result, but also typeable, so a place
can be added by GPS alone (#1435). */}
<div className={PANEL}>
<EditorField label={t('places.formAddress')} htmlFor={`${fieldId}-address`}>
<input
id={`${fieldId}-address`}
type="text"
value={address}
onChange={e => setAddress(e.target.value)}
placeholder={t('places.formAddressPlaceholder')}
className={INPUT}
/>
</EditorField>
<div role="group" aria-label={t('collections.coordinates')} className={GRID_2}>
<EditorField label={t('places.formLatLabel')} htmlFor={`${fieldId}-lat`}>
<NumericInput id={`${fieldId}-lat`} mode="signed" value={lat} onValueChange={setLat} onPaste={coordPaste} placeholder={t('places.formLat')} className={INPUT} />
</EditorField>
<EditorField label={t('places.formLngLabel')} htmlFor={`${fieldId}-lng`}>
<NumericInput id={`${fieldId}-lng`} mode="signed" value={lng} onValueChange={setLng} onPaste={coordPaste} placeholder={t('places.formLng')} className={INPUT} />
</EditorField>
</div>
</div>
<PlaceFormLocation
fieldId={fieldId}
form={{ address, lat, lng }}
onChange={(field, value) => ({ address: setAddress, lat: setLat, lng: setLng })[field](value)}
warnWithoutCoordinates
/>
<EditorField label={t('mobileCollections.status')}>
<Segmented<CollectionStatus>
@@ -1,10 +1,11 @@
import React, { useEffect, useMemo, useRef } from 'react'
import { Check, MapPin } from 'lucide-react'
import { Check, GripVertical, Info, MapPin } from 'lucide-react'
import type { CollectionPlace, CollectionStatus, CollectionLabel } from '@trek/shared'
import type { TranslationFn } from '../../types'
import PlaceAvatar from '../shared/PlaceAvatar'
import StatusBadge from './StatusBadge'
import CollectionPlaceTags from './CollectionPlaceTags'
import { usePlaceReorder } from './usePlaceReorder'
interface CollectionListProps {
places: CollectionPlace[]
@@ -15,6 +16,11 @@ interface CollectionListProps {
onOpenPlace: (id: number) => void
onStatusChange?: (placeId: number, status: CollectionStatus) => void
onToggleSelect: (id: number) => void
/** The list's own order may be dragged right now (#1457). */
reorderEnabled?: boolean
/** It could be, but a search or filter hides places, so the list says why not. */
reorderBlocked?: boolean
onReorder?: (orderedIds: number[]) => void
t: TranslationFn
}
@@ -24,7 +30,8 @@ interface CollectionListProps {
* open the place (or toggle it in select mode).
*/
export default function CollectionList({
places, labels, selectedPlaceId, selectMode, selectedIds, onOpenPlace, onStatusChange, onToggleSelect, t,
places, labels, selectedPlaceId, selectMode, selectedIds, onOpenPlace, onStatusChange, onToggleSelect,
reorderEnabled = false, reorderBlocked = false, onReorder, t,
}: CollectionListProps): React.ReactElement {
const labelsById = useMemo(() => new Map(labels.map(l => [l.id, l])), [labels])
// Bring the selected row into view — e.g. when it was picked from the map.
@@ -33,8 +40,14 @@ export default function CollectionList({
selectedRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
}, [selectedPlaceId])
const order = useMemo(() => places.map(p => p.id), [places])
const reorder = usePlaceReorder(order, reorderEnabled && !!onReorder, ids => onReorder?.(ids))
return (
<div className="col-listview">
{reorderBlocked && (
<p className="col-reorder-note"><Info size={13} /> {t('collections.reorderBlocked')}</p>
)}
{places.map(place => {
const selected = selectedIds.includes(place.id)
const active = selectedPlaceId === place.id
@@ -51,8 +64,21 @@ export default function CollectionList({
tabIndex={0}
onClick={() => (selectMode ? onToggleSelect(place.id) : onOpenPlace(place.id))}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); if (selectMode) onToggleSelect(place.id); else onOpenPlace(place.id) } }}
className={`col-lrow col-lrow-place${active || selected ? ' sel' : ''}`}
className={`col-lrow col-lrow-place${active || selected ? ' sel' : ''}${reorder.enabled ? ' can-reorder' : ''}${reorder.dragId === place.id ? ' dragging' : ''}${reorder.dropSide(place.id) ? ` drop-${reorder.dropSide(place.id)}` : ''}`}
{...reorder.rowProps(place.id)}
>
{reorder.enabled && (
<span
className="col-lgrip"
role="button"
tabIndex={0}
aria-label={t('collections.reorderHandle', { name: place.name })}
onClick={e => e.stopPropagation()}
{...reorder.handleProps(place.id)}
>
<GripVertical size={14} />
</span>
)}
{selectMode ? (
<span className={`col-lcheck${selected ? ' on' : ''}`}>{selected && <Check size={14} strokeWidth={3} />}</span>
) : (
@@ -0,0 +1,82 @@
import { Loader2, MapPin, MapPinCheck, MapPinOff, Search } from 'lucide-react';
import React from 'react';
import type { MapMatch } from '../../repo/mapMatchRepo';
import type { TranslationFn } from '../../types';
import { useLocationSearch } from '../shared/useLocationSearch';
interface CollectionLocationSearchProps {
/** A hit was picked and waits for the save: the row says so instead of the hint. */
picked: boolean;
onPick: (spot: MapMatch) => void;
t: TranslationFn;
}
/**
* The "find the position" row of the saved place's edit form (#2837). The form
* had an address and two coordinate fields but no search, so a place saved with
* a typed address had no way back onto the map short of looking the numbers up
* elsewhere. A pick fills only the coordinates (and an empty address).
*/
export function CollectionLocationSearch({ picked, onPick, t }: CollectionLocationSearchProps): React.ReactElement {
const { query, setQuery, results, searching, noResults, search, pick } = useLocationSearch(onPick);
return (
<div className="col-detail-field">
<div className="col-detail-label">
<Search size={12} /> {t('collections.findPosition')}
</div>
{!picked && (
<p className="flex items-start gap-1.5 text-caption text-content-muted">
<MapPinOff size={13} strokeWidth={2} aria-hidden="true" className="mt-px flex-none text-warning" />
{t('collections.findPositionHint')}
</p>
)}
{picked && (
<p className="flex items-start gap-1.5 text-caption text-content-muted" role="status">
<MapPinCheck size={13} strokeWidth={2} aria-hidden="true" className="mt-px flex-none text-success" />
{t('collections.findPositionPicked')}
</p>
)}
<form
className="col-detail-link-row"
role="search"
onSubmit={(e) => {
e.preventDefault();
void search();
}}
>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('collections.findPositionPlaceholder')}
aria-label={t('collections.findPosition')}
className="col-detail-input flex-1"
/>
<button
type="submit"
className="col-detail-icon-btn"
disabled={!query.trim() || searching}
aria-label={t('common.search')}
>
{searching ? <Loader2 size={14} className="animate-spin" /> : <Search size={14} />}
</button>
</form>
{noResults && <p className="text-caption text-content-faint">{t('planner.noPlacesFound')}</p>}
{results.length > 0 && (
<ul className="flex flex-col gap-0.5" aria-label={t('collections.findPosition')}>
{results.map((spot, i) => (
<li key={`${spot.lat},${spot.lng},${i}`}>
<button
type="button"
onClick={() => pick(spot)}
className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-start hover:bg-surface-hover"
>
<MapPin size={13} className="flex-none text-content-faint" />
<span className="min-w-0 flex-1 truncate text-body text-content">{spot.label}</span>
</button>
</li>
))}
</ul>
)}
</div>
);
}
@@ -16,6 +16,7 @@ import { STATUS_META, STATUS_ORDER, normalizeLinkUrl } from '../../pages/collect
import { Tooltip } from '../shared/Tooltip'
import PlaceRating from '../shared/StarRating'
import { useCollectionPlaceForm } from './useCollectionPlaceForm'
import { CollectionLocationSearch } from './CollectionLocationSearch'
function linkHost(url: string): string {
try { return new URL(url).hostname.replace(/^www\./, '') } catch { return url }
@@ -75,7 +76,7 @@ export default function CollectionPlaceDetail({
const descRef = useRef<HTMLTextAreaElement>(null)
const {
editing, setEditing, name, setName, categoryId, setCategoryId, description, setDescription, notes, setNotes, links, setLinks, setLink,
labelIds, toggleLabel, address, setAddress, lat, setLat, lng, setLng, saving, imgBusy, cover: banner, assignedLabels,
labelIds, toggleLabel, address, setAddress, lat, setLat, lng, setLng, pickPosition, positionPicked, needsPosition, saving, imgBusy, cover: banner, assignedLabels,
handleImagePick: handleCoverPick, handleImageRemove, cancelEdit: resetForm, save,
} = useCollectionPlaceForm({ place, labels, onSave, onUploadImage, t, normalizeLinkUrl, withCoordinates: true })
@@ -191,6 +192,8 @@ export default function CollectionPlaceDetail({
})}
</div>
</div>
{/* A place that has no position yet can be looked up here (#2837). */}
{needsPosition && <CollectionLocationSearch picked={positionPicked} onPick={pickPosition} t={t} />}
{/* Address (#1870): free text, the coordinates stay separate */}
<div className="col-detail-field">
<div className="col-detail-label"><MapPin size={12} /> {t('places.formAddress')}</div>
@@ -0,0 +1,50 @@
// FE-COMP-COPYCARRY-001 to FE-COMP-COPYCARRY-002
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import CopyCarryPanel from './CopyCarryPanel';
const t = (k: string) => k;
describe.each(['dialog', 'sheet'] as const)('CopyCarryPanel (%s)', (variant) => {
it('FE-COMP-COPYCARRY-001: switches the notes and picks tags to take along', () => {
const onIncludeNotes = vi.fn();
const onToggleTag = vi.fn();
render(
<CopyCarryPanel
options={{
hasNotes: true,
tags: [
{ id: 7, name: 'Coffee', color: '#f97316' },
{ id: 8, name: 'Late' },
],
}}
includeNotes={false}
onIncludeNotes={onIncludeNotes}
tagIds={[8]}
onToggleTag={onToggleTag}
variant={variant}
t={t}
/>
);
fireEvent.click(screen.getByRole('button', { name: 'collections.copyCarry.notes' }));
expect(onIncludeNotes).toHaveBeenCalledWith(true);
expect(screen.getByRole('button', { name: 'Late' })).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(screen.getByRole('button', { name: 'Coffee' }));
expect(onToggleTag).toHaveBeenCalledWith(7);
});
it('FE-COMP-COPYCARRY-002: shows only what the places carry', () => {
render(
<CopyCarryPanel
options={{ hasNotes: false, tags: [{ id: 7, name: 'Coffee' }] }}
includeNotes={false}
onIncludeNotes={vi.fn()}
tagIds={[]}
onToggleTag={vi.fn()}
variant={variant}
t={t}
/>
);
expect(screen.queryByText('collections.copyCarry.notes')).toBeNull();
expect(screen.getByRole('button', { name: 'Coffee' })).toHaveAttribute('aria-pressed', 'false');
});
});
@@ -0,0 +1,101 @@
import { NotebookPen, Tag } from 'lucide-react';
import React from 'react';
import type { TranslationFn } from '../../types';
import ToggleSwitch from '../Settings/ToggleSwitch';
import type { CopyCarryOptions } from './useTripCopyPicker';
interface CopyCarryPanelProps {
options: CopyCarryOptions;
includeNotes: boolean;
onIncludeNotes: (on: boolean) => void;
tagIds: number[];
onToggleTag: (id: number) => void;
/** The phone sheet wears the mobile tokens, the desktop dialog the app's. */
variant: 'dialog' | 'sheet';
t: TranslationFn;
}
const LOOK = {
dialog: {
box: 'rounded-[14px] border border-edge-faint bg-surface-secondary px-3.5 py-3',
title: 'text-content-muted',
label: 'text-content',
hint: 'text-content-faint',
chipOff: 'border-edge-faint bg-surface-card text-content-muted',
chipOn: 'border-accent bg-accent text-accent-text',
},
sheet: {
box: 'rounded-2xl border border-m-rowbr bg-m-sheetop px-3.5 py-3',
title: 'text-m-muted',
label: 'text-m-ink',
hint: 'text-m-faint',
chipOff: 'border-m-rowbr bg-m-ic text-m-muted',
chipOn: 'border-m-act bg-m-act text-m-actfg',
},
} as const;
/**
* What goes along when saved places are copied into a trip (#3168). Notes and tags
* are the reader's own, so neither leaves the list unless it is switched on here; a
* tag taken along becomes a tag of the trip, shared with its travellers.
*/
export default function CopyCarryPanel({
options,
includeNotes,
onIncludeNotes,
tagIds,
onToggleTag,
variant,
t,
}: CopyCarryPanelProps): React.ReactElement {
const look = LOOK[variant];
return (
<section className={`flex flex-col gap-3 ${look.box}`} aria-label={t('collections.copyCarry.title')}>
<div className={`text-caption font-semibold ${look.title}`}>{t('collections.copyCarry.title')}</div>
{options.hasNotes && (
<div className="flex items-center gap-3">
<NotebookPen size={15} className={`flex-none ${look.hint}`} aria-hidden="true" />
<div className="min-w-0 flex-1">
<div className={`text-body font-semibold ${look.label}`}>{t('collections.copyCarry.notes')}</div>
<div className={`text-caption ${look.hint}`}>{t('collections.copyCarry.notesHint')}</div>
</div>
<ToggleSwitch
on={includeNotes}
onToggle={() => onIncludeNotes(!includeNotes)}
label={t('collections.copyCarry.notes')}
/>
</div>
)}
{options.tags.length > 0 && (
<div className="flex items-start gap-3">
<Tag size={15} className={`mt-0.5 flex-none ${look.hint}`} aria-hidden="true" />
<div className="min-w-0 flex-1">
<div className={`text-body font-semibold ${look.label}`}>{t('collections.copyCarry.tags')}</div>
<div className={`text-caption ${look.hint}`}>{t('collections.copyCarry.tagsHint')}</div>
<div className="mt-2 flex flex-wrap gap-1.5" role="group" aria-label={t('collections.copyCarry.tags')}>
{options.tags.map((tag) => {
const on = tagIds.includes(tag.id);
return (
<button
key={tag.id}
type="button"
aria-pressed={on}
onClick={() => onToggleTag(tag.id)}
className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-caption font-semibold ${on ? look.chipOn : look.chipOff}`}
>
{/* The tag's own colour, the one data-driven value here. */}
<span
className="h-2 w-2 flex-none rounded-full"
style={{ background: tag.color || 'var(--accent)' }}
/>
{tag.name}
</button>
);
})}
</div>
</div>
</div>
)}
</section>
);
}
@@ -162,7 +162,7 @@ describe('CopyToTripModal', () => {
fireEvent.click(await screen.findByText('Rome 2026'));
await waitFor(() => expect(props.onClose).toHaveBeenCalled());
expect(onCopy).toHaveBeenCalledWith(1);
expect(onCopy).toHaveBeenCalledWith(1, {});
expect(addToast).toHaveBeenCalledWith('Copied 2 places', 'success', undefined);
});
@@ -3,7 +3,8 @@ import { Search, MapPin, Loader2, Copy, CalendarDays } from 'lucide-react'
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { INPUT } from '../shared/dialogParts'
import type { TranslationFn } from '../../types'
import { useTripCopyPicker } from './useTripCopyPicker'
import { useTripCopyPicker, type CopyCarry, type CopyCarryOptions } from './useTripCopyPicker'
import CopyCarryPanel from './CopyCarryPanel'
interface CopyToTripModalProps {
isOpen: boolean
@@ -11,7 +12,9 @@ interface CopyToTripModalProps {
/** The collection place ids to copy. */
placeIds: number[]
/** Delegates to collectionStore.copyToTrip; returns the server reconcile result. */
onCopy: (tripId: number) => Promise<{ copied: number; skipped: { id: number; name: string }[] }>
onCopy: (tripId: number, carry: CopyCarry) => Promise<{ copied: number; skipped: { id: number; name: string }[] }>
/** The notes and tags the copied places carry, offered to take along. */
carryOptions?: CopyCarryOptions
t: TranslationFn
}
@@ -21,10 +24,10 @@ interface CopyToTripModalProps {
* dedup result into a copied / skipped-duplicates toast. Works for a single
* place (detail panel) and bulk select-mode ("Copy N to trip").
*/
export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, t }: CopyToTripModalProps): React.ReactElement | null {
export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, carryOptions, t }: CopyToTripModalProps): React.ReactElement | null {
const labelId = useId()
const { loading, search, setSearch, filtered, busyTripId, dateRange, handleCopy } =
useTripCopyPicker({ open: isOpen, onCopy, onClose, t, emptySelection: placeIds.length === 0 })
const { loading, search, setSearch, filtered, busyTripId, dateRange, handleCopy, offersCarry, includeNotes, setIncludeNotes, tagIds, toggleTag } =
useTripCopyPicker({ open: isOpen, onCopy, onClose, t, emptySelection: placeIds.length === 0, carryOptions })
if (!isOpen) return null
@@ -62,6 +65,9 @@ export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, t }
className={`${INPUT} ps-8`}
/>
</div>
{offersCarry && carryOptions && (
<CopyCarryPanel options={carryOptions} includeNotes={includeNotes} onIncludeNotes={setIncludeNotes} tagIds={tagIds} onToggleTag={toggleTag} variant="dialog" t={t} />
)}
{loading ? (
<div className="flex items-center justify-center py-8 text-content-faint">
<Loader2 size={20} className="animate-spin" />
@@ -10,9 +10,14 @@ import {
type CollectionFileError,
type GpxLeftovers,
type GpxReader,
type MapReader,
type ParsedCollectionFile,
COLLECTION_FILE_EXTENSION,
COLLECTION_GPX_EXTENSION,
COLLECTION_KML_EXTENSION,
COLLECTION_KMZ_EXTENSION,
} from './collectionFile'
import MapImportPreview from './MapImportPreview'
interface ImportCollectionModalProps {
onImport: (file: CollectionFile, name?: string) => Promise<void>
@@ -24,6 +29,8 @@ interface ImportCollectionModalProps {
defaultListId?: number | null
/** Reads a GPX into a list file (#2301); the server does the parsing. */
onReadGpx: GpxReader
/** Reads a KML or KMZ map into a list file (PLC-22); the server does that as well. */
onReadMap?: MapReader
onClose: () => void
t: TranslationFn
}
@@ -34,6 +41,7 @@ const ERROR_KEYS: Record<CollectionFileError, string> = {
unreadable: 'collections.file.errorUnreadable',
'not-a-collection': 'collections.file.errorNotACollection',
'not-gpx': 'collections.file.errorNotGpx',
'not-map': 'collections.file.errorNotMap',
'too-many-places': 'collections.file.errorTooManyPlaces',
}
@@ -178,13 +186,16 @@ function ListChoice({ lists, selectedId, onSelect, t }: {
* in it alone and skips the places it already has.
*/
export default function ImportCollectionModal({
onImport, onImportInto, lists, defaultListId, onReadGpx, onClose, t,
onImport, onImportInto, lists, defaultListId, onReadGpx, onReadMap, onClose, t,
}: ImportCollectionModalProps): React.ReactElement {
const inputRef = useRef<HTMLInputElement>(null)
const titleId = useId()
const nameId = useId()
const [file, setFile] = useState<CollectionFile | null>(null)
const [leftovers, setLeftovers] = useState<GpxLeftovers | null>(null)
// A map's placemarks, each one to keep or not: all of them to start with.
const [map, setMap] = useState<ParsedCollectionFile['map']>(null)
const [picked, setPicked] = useState<Set<number>>(new Set())
const [name, setName] = useState('')
const [error, setError] = useState<CollectionFileError | 'failed' | null>(null)
const [failedMessage, setFailedMessage] = useState<string | null>(null)
@@ -208,14 +219,17 @@ export default function ImportCollectionModal({
setFailedMessage(null)
setReading(true)
try {
const result = await readCollectionFile(chosen, onReadGpx)
const result = await readCollectionFile(chosen, onReadGpx, onReadMap)
setFile(result.file)
setLeftovers(result.gpx ?? null)
setMap(result.map ?? null)
setPicked(new Set(result.file?.places.map((_, i) => i) ?? []))
setError(result.error)
if (result.file) setName(result.file.name)
} catch (err) {
setFile(null)
setLeftovers(null)
setMap(null)
setError('failed')
setFailedMessage(getApiErrorMessage(err, t('common.error')))
} finally {
@@ -229,17 +243,22 @@ export default function ImportCollectionModal({
void take(e.dataTransfer.files?.[0])
}
// A map goes in with the placemarks left ticked; the rest of its file is unchanged.
const chosenFile = (): CollectionFile | null =>
!file ? null : map ? { ...file, places: file.places.filter((_, i) => picked.has(i)) } : file
const submit = async () => {
if (!file || busy) return
const outgoing = chosenFile()
if (!outgoing || busy) return
setBusy(true)
setError(null)
setFailedMessage(null)
try {
if (intoExisting && listId != null) {
await onImportInto!(file, listId)
await onImportInto!(outgoing, listId)
} else {
const trimmed = name.trim()
await onImport(file, trimmed && trimmed !== file.name ? trimmed : undefined)
await onImport(outgoing, trimmed && trimmed !== outgoing.name ? trimmed : undefined)
}
} catch (err) {
setError('failed')
@@ -254,7 +273,7 @@ export default function ImportCollectionModal({
: error ? t(ERROR_KEYS[error], { count: MAX_COLLECTION_FILE_PLACES }) : null
// A GPX of nothing but a track would make an empty list, which is never what was meant.
const nothingToImport = !!leftovers && !!file && file.places.length === 0
const nothingToImport = (!!leftovers || !!map) && !!file && (map ? picked.size === 0 : file.places.length === 0)
return (
<DialogShell
@@ -290,7 +309,7 @@ export default function ImportCollectionModal({
<input
ref={inputRef}
type="file"
accept=".json,application/json,.gpx,application/gpx+xml"
accept={onReadMap ? ".json,application/json,.gpx,application/gpx+xml,.kml,.kmz,application/vnd.google-earth.kml+xml,application/vnd.google-earth.kmz" : ".json,application/json,.gpx,application/gpx+xml"}
className="hidden"
onChange={e => { void take(e.target.files?.[0]); e.target.value = '' }}
/>
@@ -314,7 +333,7 @@ export default function ImportCollectionModal({
<span className="font-semibold text-content" style={fs(13, 'body')}>
{reading ? t('collections.file.reading') : t('collections.file.choose')}
</span>
<span className="flex items-center gap-1.5 text-content-faint" style={fs(11.5)}><span>{COLLECTION_FILE_EXTENSION}</span><span>{COLLECTION_GPX_EXTENSION}</span></span>
<span className="flex items-center gap-1.5 text-content-faint" style={fs(11.5)}><span>{COLLECTION_FILE_EXTENSION}</span><span>{COLLECTION_GPX_EXTENSION}</span>{onReadMap && <><span>{COLLECTION_KML_EXTENSION}</span><span>{COLLECTION_KMZ_EXTENSION}</span></>}</span>
</button>
) : (
<>
@@ -322,7 +341,7 @@ export default function ImportCollectionModal({
<div className="flex flex-col gap-2.5">
<div className="flex items-center gap-3 rounded-[14px] border border-edge-faint bg-surface-secondary p-2.5">
<span className="grid h-9 w-9 flex-none place-items-center rounded-[10px]" style={swatch(file.color)}>
{leftovers ? <Route size={16} /> : <FileJson size={16} />}
{leftovers || map ? <Route size={16} /> : <FileJson size={16} />}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-semibold text-content" style={fs(13, 'body')}>{file.name}</span>
@@ -348,6 +367,16 @@ export default function ImportCollectionModal({
)}
{leftovers && <GpxNotes leftovers={leftovers} placeCount={file.places.length} t={t} />}
{map && (
<MapImportPreview
file={file}
map={map}
picked={picked}
onToggle={i => setPicked(prev => { const next = new Set(prev); if (next.has(i)) next.delete(i); else next.add(i); return next })}
onAll={on => setPicked(new Set(on ? file.places.map((_, i) => i) : []))}
t={t}
/>
)}
</div>
{canChoose && (
@@ -379,7 +408,7 @@ export default function ImportCollectionModal({
label={t('collections.listName')}
htmlFor={nameId}
// Ratings and members are a TREK file's business; a GPX never had any.
hint={leftovers ? undefined : t('collections.file.hint')}
hint={leftovers || map ? undefined : t('collections.file.hint')}
>
<input
id={nameId}
@@ -0,0 +1,45 @@
// FE-COMP-MAPIMPORT-001 to FE-COMP-MAPIMPORT-002
import type { CollectionFile } from '@trek/shared';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import MapImportPreview from './MapImportPreview';
const t = (k: string, p?: Record<string, unknown>) => (p ? `${k}:${JSON.stringify(p)}` : k);
const file = {
format: 'trek.collection',
version: 1,
name: 'Lisbon',
places: [
{ name: 'Belem', address: 'Belem, Lisbon', lat: 38.69, lng: -9.21 },
{ name: 'Alfama', lat: 38.71, lng: -9.13 },
],
} as unknown as CollectionFile;
const map = {
folders: ['Sights', null],
skipped: [
{ name: 'Tram 28', folder: null, reason: 'line' as const },
{ name: null, folder: null, reason: 'no_point' as const },
],
};
describe('MapImportPreview', () => {
it('FE-COMP-MAPIMPORT-001: lists every place with its folder, and toggles one or all of them', () => {
const onToggle = vi.fn();
const onAll = vi.fn();
render(<MapImportPreview file={file} map={map} picked={new Set([0, 1])} onToggle={onToggle} onAll={onAll} t={t} />);
expect(screen.getByText('Sights')).toBeInTheDocument();
expect(screen.getByRole('checkbox', { name: /Belem/ })).toHaveAttribute('aria-checked', 'true');
fireEvent.click(screen.getByRole('checkbox', { name: /Alfama/ }));
expect(onToggle).toHaveBeenCalledWith(1);
fireEvent.click(screen.getByRole('button', { name: 'collections.file.mapNone' }));
expect(onAll).toHaveBeenCalledWith(false);
});
it('FE-COMP-MAPIMPORT-002: says what was left out and why, on request', () => {
render(<MapImportPreview file={file} map={map} picked={new Set([0])} onToggle={vi.fn()} onAll={vi.fn()} t={t} />);
expect(screen.getByRole('button', { name: 'collections.file.mapAll' })).toBeInTheDocument();
expect(screen.queryByText(/Tram 28/)).toBeNull();
fireEvent.click(screen.getByRole('button', { name: /collections.file.mapSkipped/ }));
expect(screen.getByText('Tram 28: collections.file.mapSkipLine')).toBeInTheDocument();
expect(screen.getByText('collections.file.mapUnnamed: collections.file.mapSkipNoPoint')).toBeInTheDocument();
});
});
@@ -0,0 +1,121 @@
import type { CollectionFile, CollectionMapReadResult, CollectionMapSkipReason } from '@trek/shared';
import { Check, ChevronDown, Folder, Info, MapPin } from 'lucide-react';
import React, { useState } from 'react';
import type { TranslationFn } from '../../types';
import { fs } from '../shared/DialogShell';
const SKIP_KEYS: Record<CollectionMapSkipReason, string> = {
line: 'collections.file.mapSkipLine',
no_point: 'collections.file.mapSkipNoPoint',
invalid: 'collections.file.mapSkipInvalid',
};
interface MapImportPreviewProps {
file: CollectionFile;
map: Pick<CollectionMapReadResult, 'skipped' | 'folders'>;
/** Indexes into `file.places` that will be imported. */
picked: Set<number>;
onToggle: (index: number) => void;
onAll: (on: boolean) => void;
t: TranslationFn;
}
/**
* The places a KML or KMZ map holds, each one to keep or leave out (PLC-22), and
* what did not become a place and why. Nothing is written before the import button,
* so a map with a hundred pins can be narrowed to the six that matter first.
*/
export default function MapImportPreview({
file,
map,
picked,
onToggle,
onAll,
t,
}: MapImportPreviewProps): React.ReactElement {
const [showSkipped, setShowSkipped] = useState(false);
const all = picked.size === file.places.length;
return (
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between gap-2">
<span className="font-semibold text-content-muted" style={fs(12, 'body')}>
{t('collections.file.mapPicked', { picked: picked.size, total: file.places.length })}
</span>
<button
type="button"
onClick={() => onAll(!all)}
className="rounded-[8px] px-2 py-1 font-semibold text-content-muted hover:bg-surface-secondary"
style={fs(12, 'body')}
>
{all ? t('collections.file.mapNone') : t('collections.file.mapAll')}
</button>
</div>
<ul className="m-0 flex max-h-[34vh] list-none flex-col gap-0.5 overflow-y-auto rounded-[14px] border border-edge-faint bg-surface-secondary p-1.5">
{file.places.map((place, index) => {
const on = picked.has(index);
const folder = map.folders[index];
return (
<li key={`${index}-${place.name}`}>
<button
type="button"
role="checkbox"
aria-checked={on}
onClick={() => onToggle(index)}
className={`flex min-h-[44px] w-full items-center gap-2.5 rounded-[10px] px-2.5 py-1.5 text-start ${on ? 'bg-surface-card shadow-sm' : 'opacity-60 hover:bg-surface-card'}`}
>
<span
className={`grid h-5 w-5 flex-none place-items-center rounded-md border ${on ? 'border-accent bg-accent text-accent-text' : 'border-edge bg-surface-card'}`}
>
{on && <Check size={12} strokeWidth={3} />}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-semibold text-content" style={fs(13, 'body')}>
{place.name}
</span>
<span className="flex items-center gap-2 truncate text-content-faint" style={fs(11.5)}>
{folder && (
<span className="inline-flex min-w-0 items-center gap-1">
<Folder size={11} className="flex-none" />
<span className="truncate">{folder}</span>
</span>
)}
{place.address && (
<span className="inline-flex min-w-0 items-center gap-1">
<MapPin size={11} className="flex-none" />
<span className="truncate">{place.address}</span>
</span>
)}
</span>
</span>
</button>
</li>
);
})}
</ul>
{map.skipped.length > 0 && (
<div className="flex flex-col gap-1">
<button
type="button"
onClick={() => setShowSkipped((v) => !v)}
aria-expanded={showSkipped}
className="flex items-center gap-2 self-start text-content-muted"
style={fs(12, 'body')}
>
<Info size={13} className="flex-none text-content-faint" />
{t('collections.file.mapSkipped', { count: map.skipped.length })}
<ChevronDown size={13} className={`transition-transform ${showSkipped ? 'rotate-180' : ''}`} />
</button>
{showSkipped && (
<ul className="m-0 flex list-none flex-col gap-0.5 ps-5">
{map.skipped.map((entry, i) => (
<li key={i} className="text-content-faint" style={fs(11.5)}>
{entry.name || t('collections.file.mapUnnamed')}: {t(SKIP_KEYS[entry.reason])}
</li>
))}
</ul>
)}
</div>
)}
</div>
);
}
@@ -207,3 +207,49 @@ describe('readCollectionFile with a GPX (#2301)', () => {
expect(await readCollectionFile(broken, noGpx)).toEqual({ file: null, error: 'unreadable' })
})
})
describe('readCollectionFile with a map (PLC-22)', () => {
const mapResult = {
file: { format: 'trek.collection', version: 1, name: 'Lisbon', places: [{ name: 'Belem', lat: 38.69, lng: -9.21 }] },
folders: ['Sights'],
skipped: [{ name: 'Tram 28', folder: null, reason: 'line' as const }],
}
it('FE-COLL-FILE-101: a .kml, a .kmz and a KML by its root element go to the map reader', async () => {
const reader = vi.fn(async () => mapResult as never)
for (const f of [
new File(['<kml></kml>'], 'trip.kml'),
new File([new Uint8Array([0x50, 0x4b, 3, 4])], 'trip.kmz'),
new File(['<?xml version="1.0"?><kml xmlns="http://www.opengis.net/kml/2.2"></kml>'], 'export.xml'),
]) {
const result = await readCollectionFile(f, noGpx, reader)
expect(result).toEqual({ file: mapResult.file, error: null, map: { skipped: mapResult.skipped, folders: ['Sights'] } })
}
expect(reader).toHaveBeenCalledTimes(3)
})
it('FE-COLL-FILE-102: a GPX still goes to the GPX reader when a map reader is there', async () => {
const gpx = vi.fn(async () => ({ file: mapResult.file, skipped: 0, track_points: 0 }) as never)
const reader = vi.fn()
await readCollectionFile(new File(['<gpx version="1.1"></gpx>'], 'walk.gpx'), gpx, reader)
expect(gpx).toHaveBeenCalled()
expect(reader).not.toHaveBeenCalled()
})
it('FE-COLL-FILE-103: the server refusing a map is said in the dialog words; other failures pass on', async () => {
expect(await readCollectionFile(new File(['x'], 'a.kml'), noGpx, () => Promise.reject(refused('not-map'))))
.toEqual({ file: null, error: 'not-map', map: null })
expect(await readCollectionFile(new File(['x'], 'a.kml'), noGpx, () => Promise.reject(refused('no-file'))))
.toEqual({ file: null, error: 'unreadable', map: null })
await expect(readCollectionFile(new File(['x'], 'a.kml'), noGpx, () => Promise.reject(new Error('offline')))).rejects.toThrow('offline')
})
it('FE-COLL-FILE-104: a map past the upload limit is not sent at all', async () => {
const reader = vi.fn()
const big = new File(['<kml/>'], 'big.kml')
Object.defineProperty(big, 'size', { value: 50 * 1024 * 1024 })
expect(await readCollectionFile(big, noGpx, reader)).toEqual({ file: null, error: 'too-large' })
expect(reader).not.toHaveBeenCalled()
})
})
@@ -1,10 +1,13 @@
import {
COLLECTION_GPX_PROBLEMS,
COLLECTION_MAP_PROBLEMS,
collectionFileSchema,
MAX_COLLECTION_FILE_BYTES,
MAX_COLLECTION_MAP_UPLOAD_BYTES,
type CollectionFile,
type CollectionGpxProblem,
type CollectionGpxReadResult,
type CollectionMapReadResult,
} from '@trek/shared'
import { downloadBlob } from '../../utils/fileDownload'
@@ -28,6 +31,7 @@ import { downloadBlob } from '../../utils/fileDownload'
export const COLLECTION_FILE_EXTENSION = '.trekcollection.json'
export const COLLECTION_GPX_EXTENSION = '.gpx'
export const COLLECTION_KML_EXTENSION = '.kml'
export const COLLECTION_KMZ_EXTENSION = '.kmz'
/**
* The ways a list can leave: whole, for another TREK, as waypoints for every
@@ -60,7 +64,7 @@ export function downloadCollectionKml(listName: string, kml: string): void {
download(kml, 'application/vnd.google-earth.kml+xml', collectionFileName(listName, COLLECTION_KML_EXTENSION))
}
export type CollectionFileError = 'not-a-collection' | CollectionGpxProblem
export type CollectionFileError = 'not-a-collection' | 'not-map' | CollectionGpxProblem
/** What a GPX held that did not become a place. */
export interface GpxLeftovers {
@@ -82,11 +86,45 @@ export interface ParsedCollectionFile {
file: CollectionFile | null
error: CollectionFileError | null
gpx?: GpxLeftovers | null
/** A KML or KMZ map (PLC-22): what did not become a place, and the folder of each one that did. */
map?: Pick<CollectionMapReadResult, 'skipped' | 'folders'> | null
}
/** Reads a GPX document into a list file. The server does that, so the caller supplies it. */
export type GpxReader = (gpx: string, fileName: string) => Promise<CollectionGpxReadResult>
/** Reads a KML or KMZ into a list file. The server does that too, so the caller supplies it. */
export type MapReader = (file: File) => Promise<CollectionMapReadResult>
/** A KMZ is a zip; a KML says so in its root element, which is how it differs from a GPX. */
async function looksLikeMap(file: File): Promise<boolean> {
const name = (file.name ?? '').toLowerCase()
if (name.endsWith(COLLECTION_KML_EXTENSION) || name.endsWith(COLLECTION_KMZ_EXTENSION)) return true
const head = new Uint8Array(await file.slice(0, 512).arrayBuffer())
if (head[0] === 0x50 && head[1] === 0x4b) return true
return /<kml[\s>]/i.test(new TextDecoder().decode(head))
}
/** The reason the server gave for refusing a map, folded into the dialog's own words. */
function mapProblemOf(err: unknown): CollectionFileError | null {
const code: unknown = (err as { response?: { data?: { code?: unknown } } } | null)?.response?.data?.code
const problem = COLLECTION_MAP_PROBLEMS.find(p => p === code)
if (!problem) return null
return problem === 'no-file' ? 'unreadable' : problem
}
async function readMap(file: File, reader: MapReader): Promise<ParsedCollectionFile> {
if (file.size > MAX_COLLECTION_MAP_UPLOAD_BYTES) return { file: null, error: 'too-large' }
try {
const result = await reader(file)
return { file: result.file, error: null, map: { skipped: result.skipped, folders: result.folders } }
} catch (err) {
const problem = mapProblemOf(err)
if (!problem) throw err
return { file: null, error: problem, map: null }
}
}
/** A list file is JSON and JSON never opens with `<`, so this is all the sniffing a GPX needs. */
function looksLikeXml(text: string): boolean {
const withoutBom = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
@@ -120,7 +158,8 @@ async function readGpx(text: string, fileName: string, reader: GpxReader): Promi
* readable at all, a JSON that is not a TREK list, an XML that is not a GPX,
* and a GPX with more places than a list may hold.
*/
export async function readCollectionFile(file: File, readGpxFile: GpxReader): Promise<ParsedCollectionFile> {
export async function readCollectionFile(file: File, readGpxFile: GpxReader, readMapFile?: MapReader): Promise<ParsedCollectionFile> {
if (readMapFile && (await looksLikeMap(file))) return readMap(file, readMapFile)
if (file.size > MAX_COLLECTION_FILE_BYTES) return { file: null, error: 'too-large' }
let text: string
try {
@@ -1,7 +1,6 @@
// FE-COMP-ADDPLACEHOOK-001 to FE-COMP-ADDPLACEHOOK-020: the add-a-place logic behind the
// desktop dialog (variant 'dialog') and the phone sheet ('sheet').
import { act, renderHook, waitFor } from '@testing-library/react';
import type React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { resetAllStores } from '../../../tests/helpers/store';
@@ -238,20 +237,6 @@ describe('useAddPlaceToCollection: picking', () => {
expect(result.current.lat).toBe('');
expect(result.current.lng).toBe('');
});
it('FE-COMP-ADDPLACEHOOK-010: a pasted coordinate pair fills both fields, anything else is left to the input', () => {
const { result } = dialog();
const preventDefault = vi.fn();
const paste = (text: string) =>
({ clipboardData: { getData: () => text }, preventDefault }) as unknown as React.ClipboardEvent<HTMLInputElement>;
act(() => result.current.coordPaste(paste(' 53.55, 9.99 ')));
expect(result.current.lat).toBe('53.55');
expect(result.current.lng).toBe('9.99');
expect(preventDefault).toHaveBeenCalledTimes(1);
act(() => result.current.coordPaste(paste('Hamburg')));
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(result.current.lat).toBe('53.55');
});
});
describe('useAddPlaceToCollection: saving from the dialog', () => {
@@ -1,5 +1,4 @@
import type { CollectionLink, CollectionStatus } from '@trek/shared';
import type React from 'react';
import { useEffect, useEffectEvent, useState } from 'react';
import { mapsApi } from '../../api/client';
@@ -7,7 +6,6 @@ import { collectionsApi } from '../../api/collections';
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage';
import { getApiErrorMessage as errorWithMessage, type TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { parseCoordinatePair } from '../Planner/PlaceFormModal.helpers';
import { useToast } from '../shared/Toast';
import { type MapsPlace, num, str } from './addPlaceModel';
@@ -162,15 +160,9 @@ export function useAddPlaceToCollection(options: AddPlaceToCollectionOptions) {
const setLink = (i: number, patch: Partial<CollectionLink>) =>
setLinks(links.map((l, idx) => (idx === i ? { ...l, ...patch } : l)));
/** "48.85, 2.35" pasted into either coordinate fills both halves. */
const coordPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
const pair = parseCoordinatePair(e.clipboardData.getData('text'));
if (pair) {
e.preventDefault();
setLat(pair[0]);
setLng(pair[1]);
}
};
// The phone sheet takes coordinates from a picked hit only, so a typed address
// alone saves a place that will not be on the map; the sheet says so (#2837).
const positionMissing = sheet && !!address.trim() && !(picked && num(picked.lat) != null && num(picked.lng) != null);
const save = async () => {
const cleanName = name.trim();
@@ -252,7 +244,7 @@ export function useAddPlaceToCollection(options: AddPlaceToCollectionOptions) {
setTargetId,
search,
pick,
coordPaste,
save,
positionMissing,
};
}
@@ -1,4 +1,4 @@
// FE-COMP-COLPLACEHOOK-001 to FE-COMP-COLPLACEHOOK-013: the saved place detail logic
// FE-COMP-COLPLACEHOOK-001 to FE-COMP-COLPLACEHOOK-015: the saved place detail logic
// behind both the desktop detail sheet and the phone sheet.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { CollectionLabel, CollectionPlace } from '@trek/shared';
@@ -272,4 +272,30 @@ describe('useCollectionPlaceForm', () => {
expect(onSave).toHaveBeenCalledWith({ image_url: null });
expect(addToast).toHaveBeenCalledTimes(2);
});
it('FE-COMP-COLPLACEHOOK-014: a picked position is saved even where the form has no coordinate fields (#2837)', async () => {
const { result, props } = setup({ place: place({ address: null, lat: null, lng: null }) });
expect(result.current.needsPosition).toBe(true);
act(() => result.current.pickPosition({ lat: 35.66, lng: 139.7, address: 'Shibuya, Tokyo' }));
expect(result.current.address).toBe('Shibuya, Tokyo');
expect(result.current.positionPicked).toBe(true);
await act(() => result.current.save());
expect(props.onSave).toHaveBeenCalledWith(
expect.objectContaining({ lat: 35.66, lng: 139.7, address: 'Shibuya, Tokyo' })
);
});
it('FE-COMP-COLPLACEHOOK-015: without a pick the phone form never sends coordinates, and a pick keeps a typed address', async () => {
const { result, props } = setup();
expect(result.current.needsPosition).toBe(false);
act(() => result.current.setAddress('Typed by hand'));
await act(() => result.current.save());
expect(props.onSave).toHaveBeenLastCalledWith(expect.not.objectContaining({ lat: expect.anything() }));
act(() => result.current.pickPosition({ lat: 0, lng: 0, address: 'Somewhere else' }));
expect(result.current.address).toBe('Typed by hand');
await act(() => result.current.save());
expect(props.onSave).toHaveBeenLastCalledWith(
expect.objectContaining({ lat: 0, lng: 0, address: 'Typed by hand' })
);
});
});
@@ -6,6 +6,7 @@ import { mapsApi } from '../../api/client';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { normalizeImageFile } from '../../utils/convertHeic';
import { hasCoordinates } from '../Planner/placeCoordinates';
import { useToast } from '../shared/Toast';
import { cleanListLinks } from './useListEditor';
@@ -92,6 +93,9 @@ export function useCollectionPlaceForm({
const [address, setAddress] = useState(shown?.address ?? '');
const [lat, setLat] = useState(coordText(shown?.lat));
const [lng, setLng] = useState(coordText(shown?.lng));
// A position picked from the map search (#2837). The phone form has no coordinate
// fields, so its save only sends coordinates once one was picked here.
const [positionPicked, setPositionPicked] = useState(false);
const [saving, setSaving] = useState(false);
// A higher res photo pulled from the maps provider when the place has none of
// its own; the list avatar's little thumbnail is too low res for the cover.
@@ -110,8 +114,17 @@ export function useCollectionPlaceForm({
setAddress(p.address ?? '');
setLat(coordText(p.lat));
setLng(coordText(p.lng));
setPositionPicked(false);
}, []);
/** Takes a hit of the position search: its coordinates, and its address only where the form has none. */
const pickPosition = (spot: { lat: number; lng: number; address?: string }) => {
setLat(String(spot.lat));
setLng(String(spot.lng));
if (!address.trim() && spot.address) setAddress(spot.address);
setPositionPicked(true);
};
// Reseed the form and fetch the cover only when a DIFFERENT place opens (keyed on
// the id, not on every field).
const seededId = useRef<number | null>(null);
@@ -201,7 +214,9 @@ export function useCollectionPlaceForm({
};
setSaving(true);
try {
await onSave(withCoordinates ? { ...base, lat: parseCoordinate(lat), lng: parseCoordinate(lng) } : base);
await onSave(
withCoordinates || positionPicked ? { ...base, lat: parseCoordinate(lat), lng: parseCoordinate(lng) } : base
);
setEditing(false);
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')));
@@ -230,6 +245,10 @@ export function useCollectionPlaceForm({
address,
setAddress,
lat,
pickPosition,
positionPicked,
// The search row is for places saved without a position, not for moving one that has it.
needsPosition: !!shown && !hasCoordinates(shown),
setLat,
lng,
setLng,
@@ -0,0 +1,74 @@
// FE-COMP-PLACEORDER-001 to FE-COMP-PLACEORDER-005: the list's own order (#1457).
import { act, renderHook } from '@testing-library/react';
import type React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { movePlace, stepPlace, usePlaceReorder } from './usePlaceReorder';
const drag = (over: Partial<React.DragEvent<HTMLElement>> = {}) =>
({
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
dataTransfer: { setData: vi.fn(), effectAllowed: '', dropEffect: '' },
clientY: 0,
currentTarget: { getBoundingClientRect: () => ({ top: 0, height: 40 }) },
...over,
}) as unknown as React.DragEvent<HTMLElement>;
describe('moving places in a list', () => {
it('FE-COMP-PLACEORDER-001: drops a place before or after another, and leaves a no-op alone', () => {
expect(movePlace([1, 2, 3, 4], 4, 2, 'before')).toEqual([1, 4, 2, 3]);
expect(movePlace([1, 2, 3, 4], 1, 3, 'after')).toEqual([2, 3, 1, 4]);
expect(movePlace([1, 2, 3], 2, 2, 'after')).toEqual([1, 2, 3]);
expect(movePlace([1, 2, 3], 9, 2, 'after')).toEqual([1, 2, 3]);
});
it('FE-COMP-PLACEORDER-002: steps one up or down and stops at either end', () => {
expect(stepPlace([1, 2, 3], 2, -1)).toEqual([2, 1, 3]);
expect(stepPlace([1, 2, 3], 2, 1)).toEqual([1, 3, 2]);
expect(stepPlace([1, 2, 3], 1, -1)).toEqual([1, 2, 3]);
expect(stepPlace([1, 2, 3], 3, 1)).toEqual([1, 2, 3]);
});
});
describe('usePlaceReorder', () => {
it('FE-COMP-PLACEORDER-003: a drag onto the lower half of a row lands after it and commits the whole order', () => {
const onCommit = vi.fn();
const { result } = renderHook(() => usePlaceReorder([1, 2, 3], true, onCommit));
act(() => (result.current.handleProps(1) as { onDragStart: (e: React.DragEvent) => void }).onDragStart(drag()));
expect(result.current.dragId).toBe(1);
const row = () =>
result.current.rowProps(3) as {
onDragOver: (e: React.DragEvent<HTMLElement>) => void;
onDrop: (e: React.DragEvent) => void;
};
act(() => row().onDragOver(drag({ clientY: 30 })));
expect(result.current.dropSide(3)).toBe('after');
expect(result.current.dropSide(1)).toBeNull();
act(() => row().onDrop(drag()));
expect(onCommit).toHaveBeenCalledWith([2, 3, 1]);
expect(result.current.dragId).toBeNull();
});
it('FE-COMP-PLACEORDER-004: the arrow keys move a place, a step past the end commits nothing', () => {
const onCommit = vi.fn();
const { result } = renderHook(() => usePlaceReorder([1, 2, 3], true, onCommit));
const key = (k: string) => ({ key: k, preventDefault: vi.fn() }) as unknown as React.KeyboardEvent;
const handle = (id: number) => result.current.handleProps(id) as { onKeyDown: (e: React.KeyboardEvent) => void };
act(() => handle(2).onKeyDown(key('ArrowUp')));
expect(onCommit).toHaveBeenLastCalledWith([2, 1, 3]);
act(() => handle(3).onKeyDown(key('ArrowDown')));
act(() => handle(3).onKeyDown(key('Enter')));
expect(onCommit).toHaveBeenCalledTimes(1);
act(() => result.current.moveDown(1));
expect(onCommit).toHaveBeenLastCalledWith([2, 1, 3]);
act(() => result.current.moveUp(3));
expect(onCommit).toHaveBeenLastCalledWith([1, 3, 2]);
});
it('FE-COMP-PLACEORDER-005: switched off, the rows and handles carry no drag at all', () => {
const { result } = renderHook(() => usePlaceReorder([1, 2], false, vi.fn()));
expect(result.current.handleProps(1)).toEqual({});
expect(result.current.rowProps(1)).toEqual({});
});
});
@@ -0,0 +1,105 @@
import type React from 'react';
import { useState } from 'react';
/** Where a dragged place would land relative to the row under it. */
export type DropSide = 'before' | 'after';
/**
* Moves `id` next to `targetId` in `order`. Returns the order unchanged when either id
* is missing or the place would land where it already is.
*/
export function movePlace(order: readonly number[], id: number, targetId: number, side: DropSide): number[] {
if (id === targetId || !order.includes(id) || !order.includes(targetId)) return [...order];
const rest = order.filter((x) => x !== id);
const at = rest.indexOf(targetId) + (side === 'after' ? 1 : 0);
return [...rest.slice(0, at), id, ...rest.slice(at)];
}
/** One step up or down, for the keyboard and for the phone's move buttons. */
export function stepPlace(order: readonly number[], id: number, delta: -1 | 1): number[] {
const from = order.indexOf(id);
const to = from + delta;
if (from < 0 || to < 0 || to >= order.length) return [...order];
const next = [...order];
next.splice(from, 1);
next.splice(to, 0, id);
return next;
}
const sameOrder = (a: readonly number[], b: readonly number[]) =>
a.length === b.length && a.every((x, i) => x === b[i]);
/**
* The manual order of a list's places (#1457), behind the desktop list and the phone
* cards, which render their own handles over it. Drag works with the mouse and, through
* the shell's touch bridge, with a finger; the handle also answers the arrow keys.
*
* `enabled` is false whenever a reorder would be a lie: another sort, a search or a
* filter that hides places, a list the reader may not edit, or "All saved", which mixes
* lists. Every change hands the whole order of the list to `onCommit`.
*/
export function usePlaceReorder(order: readonly number[], enabled: boolean, onCommit: (orderedIds: number[]) => void) {
const [dragId, setDragId] = useState<number | null>(null);
const [over, setOver] = useState<{ id: number; side: DropSide } | null>(null);
const commit = (next: number[]) => {
if (!sameOrder(next, order)) onCommit(next);
};
const end = () => {
setDragId(null);
setOver(null);
};
/** For the drag handle of one row. */
const handleProps = (id: number) =>
enabled
? {
draggable: true,
onDragStart: (e: React.DragEvent) => {
e.stopPropagation();
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', String(id));
setDragId(id);
},
onDragEnd: end,
onKeyDown: (e: React.KeyboardEvent) => {
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;
e.preventDefault();
commit(stepPlace(order, id, e.key === 'ArrowUp' ? -1 : 1));
},
}
: {};
/** For the row itself: where the drop would land, and the drop. */
const rowProps = (id: number) =>
enabled && dragId != null
? {
onDragOver: (e: React.DragEvent<HTMLElement>) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
const box = e.currentTarget.getBoundingClientRect();
const side: DropSide = e.clientY - box.top < box.height / 2 ? 'before' : 'after';
if (over?.id !== id || over.side !== side) setOver({ id, side });
},
onDrop: (e: React.DragEvent) => {
e.preventDefault();
if (dragId != null && over) commit(movePlace(order, dragId, over.id, over.side));
end();
},
}
: {};
/** The line a row shows while something is dragged over it. */
const dropSide = (id: number): DropSide | null =>
dragId != null && dragId !== id && over?.id === id ? over.side : null;
return {
enabled,
dragId,
handleProps,
rowProps,
dropSide,
moveUp: (id: number) => commit(stepPlace(order, id, -1)),
moveDown: (id: number) => commit(stepPlace(order, id, 1)),
};
}
@@ -1,4 +1,4 @@
// FE-COMP-TRIPCOPYHOOK-001 to FE-COMP-TRIPCOPYHOOK-009: the "Copy to trip" picker logic
// FE-COMP-TRIPCOPYHOOK-001 to FE-COMP-TRIPCOPYHOOK-011: the "Copy to trip" picker logic
// behind both the desktop dialog and the phone sheet.
import { act, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi, type Mock, type MockInstance } from 'vitest';
@@ -93,7 +93,7 @@ describe('useTripCopyPicker', () => {
await act(async () => {
await result.current.handleCopy(1);
});
expect(props.onCopy).toHaveBeenCalledWith(1);
expect(props.onCopy).toHaveBeenCalledWith(1, {});
expect(addToast).toHaveBeenCalledWith('collections.copiedCount:{"count":2}', 'success', undefined);
expect(addToast).toHaveBeenCalledTimes(1);
expect(props.onClose).toHaveBeenCalledTimes(1);
@@ -151,4 +151,37 @@ describe('useTripCopyPicker', () => {
});
expect(empty.props.onCopy).not.toHaveBeenCalled();
});
it('FE-COMP-TRIPCOPYHOOK-010: notes and tags stay behind unless picked, and only the offered tags go along', async () => {
const carryOptions = {
hasNotes: true,
tags: [
{ id: 7, name: 'Coffee' },
{ id: 8, name: 'Late' },
],
};
const { result, props } = setup({ carryOptions });
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.offersCarry).toBe(true);
await act(() => result.current.handleCopy(1));
expect(props.onCopy).toHaveBeenLastCalledWith(1, {});
act(() => {
result.current.setIncludeNotes(true);
result.current.toggleTag(8);
result.current.toggleTag(7);
result.current.toggleTag(7);
});
expect(result.current.tagIds).toEqual([8]);
await act(() => result.current.handleCopy(2));
expect(props.onCopy).toHaveBeenLastCalledWith(2, { include_notes: true, tag_ids: [8] });
});
it('FE-COMP-TRIPCOPYHOOK-011: a reopened picker starts with nothing taken along, and offers nothing without notes or tags', async () => {
const { result, rerender, props } = setup({ carryOptions: { hasNotes: true, tags: [] } });
act(() => result.current.setIncludeNotes(true));
rerender({ ...props, open: false });
rerender({ ...props, open: true, carryOptions: { hasNotes: false, tags: [] } });
expect(result.current.includeNotes).toBe(false);
expect(result.current.offersCarry).toBe(false);
});
});
@@ -20,10 +20,24 @@ export interface CopyResult {
skipped: { id: number; name: string }[];
}
/** What the copied places carry that may come along: their notes and their tags (#3168). */
export interface CopyCarryOptions {
hasNotes: boolean;
tags: { id: number; name: string; color?: string | null }[];
}
/** What the reader chose to take along. Left as is, nothing private leaves the list. */
export interface CopyCarry {
include_notes?: boolean;
tag_ids?: number[];
}
export interface TripCopyPickerOptions {
open: boolean;
/** Copies the selected places into the trip; resolves with the server's reconcile result. */
onCopy: (tripId: number) => Promise<CopyResult>;
onCopy: (tripId: number, carry: CopyCarry) => Promise<CopyResult>;
/** The notes and tags the selection carries, so the picker can offer them. */
carryOptions?: CopyCarryOptions;
onClose: () => void;
t: TranslationFn;
/** True when nothing is selected: a pick then does nothing (the desktop dialog's guard). */
@@ -43,19 +57,32 @@ export function filterTripOptions(trips: TripOption[], search: string): TripOpti
* clears the search; a pick copies the selected places and turns the server's dedup
* result into copied / skipped duplicates toasts before closing.
*/
export function useTripCopyPicker({ open, onCopy, onClose, t, emptySelection = false }: TripCopyPickerOptions) {
export function useTripCopyPicker({
open,
onCopy,
onClose,
t,
emptySelection = false,
carryOptions,
}: TripCopyPickerOptions) {
const toast = useToast();
const { language } = useTranslation();
const [trips, setTrips] = useState<TripOption[]>([]);
const [loading, setLoading] = useState(false);
const [search, setSearch] = useState('');
const [busyTripId, setBusyTripId] = useState<number | null>(null);
// A personal note or tag stays in the list unless the reader takes it along on purpose.
const [includeNotes, setIncludeNotes] = useState(false);
const [tagIds, setTagIds] = useState<number[]>([]);
const toggleTag = (id: number) => setTagIds((ids) => (ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id]));
useEffect(() => {
if (!open) return;
let cancelled = false;
setLoading(true);
setSearch('');
setIncludeNotes(false);
setTagIds([]);
tripsApi
.list()
.then((res: { trips?: TripOption[] }) => {
@@ -85,7 +112,12 @@ export function useTripCopyPicker({ open, onCopy, onClose, t, emptySelection = f
if (busyTripId != null || emptySelection) return;
setBusyTripId(tripId);
try {
const res = await onCopy(tripId);
const carry: CopyCarry = {};
if (includeNotes && carryOptions?.hasNotes) carry.include_notes = true;
const offered = new Set(carryOptions?.tags.map((tag) => tag.id) ?? []);
const tags = tagIds.filter((id) => offered.has(id));
if (tags.length) carry.tag_ids = tags;
const res = await onCopy(tripId, carry);
if (res.copied > 0) toast.success(t('collections.copiedCount', { count: res.copied }));
if (res.skipped.length > 0) toast.info(t('collections.skippedDuplicates', { count: res.skipped.length }));
if (res.copied === 0 && res.skipped.length === 0) toast.info(t('collections.copyNothing'));
@@ -97,5 +129,20 @@ export function useTripCopyPicker({ open, onCopy, onClose, t, emptySelection = f
}
};
return { loading, search, setSearch, filtered, busyTripId, dateRange, handleCopy };
const offersCarry = !!carryOptions && (carryOptions.hasNotes || carryOptions.tags.length > 0);
return {
loading,
search,
setSearch,
filtered,
busyTripId,
dateRange,
handleCopy,
offersCarry,
includeNotes,
setIncludeNotes,
tagIds,
toggleTag,
};
}
@@ -0,0 +1,25 @@
import { useCallback } from 'react';
import { useMap } from 'react-leaflet';
import { usePlaceNameLayout, usePlaceNamesSetting } from './usePlaceNameLayout';
/**
* The Leaflet map's wiring for the place names (#2796): its container, and a layout
* after every zoom or move ends. Renders nothing; it lives inside the MapContainer
* only to reach the map.
*/
export function LeafletPlaceNames() {
const map = useMap();
const enabled = usePlaceNamesSetting();
const getContainer = useCallback(() => map.getContainer(), [map]);
const listen = useCallback(
(run: () => void) => {
map.on('zoomend moveend', run);
return () => {
map.off('zoomend moveend', run);
};
},
[map]
);
usePlaceNameLayout(enabled, getContainer, listen);
return null;
}
+7 -17
View File
@@ -44,7 +44,9 @@ import 'leaflet.markercluster/dist/MarkerCluster.Default.css'
import { mapsApi } from '../../api/client'
import { AssistantMapLeaflet } from './AssistantMapLeaflet'
import PlaceHoverCard from './PlaceHoverCard'
import { ratingBadgeHtml } from './ratingBadge'
import { cornerBadgeHtml } from './ratingBadge'
import { tagPlaceName } from './placeNameLabels'
import { LeafletPlaceNames } from './LeafletPlaceNames'
import ReservationOverlay from './ReservationOverlay'
import { PluginMapMarkers } from './MapPluginMarkers'
import { PluginMapLayers } from './MapPluginLayers'
@@ -163,22 +165,7 @@ function createPlaceIcon(place, orderNumbers, isSelected) {
// Number badges (bottom-right), or the rating where there are none: a numbered stop
// is one already planned into a day, and the rating answers the question asked before
// that. The two never want the same corner at the same time.
let badgeHtml = look.showRating ? ratingBadgeHtml((place as { rating_avg?: number | null }).rating_avg) : ''
if (orderNumbers && orderNumbers.length > 0) {
const label = orderNumbers.join(' · ')
badgeHtml = `<span style="
position:absolute;bottom:-4px;right:-4px;
min-width:18px;height:${orderNumbers.length > 1 ? 16 : 18}px;border-radius:${orderNumbers.length > 1 ? 8 : 9}px;
padding:0 ${orderNumbers.length > 1 ? 4 : 3}px;
background:rgba(255,255,255,0.94);
border:1.5px solid rgba(0,0,0,0.15);
box-shadow:0 1px 4px rgba(0,0,0,0.18);
display:flex;align-items:center;justify-content:center;
font-size:${orderNumbers.length > 1 ? 7.5 : 9}px;font-weight:800;color:#111827;
font-family:var(--font-system);line-height:1;
box-sizing:border-box;white-space:nowrap;
">${label}</span>`
}
const badgeHtml = cornerBadgeHtml(orderNumbers, (place as { rating_avg?: number | null }).rating_avg, look.showRating, -4)
// Prefer base64 data URLs (no zoom lag); also accept same-origin proxy + uploaded
// custom images (#1136) as a fallback while the thumb is still being generated
@@ -552,6 +539,7 @@ const MemoMarker = memo(function MemoMarker({
// and it is rebuilt whenever the icon changes (selection, day number),
// so the wiring is redone on every add rather than once on mount.
add: (e: any) => {
tagPlaceName(e.target.getElement(), place.name, isSelected ? 2 : orderNumbers?.length ? 1 : 0)
cleanupRef.current?.()
cleanupRef.current = draggable ? wireDraggablePin(e.target.getElement() as HTMLElement, place.id, map) : null
},
@@ -573,6 +561,7 @@ function plannerWaypointPinCss(size: number, selected: boolean): string {
export const MapView = memo(function MapView({
places = [],
placeNames = false,
dayPlaces = [],
route = null,
// One colour pair per entry of `route`, or absent for the blue the route has always
@@ -946,6 +935,7 @@ export const MapView = memo(function MapView({
<MapClickHandler onClick={onMapClick} />
<MapContextMenuHandler onContextMenu={onMapContextMenu} />
<CameraHoverGuard movingRef={mapMovingRef} onMoveStart={clearHover} onZoom={setMapZoom} />
{placeNames && <LeafletPlaceNames />}
<ViewportController onViewportChange={onViewportChange} />
<PoiDropTarget onPoiDropOnRoute={onPoiDropOnRoute} />
<LeafletLocationLayer position={userPosition} mode={trackingMode} />
+7 -17
View File
@@ -47,7 +47,7 @@ import { useDawarichTrailGL } from './useDawarichTrailGL'
import { bindDayBoundaryDrag } from './dayBoundaryDrag'
import NightPauseTooltip from './NightPauseTooltip'
import PlaceHoverCard from './PlaceHoverCard'
import { ratingBadgeHtml } from './ratingBadge'
import { cornerBadgeHtml } from './ratingBadge'
import type { Poi } from './poiCategories'
import { poiPinParts } from './poiMarker'
import { addGpxTrackLayers, GPX_HIT_LAYER_ID, hasGpxTrackLayers, selectGpxTrack, setGpxTracks } from './gpxTrackLayers'
@@ -58,6 +58,8 @@ import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../../constants/mapDefault
import { alongShortestArc, computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport'
import { onRealWorld } from '../../utils/worldCopy'
import { bindPoiDropTarget } from './poiDropTarget'
import { tagPlaceName } from './placeNameLabels'
import { useGlPlaceNames } from './usePlaceNameLayout'
import {
PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID, PLACE_CLUSTER_SOURCE_ID,
addPlaceClusterLayers, drawClusterBubbles, expandCluster,
@@ -144,22 +146,7 @@ function createMarkerElement(place: Place & PlaceMarkerFlags & { category_color?
// Same corner, same rule as the Leaflet map: numbers when the place is planned into a
// day, the rating when it is not.
let badgeHtml = look.showRating ? ratingBadgeHtml((place as { rating_avg?: number | null }).rating_avg) : ''
if (orderNumbers && orderNumbers.length > 0) {
const label = orderNumbers.join(' · ')
badgeHtml = `<span style="
position:absolute;bottom:-2px;right:-2px;
min-width:18px;height:${orderNumbers.length > 1 ? 16 : 18}px;border-radius:${orderNumbers.length > 1 ? 8 : 9}px;
padding:0 ${orderNumbers.length > 1 ? 4 : 3}px;
background:rgba(255,255,255,0.94);
border:1.5px solid rgba(0,0,0,0.15);
box-shadow:0 1px 4px rgba(0,0,0,0.18);
display:flex;align-items:center;justify-content:center;
font-size:${orderNumbers.length > 1 ? 7.5 : 9}px;font-weight:800;color:#111827;
font-family:var(--font-system);line-height:1;
box-sizing:border-box;white-space:nowrap;
">${label}</span>`
}
const badgeHtml = cornerBadgeHtml(orderNumbers, (place as { rating_avg?: number | null }).rating_avg, look.showRating, -2)
const wrap = document.createElement('div')
// Do NOT set `position: relative` here — GL map libraries ship
@@ -368,6 +355,7 @@ function plannerWaypointPinCss(size: number, selected: boolean): string {
export function MapViewGL({
places = NO_PLACES,
placeNames = false,
dayPlaces = NO_PLACES,
tripId,
routeVias = NO_ROUTE_VIAS,
@@ -457,6 +445,7 @@ export function MapViewGL({
const enableMapbox3d = !isMapLibre && mapbox3d
const [mapReady, setMapReady] = useState(false)
const [readyMap, setReadyMap] = useState<FerrataGlMap | null>(null) // the ready map, read without touching mapRef
useGlPlaceNames(placeNames ? readyMap : null) // place names beside the pins (#2796)
// Hover tooltip — a cursor-following name/category/address card, matching the
// Leaflet map's overlay exactly (no anchored popup, no photo thumbnail).
const [hoverPlace, setHoverPlace] = useState<MapHoverInfo | null>(null)
@@ -1490,6 +1479,7 @@ export function MapViewGL({
const photoUrl = placePhotoUrl(place, photoUrls)
const selected = place.id === selectedPlaceId
const el = createMarkerElement(place as Place & PlaceMarkerFlags & { category_color?: string; category_icon?: string }, photoUrl, orderNumbers, selected)
tagPlaceName(el, place.name, selected ? 2 : orderNumbers?.length ? 1 : 0)
// Drag onto a day in the plan (#891). Markers are rebuilt from scratch
// on every reconcile, so the listeners go with the element and need no
// teardown of their own.
@@ -0,0 +1,29 @@
// FE-MAP-PLACENAMESPILL-001 to FE-MAP-PLACENAMESPILL-002
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { useSettingsStore } from '../../store/settingsStore';
import { PlaceNamesPill } from './PlaceNamesPill';
describe('PlaceNamesPill', () => {
it('FE-MAP-PLACENAMESPILL-001: switches the place names setting on and off', async () => {
const updateSetting = vi.fn(async (key: string, value: unknown) => {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, [key]: value } }));
});
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: false }, updateSetting }));
render(<PlaceNamesPill />);
fireEvent.click(screen.getByRole('button', { name: 'Show place names' }));
expect(updateSetting).toHaveBeenCalledWith('map_place_labels', true);
expect(await screen.findByRole('button', { name: 'Hide place names' })).toHaveAttribute('aria-pressed', 'true');
});
it('FE-MAP-PLACENAMESPILL-002: a save that fails turns the switch back', async () => {
const updateSetting = vi.fn(async (key: string, value: unknown) => {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, [key]: value } }));
throw new Error('Error saving setting');
});
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: false }, updateSetting }));
render(<PlaceNamesPill />);
fireEvent.click(screen.getByRole('button', { name: 'Show place names' }));
await waitFor(() => expect(useSettingsStore.getState().settings.map_place_labels).toBe(false));
expect(screen.getByRole('button', { name: 'Show place names' })).toHaveAttribute('aria-pressed', 'false');
});
});
@@ -0,0 +1,37 @@
import { Type } from 'lucide-react';
import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import { useToast } from '../shared/Toast';
import { MapTogglePill } from './MapTogglePill';
import { usePlaceNamesSetting } from './usePlaceNameLayout';
/**
* Turns the place names beside the trip map's pins on and off (#2796). The choice is
* the reader's own setting, so it holds on every trip and on the other device too.
*/
export function PlaceNamesPill() {
const { t } = useTranslation();
const on = usePlaceNamesSetting();
const updateSetting = useSettingsStore((s) => s.updateSetting);
const toast = useToast();
// The switch flips at once; a save that fails turns it back and says so.
const toggle = async () => {
try {
await updateSetting('map_place_labels', !on);
} catch (err) {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: on } }));
toast.error(err instanceof Error ? err.message : t('common.error'));
}
};
return (
<MapTogglePill
active={on}
onToggle={() => {
void toggle();
}}
label={on ? t('map.placeNames.hide') : t('map.placeNames.show')}
testId="place-names-pill"
icon={<Type size={17} strokeWidth={2} />}
/>
);
}
@@ -42,6 +42,8 @@ export interface RouteSegment {
export interface MapViewProps {
places?: Place[];
/** The trip map offers place names beside the pins, shown while the reader's setting is on (#2796). */
placeNames?: boolean;
dayPlaces?: Place[];
// Enables the plugin map contributions (markers + layers). Absent on surfaces
// without a trip (CollectionMap), which naturally excludes them — same rule as
@@ -0,0 +1,131 @@
// FE-MAP-PLACENAMES-001 to FE-MAP-PLACENAMES-005: the place names beside the trip map's pins (#2796).
import { afterEach, describe, expect, it } from 'vitest';
import { controlBoxes, layoutPlaceNames, tagPlaceName } from './placeNameLabels';
type Rect = { left: number; top: number; width: number; height: number };
/** jsdom lays nothing out, so every element answers the box it was given. */
function place(el: Element, r: Rect): void {
el.getBoundingClientRect = () =>
({ ...r, right: r.left + r.width, bottom: r.top + r.height, x: r.left, y: r.top, toJSON: () => ({}) }) as DOMRect;
}
function mapWith(pins: { name: string; priority: 0 | 1 | 2; at: Rect; label: Rect }[]): HTMLElement {
const container = document.createElement('div');
place(container, { left: 0, top: 0, width: 800, height: 600 });
document.body.appendChild(container);
for (const pin of pins) {
const el = document.createElement('div');
place(el, pin.at);
tagPlaceName(el, pin.name, pin.priority);
container.appendChild(el);
// The label is made on the first layout; it gets its box the moment it is added.
const original = el.appendChild.bind(el);
el.appendChild = <T extends Node>(node: T): T => {
if (node instanceof HTMLElement) place(node, pin.label);
return original(node);
};
}
return container;
}
const labels = (c: HTMLElement) => Array.from(c.querySelectorAll<HTMLElement>('.trek-place-name'));
afterEach(() => {
document.body.innerHTML = '';
});
describe('place names on the map', () => {
it('FE-MAP-PLACENAMES-001: every tagged pin gets its name as text, nothing as markup', () => {
const c = mapWith([
{
name: '<b>Senso-ji</b>',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
},
]);
layoutPlaceNames(c, true);
expect(labels(c)).toHaveLength(1);
expect(labels(c)[0].textContent).toBe('<b>Senso-ji</b>');
expect(c.querySelector('b')).toBeNull();
});
it('FE-MAP-PLACENAMES-002: of two colliding names the selected one stays', () => {
const c = mapWith([
{
name: 'Plain',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
},
{
name: 'Picked',
priority: 2,
at: { left: 10, top: 60, width: 20, height: 20 },
label: { left: 40, top: 14, width: 80, height: 16 },
},
]);
layoutPlaceNames(c, true);
const [plain, picked] = labels(c);
expect(picked.hasAttribute('data-hidden')).toBe(false);
expect(plain.hasAttribute('data-hidden')).toBe(true);
});
it('FE-MAP-PLACENAMES-003: a name that would cover another pin, a control or run off the map is hidden', () => {
const c = mapWith([
{
name: 'Covers a pin',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
},
{
name: 'Neighbour',
priority: 0,
at: { left: 60, top: 8, width: 20, height: 20 },
label: { left: 300, top: 300, width: 40, height: 16 },
},
{
name: 'Edge',
priority: 0,
at: { left: 760, top: 200, width: 20, height: 20 },
label: { left: 786, top: 202, width: 80, height: 16 },
},
{
name: 'Under control',
priority: 0,
at: { left: 400, top: 500, width: 20, height: 20 },
label: { left: 426, top: 502, width: 80, height: 16 },
},
]);
layoutPlaceNames(c, true, [{ left: 450, top: 490, right: 520, bottom: 530 }]);
const hidden = labels(c).map((l) => l.hasAttribute('data-hidden'));
expect(hidden).toEqual([true, false, true, true]);
});
it('FE-MAP-PLACENAMES-004: switched off, the names go away again', () => {
const c = mapWith([
{
name: 'Senso-ji',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
},
]);
layoutPlaceNames(c, true);
layoutPlaceNames(c, false);
expect(labels(c)).toHaveLength(0);
layoutPlaceNames(null, true);
});
it('FE-MAP-PLACENAMES-005: control boxes are read off the elements the selector finds', () => {
const c = document.createElement('div');
const btn = document.createElement('button');
place(btn, { left: 5, top: 6, width: 30, height: 30 });
c.appendChild(btn);
expect(controlBoxes(c, 'button')).toEqual([{ left: 5, top: 6, right: 35, bottom: 36 }]);
expect(controlBoxes(null, 'button')).toEqual([]);
});
});
@@ -0,0 +1,105 @@
import './placeNames.css';
/**
* Place names beside the trip map's markers (#2796, discussion #1603).
*
* Both renderers draw a place as a DOM marker, so the name rides along as a child of
* that element and pans with it for free. The renderer only tags the element
* (`tagPlaceName`); `layoutPlaceNames` then adds or removes the labels and thins
* them out: a label that would cover a kept label, another place's marker or one of
* the map's controls is hidden, the selected place and the planned stops win first.
* A place folded into a cluster has no element, so it has no label either.
*/
export const PLACE_NAME_ATTR = 'data-place-name';
const PRIORITY_ATTR = 'data-place-name-priority';
const LABEL_CLASS = 'trek-place-name';
const HIDDEN_ATTR = 'data-hidden';
/** How strongly a label holds its spot when two collide: selected, then planned, then the rest. */
export type PlaceNamePriority = 0 | 1 | 2;
export function tagPlaceName(el: HTMLElement | null | undefined, name: string, priority: PlaceNamePriority): void {
if (!el) return;
el.setAttribute(PLACE_NAME_ATTR, name);
el.setAttribute(PRIORITY_ATTR, String(priority));
}
interface Box {
left: number;
top: number;
right: number;
bottom: number;
}
// Overlaps nothing: a marker that was not measured cannot push a label away.
const NO_BOX: Box = { left: Infinity, top: Infinity, right: -Infinity, bottom: -Infinity };
const overlaps = (a: Box, b: Box, gap = 2): boolean =>
a.left < b.right + gap && b.left < a.right + gap && a.top < b.bottom + gap && b.top < a.bottom + gap;
function ensureLabel(marker: HTMLElement): HTMLElement {
const name = marker.getAttribute(PLACE_NAME_ATTR) ?? '';
let label = marker.querySelector<HTMLElement>(`:scope > .${LABEL_CLASS}`);
if (!label) {
label = document.createElement('span');
label.className = LABEL_CLASS;
label.setAttribute('aria-hidden', 'true');
marker.appendChild(label);
}
// textContent, never markup: the name is the user's own text.
if (label.textContent !== name) label.textContent = name;
return label;
}
/**
* Brings the labels inside `container` in line with `enabled` and hides the ones that
* collide. `avoid` is what no label may cover beyond the markers themselves: the map's
* controls, measured by the caller. Cheap enough to run after every move and zoom.
*/
export function layoutPlaceNames(container: HTMLElement | null, enabled: boolean, avoid: readonly Box[] = []): void {
if (!container) return;
const markers = Array.from(container.querySelectorAll<HTMLElement>(`[${PLACE_NAME_ATTR}]`));
if (!enabled) {
container.querySelectorAll(`.${LABEL_CLASS}`).forEach((label) => label.remove());
return;
}
const frame = container.getBoundingClientRect();
const markerBoxes = new Map<HTMLElement, Box>();
for (const marker of markers) {
const r = marker.getBoundingClientRect();
markerBoxes.set(marker, { left: r.left, top: r.top, right: r.right, bottom: r.bottom });
}
const ordered = markers
.map((marker, index) => ({ marker, index, priority: Number(marker.getAttribute(PRIORITY_ATTR) ?? 0) }))
.sort((a, b) => b.priority - a.priority || a.index - b.index);
const kept: Box[] = [];
for (const { marker } of ordered) {
const label = ensureLabel(marker);
label.removeAttribute(HIDDEN_ATTR);
const r = label.getBoundingClientRect();
const box: Box = { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
const offFrame =
box.left < frame.left || box.right > frame.right || box.top < frame.top || box.bottom > frame.bottom;
const coversMarker = markers.some(
(other) => other !== marker && overlaps(box, markerBoxes.get(other) ?? NO_BOX, 0)
);
const collides =
offFrame || coversMarker || kept.some((k) => overlaps(box, k)) || avoid.some((a) => overlaps(box, a, 0));
if (collides) label.setAttribute(HIDDEN_ATTR, '');
else kept.push(box);
}
}
/** The boxes of the map controls inside `container` that a label must leave free. */
export function controlBoxes(container: HTMLElement | null, selector: string): Box[] {
if (!container) return [];
return Array.from(container.querySelectorAll<HTMLElement>(selector)).map((el) => {
const r = el.getBoundingClientRect();
return { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
});
}
/** What no label may cover: the controls drawn over the map beside it. */
export const PLACE_NAMES_CONTROLS = '.leaflet-control, .mapboxgl-ctrl, .maplibregl-ctrl, button';
+28
View File
@@ -0,0 +1,28 @@
/* Place names beside the trip map's markers (#2796). The label hangs off the marker
element, so it pans with it; placeNameLabels.ts decides which ones stay visible. */
.trek-place-name {
position: absolute;
left: calc(100% + 6px); /* rtl-lint-disable: map geometry, the label sits beside the pin on screen */
top: 50%;
transform: translateY(-50%);
max-width: 13em;
padding: 2px 8px;
border-radius: 999px;
background: var(--sidebar-bg);
-webkit-backdrop-filter: blur(12px) saturate(180%);
backdrop-filter: blur(12px) saturate(180%);
box-shadow: var(--sidebar-shadow);
color: var(--text-primary);
font-family: var(--font-system);
font-size: calc(11.5px * var(--fs-scale-caption, 1));
font-weight: 600;
line-height: 1.35;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
pointer-events: none;
}
.trek-place-name[data-hidden] {
visibility: hidden;
}
+16 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { ratingBadgeHtml } from './ratingBadge'
import { cornerBadgeHtml, ratingBadgeHtml } from './ratingBadge'
describe('ratingBadgeHtml', () => {
it('FE-MAP-RATINGBADGE-001: shows a whole rating without a decimal', () => {
@@ -21,3 +21,18 @@ describe('ratingBadgeHtml', () => {
expect(ratingBadgeHtml(0)).toBe('')
})
})
describe('cornerBadgeHtml', () => {
it('FE-MAP-RATINGBADGE-101: day numbers win the corner over the rating', () => {
const html = cornerBadgeHtml([2, 5], 4.5, true, -4);
expect(html).toContain('2 · 5');
expect(html).toContain('bottom:-4px;right:-4px');
expect(html).not.toContain('#f59e0b');
});
it('FE-MAP-RATINGBADGE-102: without numbers the rating shows when asked for, else nothing', () => {
expect(cornerBadgeHtml(null, 4, true, -2)).toContain('#f59e0b');
expect(cornerBadgeHtml([], 4, false, -2)).toBe('');
expect(cornerBadgeHtml([3], null, true, -2)).toContain('height:18px');
});
});
+27
View File
@@ -25,3 +25,30 @@ export function ratingBadgeHtml(rating: number | null | undefined): string {
box-sizing:border-box;white-space:nowrap;
">${label}</span>`;
}
/**
* The marker's corner badge: the day numbers of a planned stop, or else its rating.
* Both maps draw the same badge; only how far it hangs off the pin differs, since the
* GL wrapper is the pin's full outer size and the Leaflet one is not.
*/
export function cornerBadgeHtml(
orderNumbers: readonly number[] | null | undefined,
rating: number | null | undefined,
showRating: boolean,
inset: number
): string {
if (!orderNumbers || orderNumbers.length === 0) return showRating ? ratingBadgeHtml(rating) : '';
const many = orderNumbers.length > 1;
return `<span style="
position:absolute;bottom:${inset}px;right:${inset}px;
min-width:18px;height:${many ? 16 : 18}px;border-radius:${many ? 8 : 9}px;
padding:0 ${many ? 4 : 3}px;
background:rgba(255,255,255,0.94);
border:1.5px solid rgba(0,0,0,0.15);
box-shadow:0 1px 4px rgba(0,0,0,0.18);
display:flex;align-items:center;justify-content:center;
font-size:${many ? 7.5 : 9}px;font-weight:800;color:#111827;
font-family:var(--font-system);line-height:1;
box-sizing:border-box;white-space:nowrap;
">${orderNumbers.join(' · ')}</span>`;
}
@@ -0,0 +1,57 @@
// FE-MAP-PLACENAMESHOOK-001 to FE-MAP-PLACENAMESHOOK-002
import { renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useSettingsStore } from '../../store/settingsStore';
import { tagPlaceName } from './placeNameLabels';
import { useGlPlaceNames } from './usePlaceNameLayout';
beforeEach(() => {
vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => {
cb(0);
return 1;
});
});
afterEach(() => {
vi.restoreAllMocks();
document.body.innerHTML = '';
});
function glMap() {
const container = document.createElement('div');
const pin = document.createElement('div');
tagPlaceName(pin, 'Senso-ji', 0);
container.appendChild(pin);
document.body.appendChild(container);
const handlers = new Set<() => void>();
return {
container,
map: {
getContainer: () => container,
on: vi.fn((_t: 'moveend', fn: () => void) => handlers.add(fn)),
off: vi.fn((_t: 'moveend', fn: () => void) => handlers.delete(fn)),
},
handlers,
};
}
describe('useGlPlaceNames', () => {
it('FE-MAP-PLACENAMESHOOK-001: with the setting on, names are laid out and follow every move', () => {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: true } }));
const { container, map, handlers } = glMap();
const { unmount } = renderHook(() => useGlPlaceNames(map));
expect(container.querySelector('.trek-place-name')?.textContent).toBe('Senso-ji');
expect(map.on).toHaveBeenCalledWith('moveend', expect.any(Function));
unmount();
expect(handlers.size).toBe(0);
});
it('FE-MAP-PLACENAMESHOOK-002: with the setting off, or no map yet, there are no names', () => {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: false } }));
const { container, map } = glMap();
renderHook(() => useGlPlaceNames(map));
expect(container.querySelector('.trek-place-name')).toBeNull();
expect(map.on).not.toHaveBeenCalled();
renderHook(() => useGlPlaceNames(null));
});
});
@@ -0,0 +1,71 @@
import { useCallback, useEffect } from 'react';
import { useSettingsStore } from '../../store/settingsStore';
import { controlBoxes, layoutPlaceNames, PLACE_NAMES_CONTROLS } from './placeNameLabels';
/** Whether the trip map shows its place names, the reader's own setting (#2796). */
export function usePlaceNamesSetting(): boolean {
return useSettingsStore((s) => s.settings.map_place_labels) === true;
}
/**
* Keeps the place names of one map laid out: once after every change of the markers
* (a cluster opening, a day picked) and after every move or zoom the renderer reports
* through `listen`. Both renderers share it; only how they report a move differs.
*/
export function usePlaceNameLayout(
enabled: boolean,
/** The element the markers live in, or null while the map is not up yet. Keep it stable (useCallback). */
getContainer: () => HTMLElement | null,
/** Subscribes `run` to the renderer's move and zoom ends and returns the unsubscribe. Keep it stable too. */
listen: (run: () => void) => () => void
): void {
useEffect(() => {
const container = getContainer();
if (!container) return;
let frame = 0;
const run = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
const scope = container.parentElement ?? container;
const controls = enabled ? controlBoxes(scope, PLACE_NAMES_CONTROLS).filter((b) => b.right > b.left) : [];
layoutPlaceNames(container, enabled, controls);
});
};
run();
if (!enabled) return () => cancelAnimationFrame(frame);
const stop = listen(run);
// A marker added or taken away (a cluster splitting, a selection rebuilding the pins).
const observer = new MutationObserver(run);
observer.observe(container, { childList: true, subtree: true });
return () => {
cancelAnimationFrame(frame);
stop();
observer.disconnect();
};
}, [enabled, getContainer, listen]);
}
/** The part of either GL map the names need. */
interface NamesGlMap {
getContainer: () => HTMLElement;
on: (type: 'moveend', listener: () => void) => unknown;
off: (type: 'moveend', listener: () => void) => unknown;
}
/** The GL map's wiring: its container, and a layout after every move or zoom ends. */
export function useGlPlaceNames(map: NamesGlMap | null): void {
const enabled = usePlaceNamesSetting();
const getContainer = useCallback(() => map?.getContainer() ?? null, [map]);
const listen = useCallback(
(run: () => void) => {
if (!map) return () => {};
map.on('moveend', run);
return () => {
map.off('moveend', run);
};
},
[map]
);
usePlaceNameLayout(enabled, getContainer, listen);
}
@@ -20,3 +20,8 @@ export function addressWithoutCoordinates(place: {
}): boolean {
return !!place.address?.trim() && !(isCoordinate(place.lat) && isCoordinate(place.lng));
}
/** Whether a place has a full coordinate pair to put it on the map. */
export function hasCoordinates(place: { lat?: Coordinate; lng?: Coordinate }): boolean {
return isCoordinate(place.lat) && isCoordinate(place.lng);
}
@@ -0,0 +1,59 @@
// FE-COMP-LOCSEARCH-001 to FE-COMP-LOCSEARCH-004: the position search behind the
// "find the position" rows of the saved place editors (#2837).
import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { searchMapSpots } from '../../repo/mapMatchRepo';
import { useLocationSearch } from './useLocationSearch';
vi.mock('../../repo/mapMatchRepo', () => ({ searchMapSpots: vi.fn() }));
vi.mock('../../hooks/usePlaceLanguage', () => ({ usePlaceLanguage: () => 'de' }));
const SPOT = { lat: 35.66, lng: 139.7, label: 'Kissa Sakaiki, Shibuya', address: 'Shibuya' };
beforeEach(() => {
vi.mocked(searchMapSpots).mockReset();
});
describe('useLocationSearch', () => {
it('FE-COMP-LOCSEARCH-001: searches in the place language and lists the hits', async () => {
vi.mocked(searchMapSpots).mockResolvedValue([SPOT]);
const { result } = renderHook(() => useLocationSearch(vi.fn()));
act(() => result.current.setQuery('kissa'));
await act(() => result.current.search());
expect(searchMapSpots).toHaveBeenCalledWith('kissa', 'de');
expect(result.current.results).toEqual([SPOT]);
expect(result.current.noResults).toBe(false);
expect(result.current.searching).toBe(false);
});
it('FE-COMP-LOCSEARCH-002: a blank query asks nothing', async () => {
const { result } = renderHook(() => useLocationSearch(vi.fn()));
act(() => result.current.setQuery(' '));
await act(() => result.current.search());
expect(searchMapSpots).not.toHaveBeenCalled();
});
it('FE-COMP-LOCSEARCH-003: no hits and a failed search both say there was nothing', async () => {
vi.mocked(searchMapSpots).mockResolvedValueOnce([]).mockRejectedValueOnce(new Error('down'));
const { result } = renderHook(() => useLocationSearch(vi.fn()));
act(() => result.current.setQuery('nowhere'));
await act(() => result.current.search());
expect(result.current.noResults).toBe(true);
await act(() => result.current.search());
expect(result.current.noResults).toBe(true);
expect(result.current.results).toEqual([]);
});
it('FE-COMP-LOCSEARCH-004: a pick hands the spot over and clears the search', async () => {
vi.mocked(searchMapSpots).mockResolvedValue([SPOT]);
const onPick = vi.fn();
const { result } = renderHook(() => useLocationSearch(onPick));
act(() => result.current.setQuery('kissa'));
await act(() => result.current.search());
act(() => result.current.pick(SPOT));
expect(onPick).toHaveBeenCalledWith(SPOT);
expect(result.current.query).toBe('');
expect(result.current.results).toEqual([]);
});
});
@@ -0,0 +1,49 @@
import { useState } from 'react';
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage';
import { type MapMatch, searchMapSpots } from '../../repo/mapMatchRepo';
/**
* A small map search that only looks for a position (#2837). It backs the
* "find the position" row in the place editors that have no search of their own:
* nothing is written until the reader picks a hit, and the pick hands back only
* coordinates and an address, so a typed name or a custom note stays as it was.
* Desktop and phone render their own markup over it.
*/
export function useLocationSearch(onPick: (spot: MapMatch) => void) {
const placeLang = usePlaceLanguage();
const [query, setQuery] = useState('');
const [results, setResults] = useState<MapMatch[]>([]);
const [searching, setSearching] = useState(false);
// An empty answer has to say so; a list that just stays closed reads as a broken button.
const [noResults, setNoResults] = useState(false);
const search = async () => {
if (!query.trim() || searching) return;
setSearching(true);
setNoResults(false);
try {
const spots = await searchMapSpots(query, placeLang);
setResults(spots);
setNoResults(spots.length === 0);
} catch {
setResults([]);
setNoResults(true);
} finally {
setSearching(false);
}
};
const reset = () => {
setQuery('');
setResults([]);
setNoResults(false);
};
const pick = (spot: MapMatch) => {
onPick(spot);
reset();
};
return { query, setQuery, results, searching, noResults, search, pick, reset };
}