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
+47 -1
View File
@@ -1,4 +1,4 @@
// FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-035
// FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-038
//
// The Collections addon wrapper is thin, but every method encodes a URL, a verb and a
// request-body shape that the server contract depends on. These tests drive each method
@@ -370,4 +370,50 @@ describe('collectionsApi', () => {
expect(requestBody).toEqual({ gpx: '<gpx/>', file_name: 'tokyo.gpx' })
expect(res).toEqual({ file, skipped: 0, track_points: 12 })
})
it('FE-API-COLLECTIONS-036: copyToTrip() passes the notes and tags a copy takes along (D9)', async () => {
server.use(http.post(`${BASE}/copy-to-trip`, record({ copied: 1, skipped: [], created: [] })))
await collectionsApi.copyToTrip({ trip_id: 7, place_ids: [10], include_notes: true, tag_ids: [4] })
expect(requestBody).toEqual({ trip_id: 7, place_ids: [10], include_notes: true, tag_ids: [4] })
})
it('FE-API-COLLECTIONS-037: reorderPlaces() puts the ordered ids of a list (PLC-03)', async () => {
let method = ''
server.use(
http.put(`${BASE}/:id/places/reorder`, async (info) => {
method = info.request.method
return record({ success: true })(info)
}),
)
const res = await collectionsApi.reorderPlaces(1, [11, 10])
expect(method).toBe('PUT')
expect(requestUrl).toContain(`${BASE}/1/places/reorder`)
expect(requestBody).toEqual({ orderedIds: [11, 10] })
expect(res).toEqual({ success: true })
})
it('FE-API-COLLECTIONS-038: readMap() uploads the map file as multipart and returns the list file (PLC-22)', async () => {
const read = {
file: { format: 'trek.collection', version: 1, name: 'Lisbon', places: [{ name: 'Miradouro' }] },
folders: ['Views'],
skipped: [{ name: 'Tram 28', folder: null, reason: 'line' }],
}
let upload: File | null = null
server.use(
http.post(`${BASE}/map/read`, async ({ request }) => {
upload = (await request.formData()).get('file') as File | null
return HttpResponse.json(read)
}),
)
const res = await collectionsApi.readMap(new File(['<kml/>'], 'lisbon.kml'))
expect(upload).not.toBeNull()
expect((upload as unknown as File).name).toBe('lisbon.kml')
expect(res).toEqual(read)
})
})
+12
View File
@@ -18,6 +18,8 @@ import type {
CollectionGpxReadRequest,
CollectionGpxReadResult,
CollectionKmlExport,
CollectionMapReadResult,
CollectionPlacesReorderRequest,
CollectionPlaceUpdateRequest,
CollectionCopyToTripRequest,
CollectionInviteRequest,
@@ -76,6 +78,12 @@ export const collectionsApi = {
ax.get(`${base}/${id}/export/gpx`).then((r: AxiosResponse) => r.data),
readGpx: (body: CollectionGpxReadRequest): Promise<CollectionGpxReadResult> =>
ax.post(`${base}/gpx/read`, body satisfies CollectionGpxReadRequest).then((r: AxiosResponse) => r.data),
/** A KML or KMZ map (PLC-22) read by the server into a list file; it writes nothing, importFile(Into) does. */
readMap: (file: File): Promise<CollectionMapReadResult> => {
const fd = new FormData()
fd.append('file', file)
return postMultipart(`${base}/map/read`, fd)
},
/** The same list as pins for Google My Maps (#1866). */
exportKml: (id: number): Promise<CollectionKmlExport> =>
ax.get(`${base}/${id}/export/kml`).then((r: AxiosResponse) => r.data),
@@ -94,6 +102,10 @@ export const collectionsApi = {
reorder: (orderedIds: number[]): Promise<unknown> =>
ax.post(`${base}/reorder`, { orderedIds }).then((r: AxiosResponse) => r.data),
/** A list's places in a new order (PLC-03): every id a place of that list, the ones left out follow. */
reorderPlaces: (id: number, orderedIds: number[]): Promise<{ success: true }> =>
ax.put(`${base}/${id}/places/reorder`, { orderedIds } satisfies CollectionPlacesReorderRequest).then((r: AxiosResponse) => r.data),
savePlace: (body: CollectionSavePlaceRequest): Promise<CollectionSaveResult> =>
ax.post(`${base}/places`, body satisfies CollectionSavePlaceRequest).then((r: AxiosResponse) => r.data),
saveFromTrip: (body: CollectionSaveFromTripRequest): Promise<CollectionSaveResult> =>
@@ -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 };
}
@@ -1,4 +1,4 @@
import { Check, Loader2, MapPin, Search, X, MapPinPlus } from 'lucide-react'
import { Check, Loader2, MapPin, MapPinOff, Search, X, MapPinPlus } from 'lucide-react'
import type { Category, TranslationFn } from '../../../types'
import { STATUS_ORDER } from '../../../pages/collections/collectionsModel'
import MSheet from '../../components/MSheet'
@@ -28,7 +28,7 @@ interface MCollAddSheetProps {
export default function MCollAddSheet({ open, collectionId, collectionName, lists, categories, onClose, onAdded, t }: MCollAddSheetProps) {
const {
query, setQuery, results, setResults, searching, name, setName, address, setAddress, categoryId, setCategoryId,
status, setStatus, description, setDescription, saving, targetId, setTargetId, search, pick, save,
status, setStatus, description, setDescription, saving, targetId, setTargetId, search, pick, save, positionMissing,
} = useAddPlaceToCollection({ variant: 'sheet', open, collectionId, collectionName, lists, t, onClose, onAdded })
return (
@@ -114,6 +114,12 @@ export default function MCollAddSheet({ open, collectionId, collectionName, list
hand-typed place can carry one too (the desktop dialog always could). */}
<Eyebrow className="mb-[6px] mt-[14px]">{t('places.formAddress').toUpperCase()}</Eyebrow>
<input value={address} onChange={e => setAddress(e.target.value)} placeholder={t('places.formAddressPlaceholder')} className={INPUT_CLS} />
{positionMissing && (
<p className="mt-2 flex items-start gap-1.5 text-caption text-m-muted">
<MapPinOff size={13} strokeWidth={2} aria-hidden="true" className="mt-px flex-none text-warning" />
{t('collections.addNoPositionHint')}
</p>
)}
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.category').toUpperCase()}</Eyebrow>
<MCollCategoryPicker categories={categories} value={categoryId} onChange={setCategoryId} t={t} />
@@ -0,0 +1,38 @@
// FE-COMP-COLLOCSEARCH-001 to FE-COMP-COLLOCSEARCH-002
import { fireEvent, render, screen, waitFor } from '../../../../tests/helpers/render';
import { CollectionLocationSearch } from '../../../components/Collections/CollectionLocationSearch';
import { searchMapSpots } from '../../../repo/mapMatchRepo';
import MCollLocationSearch from './MCollLocationSearch';
vi.mock('../../../repo/mapMatchRepo', () => ({ searchMapSpots: vi.fn() }));
const t = (k: string) => k;
const SPOT = { lat: 35.66, lng: 139.7, label: 'Kissa Sakaiki, Shibuya', address: 'Shibuya' };
describe.each([
['desktop', CollectionLocationSearch],
['phone', MCollLocationSearch],
])('the %s position search', (_name, Row) => {
beforeEach(() => vi.mocked(searchMapSpots).mockReset());
it('FE-COMP-COLLOCSEARCH-001: says why the place is not on the map, and once a hit is picked that the save will put it there', () => {
const { rerender } = render(<Row picked={false} onPick={vi.fn()} t={t} />);
expect(screen.getByText('collections.findPositionHint')).toBeInTheDocument();
rerender(<Row picked onPick={vi.fn()} t={t} />);
expect(screen.queryByText('collections.findPositionHint')).toBeNull();
expect(screen.getByRole('status')).toHaveTextContent('collections.findPositionPicked');
});
it('FE-COMP-COLLOCSEARCH-002: searches on submit and hands a picked hit over', async () => {
vi.mocked(searchMapSpots).mockResolvedValue([SPOT]);
const onPick = vi.fn();
render(<Row picked={false} onPick={onPick} t={t} />);
fireEvent.change(screen.getByPlaceholderText('collections.findPositionPlaceholder'), {
target: { value: 'kissa' },
});
fireEvent.click(screen.getByRole('button', { name: 'common.search' }));
fireEvent.click(await screen.findByRole('button', { name: SPOT.label }));
expect(onPick).toHaveBeenCalledWith(SPOT);
await waitFor(() => expect(screen.queryByRole('button', { name: SPOT.label })).toBeNull());
});
});
@@ -0,0 +1,82 @@
import { Loader2, MapPin, MapPinCheck, MapPinOff, Search } from 'lucide-react';
import { useLocationSearch } from '../../../components/shared/useLocationSearch';
import type { MapMatch } from '../../../repo/mapMatchRepo';
import type { TranslationFn } from '../../../types';
import { Eyebrow, INPUT_CLS } from './MCollSheetKit';
interface MCollLocationSearchProps {
picked: boolean;
onPick: (spot: MapMatch) => void;
t: TranslationFn;
}
/**
* The phone twin of the "find the position" row (#2837). The edit sheet has no
* coordinate fields, so before this a saved place without a position could not get
* one on the phone at all. Only a picked hit is sent with the save.
*/
export default function MCollLocationSearch({ picked, onPick, t }: MCollLocationSearchProps) {
const { query, setQuery, results, searching, noResults, search, pick } = useLocationSearch(onPick);
return (
<>
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.findPosition').toUpperCase()}</Eyebrow>
{!picked && (
<p className="mb-2 flex items-start gap-1.5 text-caption text-m-muted">
<MapPinOff size={13} strokeWidth={2} aria-hidden="true" className="mt-px flex-none text-warning" />
{t('collections.findPositionHint')}
</p>
)}
{picked && (
<p className="mb-2 flex items-start gap-1.5 text-caption text-m-muted" role="status">
<MapPinCheck size={13} strokeWidth={2} aria-hidden="true" className="mt-px flex-none text-success" />
{t('collections.findPositionPicked')}
</p>
)}
<form
role="search"
className="flex items-center gap-2"
onSubmit={(e) => {
e.preventDefault();
void search();
}}
>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('collections.findPositionPlaceholder')}
aria-label={t('collections.findPosition')}
enterKeyHint="search"
className={INPUT_CLS}
/>
<button
type="submit"
disabled={!query.trim() || searching}
aria-label={t('common.search')}
className="grid h-10 w-10 flex-none place-items-center rounded-full border border-m-rowbr bg-m-ic text-m-ink disabled:opacity-40"
>
{searching ? <Loader2 size={16} className="animate-spin" /> : <Search size={16} />}
</button>
</form>
{noResults && <p className="mt-2 text-caption text-m-faint">{t('planner.noPlacesFound')}</p>}
{results.length > 0 && (
<ul
className="mt-2 overflow-hidden rounded-xl border border-m-rowbr"
aria-label={t('collections.findPosition')}
>
{results.map((spot, i) => (
<li key={`${spot.lat},${spot.lng},${i}`} className="border-b border-m-rowbr last:border-b-0">
<button
type="button"
onClick={() => pick(spot)}
className="flex w-full items-center gap-2.5 px-3 py-2.5 text-start"
>
<MapPin size={15} className="flex-none text-m-faint" />
<span className="min-w-0 flex-1 truncate text-body text-m-ink">{spot.label}</span>
</button>
</li>
))}
</ul>
)}
</>
);
}
@@ -1,4 +1,5 @@
import { Check, MapPin } from 'lucide-react'
import { Check, GripVertical, MapPin } from 'lucide-react'
import type React from 'react'
import type { CollectionPlace, CollectionStatus } from '@trek/shared'
import type { TranslationFn } from '../../../types'
import { nextStatus } from '../../../pages/collections/collectionsModel'
@@ -12,6 +13,13 @@ interface MCollPlaceRowProps {
onOpen: (id: number) => void
onToggleSelect: (id: number) => void
onSetStatus: (id: number, status: CollectionStatus) => void
/** The drag of the list's own order (#1457), while it may be dragged. */
reorder?: {
handle: React.HTMLAttributes<HTMLElement> & { draggable?: boolean }
row: React.HTMLAttributes<HTMLElement>
dropSide: 'before' | 'after' | null
dragging: boolean
}
t: TranslationFn
}
@@ -24,7 +32,7 @@ interface MCollPlaceRowProps {
* and a third of a narrow window wide, which cut the names short.
*/
export default function MCollPlaceRow({
place, selectMode, selected, canEdit, onOpen, onToggleSelect, onSetStatus, t,
place, selectMode, selected, canEdit, onOpen, onToggleSelect, onSetStatus, reorder, t,
}: MCollPlaceRowProps) {
const cat = categoryMeta(place.category)
const meta = cat ?? UNCATEGORIZED_META
@@ -43,9 +51,21 @@ export default function MCollPlaceRow({
return (
<div
className="mt-2 flex items-center rounded-2xl border border-[color:var(--m-rowbr)] bg-m-sheetop"
className={`relative mt-2 flex items-center rounded-2xl border border-[color:var(--m-rowbr)] bg-m-sheetop${reorder?.dragging ? ' opacity-50' : ''}${reorder?.dropSide === 'before' ? ' before:absolute before:inset-x-3 before:-top-[5px] before:h-0.5 before:rounded-full before:bg-m-act' : ''}${reorder?.dropSide === 'after' ? ' after:absolute after:inset-x-3 after:-bottom-[5px] after:h-0.5 after:rounded-full after:bg-m-act' : ''}`}
style={selected ? { boxShadow: 'inset 0 0 0 1.5px var(--m-act)' } : undefined}
{...reorder?.row}
>
{reorder && (
<span
{...reorder.handle}
role="button"
tabIndex={0}
aria-label={t('collections.reorderHandle', { name: place.name })}
className="flex w-6 flex-none touch-none items-center justify-center self-stretch ps-1 text-m-faint"
>
<GripVertical size={15} />
</span>
)}
<button
type="button"
onClick={() => (selectMode ? onToggleSelect(place.id) : onOpen(place.id))}
@@ -11,6 +11,7 @@ import MSheet from '../../components/MSheet'
import PlaceRating from '../../../components/shared/StarRating'
import MCollCategoryPicker from './MCollCategoryPicker'
import MCollLinksEditor from './MCollLinksEditor'
import MCollLocationSearch from './MCollLocationSearch'
import { STATUS_SPEC } from './collectionsMobileModel'
import { CancelPill, Eyebrow, INPUT_CLS, PrimaryPill, TEXTAREA_CLS } from './MCollSheetKit'
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../../../components/Planner/placeNavigation'
@@ -35,7 +36,7 @@ interface MCollPlaceSheetProps {
labels: CollectionLabel[]
onClose: () => void
onSetStatus: (status: CollectionStatus) => void
onSave: (patch: { name?: string; description?: string | null; notes?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; address?: string | null }) => Promise<void>
onSave: (patch: { name?: string; description?: string | null; notes?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; address?: string | null; lat?: number | null; lng?: number | null }) => Promise<void>
onUploadImage?: (file: File) => Promise<void>
onCopyToTrip: () => void
onRemove: () => void
@@ -57,7 +58,7 @@ export default function MCollPlaceSheet({
const [navOpen, setNavOpen] = useState(false)
const navBtnRef = useRef<HTMLButtonElement | null>(null)
const {
shown: held, editing, setEditing, name, setName, address, setAddress, categoryId, setCategoryId, description, setDescription, notes, setNotes,
shown: held, editing, setEditing, name, setName, address, setAddress, pickPosition, positionPicked, needsPosition, categoryId, setCategoryId, description, setDescription, notes, setNotes,
links, setLinks, labelIds, toggleLabel, saving, imgBusy, cover, assignedLabels, handleImagePick, handleImageRemove, cancelEdit, save,
} = useCollectionPlaceForm({
place, labels, onSave, onUploadImage, t, normalizeLinkUrl, holdLastPlace: true, dropPhotoOnPlaceUpdate: true,
@@ -165,6 +166,7 @@ export default function MCollPlaceSheet({
{/* Address (#1870): free text, same as the add sheet offers */}
<Eyebrow className="mb-[6px] mt-[14px]">{t('places.formAddress').toUpperCase()}</Eyebrow>
<input value={address} onChange={e => setAddress(e.target.value)} placeholder={t('places.formAddressPlaceholder')} className={INPUT_CLS} />
{needsPosition && <MCollLocationSearch picked={positionPicked} onPick={pickPosition} t={t} />}
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.category').toUpperCase()}</Eyebrow>
<MCollCategoryPicker categories={categories} value={categoryId} onChange={setCategoryId} t={t} />
{labels.length > 0 && (
@@ -1,6 +1,7 @@
import { CalendarDays, Copy, Loader2, MapPin, Search, Luggage } from 'lucide-react'
import type { TranslationFn } from '../../../types'
import { useTripCopyPicker } from '../../../components/Collections/useTripCopyPicker'
import { useTripCopyPicker, type CopyCarry, type CopyCarryOptions } from '../../../components/Collections/useTripCopyPicker'
import CopyCarryPanel from '../../../components/Collections/CopyCarryPanel'
import MSheet from '../../components/MSheet'
import { SheetHeader } from './MCollSheetKit'
import MSkeleton from '../../components/MSkeleton'
@@ -8,7 +9,9 @@ import MSkeleton from '../../components/MSkeleton'
interface MCollTripPickerSheetProps {
open: boolean
count: number
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
onClose: () => void
t: TranslationFn
}
@@ -17,9 +20,9 @@ interface MCollTripPickerSheetProps {
* "Copy to trip" trip picker: searchable trip rows; tapping one copies the
* selected places and reconciles the dedup result into toasts.
*/
export default function MCollTripPickerSheet({ open, count, onCopy, onClose, t }: MCollTripPickerSheetProps) {
const { loading, search, setSearch, filtered, busyTripId, dateRange, handleCopy } =
useTripCopyPicker({ open, onCopy, onClose, t })
export default function MCollTripPickerSheet({ open, count, onCopy, carryOptions, onClose, t }: MCollTripPickerSheetProps) {
const { loading, search, setSearch, filtered, busyTripId, dateRange, handleCopy, offersCarry, includeNotes, setIncludeNotes, tagIds, toggleTag } =
useTripCopyPicker({ open, onCopy, onClose, t, carryOptions })
const title = t('collections.copyN', { count })
@@ -37,6 +40,11 @@ export default function MCollTripPickerSheet({ open, count, onCopy, onClose, t }
className="min-w-0 flex-1 bg-transparent font-geist text-[0.78125rem] text-m-ink outline-none placeholder:text-m-faint"
/>
</div>
{offersCarry && carryOptions && (
<div className="mb-3">
<CopyCarryPanel options={carryOptions} includeNotes={includeNotes} onIncludeNotes={setIncludeNotes} tagIds={tagIds} onToggleTag={toggleTag} variant="sheet" t={t} />
</div>
)}
{loading ? (
<MSkeleton variant="rows" count={4} />
) : filtered.length === 0 ? (
@@ -1,8 +1,8 @@
import { ReactNode, useEffect, useState } from 'react'
import { ReactNode, useEffect, useMemo, useState } from 'react'
import { useSearchParams } from 'react-router'
import {
Bookmark, Check, CheckCheck, CheckSquare, ChevronDown, Copy, CopyPlus,
FolderInput, Layers, List, Map as MapIcon, Pencil, Search, Settings2, Shapes, Share2,
FolderInput, Info, Layers, List, Map as MapIcon, Pencil, Search, Settings2, Shapes, Share2,
Tag, Tags, Trash2,
} from 'lucide-react'
import type { CollectionStatus } from '@trek/shared'
@@ -25,6 +25,7 @@ import MCollInvites from './MCollInvites'
import { STATUS_SPEC, categoryMeta } from './collectionsMobileModel'
import MConfirmSheet from '../settings/MConfirmSheet'
import MCollListNav from './MCollListNav'
import { usePlaceReorder } from '../../../components/Collections/usePlaceReorder'
import { useIsSplit } from '../../../hooks/sizeClass'
import { skipNextRouteTransition } from '../../routeTransition'
import MSkeleton from '../../components/MSkeleton'
@@ -92,6 +93,9 @@ function EmptyNote({ icon, scene, title }: { icon?: ReactNode; scene?: TrekScene
export default function MCollections() {
const c = useCollections()
const { t } = c
// The list's own order (#1457): the grip on each card, while the list may be dragged.
const placeOrder = useMemo(() => c.visiblePlaces.map(p => p.id), [c.visiblePlaces])
const reorder = usePlaceReorder(placeOrder, c.reorderEnabled, c.commitOrder)
const [drop, setDrop] = useState(false)
// With room for two panes the lists stand in a column beside the places
@@ -522,6 +526,12 @@ export default function MCollections() {
<EmptyNote icon={<Search size={19} strokeWidth={1.8} />} title={t('collections.empty.noMatchTitle')} />
) : (
// Two columns of rows where the page has the room for them.
<>
{c.reorderBlocked && (
<p className="mt-2 flex items-center gap-1.5 px-1 text-caption text-m-muted">
<Info size={13} className="flex-none" /> {t('collections.reorderBlocked')}
</p>
)}
<div className="wide:grid wide:grid-cols-[repeat(auto-fill,minmax(min(100%,380px),1fr))] wide:gap-x-3">
{c.visiblePlaces.map(p => (
<MCollPlaceRow
@@ -533,10 +543,17 @@ export default function MCollections() {
onOpen={c.setSelectedPlaceId}
onToggleSelect={c.toggleSelect}
onSetStatus={(id: number, status: CollectionStatus) => c.handleStatusChange(id, status)}
reorder={reorder.enabled ? {
handle: reorder.handleProps(p.id),
row: reorder.rowProps(p.id),
dropSide: reorder.dropSide(p.id),
dragging: reorder.dragId === p.id,
} : undefined}
t={t}
/>
))}
</div>
</>
)
)}
@@ -626,6 +643,7 @@ export default function MCollections() {
open={c.copyIds != null}
count={c.copyIds?.length ?? 0}
onCopy={c.handleCopyToTrip}
carryOptions={c.copyCarryOptions}
onClose={c.closeCopy}
t={t}
/>
@@ -3,6 +3,7 @@ import { MapViewAuto } from '../../../../components/Map/MapViewAuto'
import { MapCompassPill, type CompassMap } from '../../../../components/Map/MapCompassPill'
import { MAP_LAYER_SWITCHER_INSET, MAP_ROUND_CONTROL_SIZE } from '../../../../components/Map/MapLayerSwitcher'
import { TripRouteOverviewPill, TripRouteOverviewPanel } from '../../../../components/Map/TripRouteOverview'
import { PlaceNamesPill } from '../../../../components/Map/PlaceNamesPill'
import { DawarichTrailPill } from '../../../../components/Map/DawarichTrailPill'
import PoiCategoryPill from '../../../../components/Map/PoiCategoryPill'
import { usePoiExplore } from '../../../../components/Map/usePoiExplore'
@@ -388,6 +389,7 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
className="pointer-events-none invisible absolute start-0 top-0 pb-[env(safe-area-inset-bottom,0px)] pt-[env(safe-area-inset-top,0px)]"
/>
<MapViewAuto
placeNames
tripId={planner.tripId}
dawarichTrack={planner.dawarichTrail.track}
places={stageMap ? stagePlaces : planner.mapPlaces}
@@ -537,6 +539,7 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
{!planner.roadtripActive && (
<TripRouteOverviewPill active={planner.overviewShown} onToggle={planner.toggleOverview} />
)}
<PlaceNamesPill />
</div>
)}
</div>
+5
View File
@@ -97,6 +97,9 @@ function CollectionsPageDesktop(): React.ReactElement {
onOpenPlace={openPlace}
onStatusChange={c.canEdit ? c.handleStatusChange : undefined}
onToggleSelect={c.toggleSelect}
reorderEnabled={c.reorderEnabled}
reorderBlocked={c.reorderBlocked}
onReorder={c.commitOrder}
t={t}
/>
)
@@ -391,6 +394,7 @@ function CollectionsPageDesktop(): React.ReactElement {
lists={c.writableLists}
defaultListId={typeof c.activeId === 'number' ? c.activeId : null}
onReadGpx={c.handleReadGpx}
onReadMap={c.handleReadMap}
onClose={() => c.setShowImportFile(false)}
t={t}
/>
@@ -415,6 +419,7 @@ function CollectionsPageDesktop(): React.ReactElement {
onClose={c.closeCopy}
placeIds={c.copyIds ?? []}
onCopy={c.handleCopyToTrip}
carryOptions={c.copyCarryOptions}
t={t}
/>
@@ -182,14 +182,14 @@ describe('collectionsModel', () => {
expect(sortPlaces(places).map(p => p.id)).toEqual([2, 3, 1]);
});
it('FE-COLLECTIONS-MODEL-011: ties on sort_order fall back to created_at newest-first', () => {
it('FE-COLLECTIONS-MODEL-011: ties on sort_order fall back to oldest first, then id, as the server orders them', () => {
const places = [
cp({ id: 4, name: 'D', status: 'idea', sort_order: 0, created_at: '2025-02-01T00:00:00Z' }),
cp({ id: 1, name: 'A', status: 'idea', sort_order: 0, created_at: '2025-01-01T00:00:00Z' }),
cp({ id: 2, name: 'B', status: 'idea', sort_order: 0, created_at: '2025-03-01T00:00:00Z' }),
cp({ id: 3, name: 'C', status: 'idea', sort_order: 0, created_at: '2025-02-01T00:00:00Z' }),
];
// newest created_at first
expect(sortPlaces(places).map(p => p.id)).toEqual([2, 3, 1]);
expect(sortPlaces(places).map(p => p.id)).toEqual([1, 3, 4, 2]);
});
it('FE-COLLECTIONS-MODEL-012: missing sort_order is treated as 0', () => {
@@ -12,17 +12,18 @@ import { textMatchesSearch } from '../../utils/placeSearch'
// draw it too); re-exported here for the page and its views.
export { STATUS_META, STATUS_ORDER, nextStatus } from '../../components/Collections/collectionStatus'
/** Order the places for display. 'default' keeps the saved order (sort_order,
* then newest first); 'name_asc' sorts alphabetically by name (locale-aware). */
/** Order the places for display. 'default' is the list's own order, the one the
* server keeps and the reader can drag (#1457): sort_order, then oldest first, then
* id, exactly as the server answers; 'name_asc' sorts by name (locale-aware). */
export function sortPlaces(places: CollectionPlace[], mode: CollectionSortMode = 'default'): CollectionPlace[] {
if (mode === 'name_asc') {
return [...places].sort((a, b) => a.name.localeCompare(b.name))
}
return [...places].sort((a, b) => {
const so = (a.sort_order ?? 0) - (b.sort_order ?? 0)
if (so !== 0) return so
return (b.created_at ?? '').localeCompare(a.created_at ?? '')
})
return [...places].sort((a, b) =>
(a.sort_order ?? 0) - (b.sort_order ?? 0)
|| (a.created_at ?? '').localeCompare(b.created_at ?? '')
|| a.id - b.id,
)
}
/** Apply the active status filter + free-text search (name/address/notes) +
@@ -80,6 +80,7 @@ function makeStore() {
moveToList: vi.fn(async (_ids: number[], _target: number) => {}),
duplicateToList: vi.fn(async (_ids: number[], _target: number) => {}),
setSelectedIds: vi.fn((_ids: number[]) => {}),
reorderPlaces: vi.fn(async (_ids: number[]) => {}),
createLabel: vi.fn(async (_name: string, _color?: string) => {}),
updateLabel: vi.fn(async (_id: number, _body: Record<string, unknown>) => {}),
deleteLabel: vi.fn(async (_id: number) => {}),
@@ -826,7 +827,7 @@ describe('useCollections — detail panel and copy to trip', () => {
let res: { copied: number } | undefined
await act(async () => { res = await result.current.handleCopyToTrip(20) })
expect(store.copyToTrip).toHaveBeenCalledWith(20, [4, 5])
expect(store.copyToTrip).toHaveBeenCalledWith(20, [4, 5], undefined, {})
expect(res?.copied).toBe(2)
expect(store.clearSelection).toHaveBeenCalled()
})
@@ -834,7 +835,7 @@ describe('useCollections — detail panel and copy to trip', () => {
it('FE-PAGE-COLL-070: copying without an open modal sends an empty id list', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleCopyToTrip(20) })
expect(store.copyToTrip).toHaveBeenCalledWith(20, [])
expect(store.copyToTrip).toHaveBeenCalledWith(20, [], undefined, {})
expect(store.clearSelection).not.toHaveBeenCalled()
})
})
@@ -1406,4 +1407,40 @@ describe('useCollections — route that is an invite (#2645)', () => {
const drop = setSearchParams.mock.calls[0]?.[0] as (prev: URLSearchParams) => URLSearchParams
expect(drop(new URLSearchParams('place=34&x=1')).toString()).toBe('x=1')
})
it('FE-PAGE-COLL-096: a list of its own, in its own order, with nothing filtered can be dragged; a search says why not', async () => {
store.collections = [collection({ id: 1 })]
store.activeId = 1
store.places = [place({ id: 4 }), place({ id: 5 })]
const { result, rerender } = await setup()
expect(result.current.reorderEnabled).toBe(true)
expect(result.current.reorderBlocked).toBe(false)
act(() => result.current.commitOrder([5, 4]))
expect(store.reorderPlaces).toHaveBeenCalledWith([5, 4])
store.search = 'kissa'
rerender()
expect(result.current.reorderEnabled).toBe(false)
expect(result.current.reorderBlocked).toBe(true)
store.activeId = 'all'
rerender()
expect(result.current.reorderBlocked).toBe(false)
})
it('FE-PAGE-COLL-097: the copy picker is offered the notes and the tags of the places about to be copied', async () => {
store.places = [
place({ id: 4, notes: ' ', tags: [{ id: 7, name: 'Coffee', color: '#f00' }] } as Partial<CollectionPlace> & { id: number }),
place({ id: 5, notes: 'Go early', tags: [{ id: 7, name: 'Coffee', color: '#f00' }, { id: 8, name: 'Late' }] } as Partial<CollectionPlace> & { id: number }),
place({ id: 6, notes: 'Not picked' }),
]
store.selectedIds = [4, 5]
const { result } = await setup()
expect(result.current.copyCarryOptions).toEqual({ hasNotes: false, tags: [] })
act(() => result.current.openCopyForSelection())
expect(result.current.copyCarryOptions).toEqual({
hasNotes: true,
tags: [{ id: 7, name: 'Coffee', color: '#f00' }, { id: 8, name: 'Late', color: undefined }],
})
await act(async () => { await result.current.handleCopyToTrip(20, { include_notes: true }) })
expect(store.copyToTrip).toHaveBeenCalledWith(20, [4, 5], undefined, { include_notes: true })
})
})
+27 -5
View File
@@ -10,6 +10,7 @@ import { useToast } from '../../components/shared/Toast'
import { collectionsApi } from '../../api/collections'
import { downloadCollectionFile, downloadCollectionGpx, downloadCollectionKml, type CollectionExportFormat } from '../../components/Collections/collectionFile'
import { getApiErrorMessage } from '../../types'
import type { CopyCarry, CopyCarryOptions } from '../../components/Collections/useTripCopyPicker'
import { canAddToCollection, canRemoveFromCollection, collectionRoleOf } from '../../utils/collectionAccess'
import { addListener, removeListener } from '../../api/websocket'
import { useCollectionStore, ALL_SAVED } from '../../store/collectionStore'
@@ -66,7 +67,7 @@ export function useCollections() {
loadAll, setActive, refreshActive, loadCollection,
deleteCollection,
setStatus, updatePlace, uploadPlaceImage, ratePlace, deletePlace, deleteMany, copyToTrip, clearSelection,
moveToList, duplicateToList, setSelectedIds,
moveToList, duplicateToList, setSelectedIds, reorderPlaces,
createLabel, updateLabel, deleteLabel, assignLabels,
acceptInvite, declineInvite,
setView, setStatusFilter, setCategoryFilter, setRatingFilter, setLabelFilter, setSortMode, setSearch, setSelectedPlaceId, setSelectMode, toggleSelect,
@@ -254,6 +255,16 @@ export function useCollections() {
() => sortPlaces(filterPlaces(places, statusFilter, search, categoryFilter, isAllSaved ? [] : labelFilter, ratingFilter), sortMode),
[places, statusFilter, search, categoryFilter, isAllSaved, labelFilter, ratingFilter, sortMode],
)
// The list's own order can be dragged (#1457) only while every place of it is on
// screen in that order: a single list, its own sort, no search or filter hiding
// places, edit rights, not mid selection. With a filter on, the list says why not.
const orderShown = typeof activeId === 'number' && sortMode === 'default' && canEdit && !selectMode
const orderFiltered = !!search.trim() || statusFilter !== 'all' || categoryFilter !== 'all' || ratingFilter !== 'all' || labelFilter.length > 0
const reorderEnabled = orderShown && !orderFiltered
const reorderBlocked = orderShown && orderFiltered
const commitOrder = useCallback((orderedIds: number[]) => {
reorderPlaces(orderedIds).catch((err: unknown) => toast.error(getApiErrorMessage(err, t('common.error'))))
}, [reorderPlaces, toast, t])
// 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.
@@ -327,6 +338,8 @@ export function useCollections() {
(gpx: string, fileName: string) => collectionsApi.readGpx({ gpx, file_name: fileName }),
[],
)
/** A KML or KMZ map read the same way (PLC-22): the server reads it, nothing is written yet. */
const handleReadMap = useCallback((file: File) => collectionsApi.readMap(file), [])
/**
* Read a chosen file and create the list it describes.
@@ -551,9 +564,17 @@ export function useCollections() {
const closeCopy = useCallback(() => setCopyIds(null), [])
const handleCopyToTrip = useCallback(async (tripId: number) => {
// What the places about to be copied carry, so the picker can offer to take it along.
const copyCarryOptions = useMemo<CopyCarryOptions>(() => {
const picked = places.filter(p => (copyIds ?? []).includes(p.id))
const tags = new Map<number, CopyCarryOptions['tags'][number]>()
for (const p of picked) for (const tag of p.tags ?? []) if (tag.id != null && tag.name) tags.set(tag.id, { id: tag.id, name: tag.name, color: tag.color })
return { hasNotes: picked.some(p => !!p.notes?.trim()), tags: [...tags.values()] }
}, [places, copyIds])
const handleCopyToTrip = useCallback(async (tripId: number, carry: CopyCarry = {}) => {
const ids = copyIds ?? []
const res = await copyToTrip(tripId, ids)
const res = await copyToTrip(tripId, ids, undefined, carry)
if (selectMode) clearSelection()
return res
}, [copyIds, copyToTrip, selectMode, clearSelection])
@@ -565,7 +586,8 @@ export function useCollections() {
mapLocked, toggleMapLocked,
// store data
collections, ownedLists, sharedLists, activeCollection, isAllSaved, isOwner,
myRole, canEdit, canDelete,
copyCarryOptions,
myRole, canEdit, canDelete, reorderEnabled, reorderBlocked, commitOrder,
canShare, shareMemberCount,
activeId, places, visiblePlaces, mappable, hasMappable, members, incomingInvites, routeInvite, orderedInvites, counts,
view, statusFilter, categoryFilter, categoryOptions, ratingFilter, sortMode, search, selectedPlaceId, selectMode, selectedIds,
@@ -582,7 +604,7 @@ export function useCollections() {
showAddPlace, setShowAddPlace, handlePlaceAdded,
showImport, setShowImport,
exporting, handleExportList,
showImportFile, setShowImportFile, handleImportFile, handleImportFileInto, handleReadGpx,
showImportFile, setShowImportFile, handleImportFile, handleImportFileInto, handleReadGpx, handleReadMap,
writableLists,
confirmDeleteList, setConfirmDeleteList,
mobileRailOpen, setMobileRailOpen,
@@ -3,6 +3,7 @@ import { createPortal } from 'react-dom'
import { MapViewAuto as MapView } from '../../components/Map/MapViewAuto'
import { MapCompassPill, type CompassMap } from '../../components/Map/MapCompassPill'
import { TripRouteOverviewPill, TripRouteOverviewPanel, TRIP_OVERVIEW_INSET } from '../../components/Map/TripRouteOverview'
import { PlaceNamesPill } from '../../components/Map/PlaceNamesPill'
import { DawarichTrailPill } from '../../components/Map/DawarichTrailPill'
import PoiCategoryPill from '../../components/Map/PoiCategoryPill'
import ActivityCompareLegend from '../../components/Tours/activity/ActivityCompareLegend'
@@ -86,6 +87,7 @@ export function PlanMapStage({
return (
<>
<MapView
placeNames
tripId={tripId}
dawarichTrack={dawarichTrail.track}
dawarichHiddenDates={dawarichHiddenDates}
@@ -198,6 +200,7 @@ export function PlanMapStage({
{!roadtripActive && (
<TripRouteOverviewPill active={overviewShown} onToggle={toggleOverview} />
)}
<PlaceNamesPill />
{/* Stays in road-trip mode, unlike the overview: the route that was
actually driven is the thing you most want beside the planned
one. It is drawn, never applied. Correcting the plan from the
+25 -1
View File
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { mapsApi } from '../api/client';
import { isEffectivelyOffline } from '../sync/networkMode';
import { findOnMap, stayQueries } from './mapMatchRepo';
import { findOnMap, searchMapSpots, stayQueries } from './mapMatchRepo';
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) }));
vi.mock('../api/client', () => ({ mapsApi: { search: vi.fn() } }));
@@ -67,3 +67,27 @@ describe('finding a stay on the map', () => {
expect(mapsApi.search).not.toHaveBeenCalled();
});
});
describe('searching spots to pick from', () => {
it('FE-MAP-MATCH-101: lists every hit with coordinates and leaves the others out', async () => {
vi.mocked(mapsApi.search).mockResolvedValue({
places: [
{ name: 'Kissa Sakaiki', address: 'Shibuya, Tokyo', lat: 35.66, lng: 139.7 },
{ name: 'No position', address: 'Somewhere' },
{ name: 'Null Island', lat: 0, lng: 0 },
],
} as never);
await expect(searchMapSpots(' kissa ', 'ja')).resolves.toEqual([
{ lat: 35.66, lng: 139.7, label: 'Kissa Sakaiki, Shibuya, Tokyo', address: 'Shibuya, Tokyo' },
{ lat: 0, lng: 0, label: 'Null Island' },
]);
expect(mapsApi.search).toHaveBeenCalledWith('kissa', 'ja');
});
it('FE-MAP-MATCH-102: a blank query or no connection asks nothing', async () => {
await expect(searchMapSpots(' ')).resolves.toEqual([]);
vi.mocked(isEffectivelyOffline).mockReturnValue(true);
await expect(searchMapSpots('Tokyo')).resolves.toEqual([]);
expect(mapsApi.search).not.toHaveBeenCalled();
});
});
+25 -7
View File
@@ -34,14 +34,32 @@ export async function findOnMap(queries: string[], lang?: string): Promise<MapMa
for (const query of queries) {
const res = lang ? await mapsApi.search(query, lang) : await mapsApi.search(query);
for (const row of res?.places ?? []) {
const place = row as { lat?: unknown; lng?: unknown; name?: unknown; address?: unknown };
const lat = typeof place.lat === 'number' ? place.lat : NaN;
const lng = typeof place.lng === 'number' ? place.lng : NaN;
if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue;
const parts = [place.name, place.address].filter((v): v is string => typeof v === 'string' && v.trim() !== '');
const address = typeof place.address === 'string' && place.address.trim() ? place.address : undefined;
return { lat, lng, label: parts.join(', ') || query, ...(address ? { address } : {}) };
const match = toMatch(row, query);
if (match) return match;
}
}
return null;
}
/** One search hit as a match, or null when it has no coordinates to put on the map. */
function toMatch(row: unknown, query: string): MapMatch | null {
const place = row as { lat?: unknown; lng?: unknown; name?: unknown; address?: unknown };
const lat = typeof place.lat === 'number' ? place.lat : NaN;
const lng = typeof place.lng === 'number' ? place.lng : NaN;
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
const parts = [place.name, place.address].filter((v): v is string => typeof v === 'string' && v.trim() !== '');
const address = typeof place.address === 'string' && place.address.trim() ? place.address : undefined;
return { lat, lng, label: parts.join(', ') || query, ...(address ? { address } : {}) };
}
/**
* Every spot the map search found for `query` that has coordinates, for a picker
* that lets the reader choose the right one. Online only, like findOnMap: offline
* the answer is an empty list, not a guess.
*/
export async function searchMapSpots(query: string, lang?: string): Promise<MapMatch[]> {
const q = query.trim();
if (!q || isEffectivelyOffline()) return [];
const res = lang ? await mapsApi.search(q, lang) : await mapsApi.search(q);
return (res?.places ?? []).map((row) => toMatch(row, q)).filter((m): m is MapMatch => m !== null);
}
+52 -1
View File
@@ -1,4 +1,4 @@
// FE-STORE-COLLECTION-001 to FE-STORE-COLLECTION-063
// FE-STORE-COLLECTION-001 to FE-STORE-COLLECTION-067
//
// The store owns the optimistic updates (status, labels, reorder, bulk delete) and the
// reload chains that follow every mutation, so the API layer is mocked here and the
@@ -20,6 +20,7 @@ vi.mock('../api/collections', () => ({
uploadCover: vi.fn(),
remove: vi.fn(),
reorder: vi.fn(),
reorderPlaces: vi.fn(),
savePlace: vi.fn(),
updatePlace: vi.fn(),
uploadPlaceImage: vi.fn(),
@@ -76,6 +77,7 @@ beforeEach(() => {
vi.mocked(collectionsApi.uploadCover).mockResolvedValue(listA)
vi.mocked(collectionsApi.remove).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.reorder).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.reorderPlaces).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.savePlace).mockResolvedValue({ place: buildPlace() })
vi.mocked(collectionsApi.updatePlace).mockResolvedValue(buildPlace())
vi.mocked(collectionsApi.uploadPlaceImage).mockResolvedValue(buildPlace())
@@ -1056,3 +1058,52 @@ describe('collectionStore — "All saved" load pressure (#2559)', () => {
expect(store().activeId).toBe(ALL_SAVED)
})
})
describe('collectionStore: copy notes and tags, place order (D9, PLC-03)', () => {
it('FE-STORE-COLLECTION-064: copyToTrip() sends the notes and tags the copy takes along', async () => {
await store().copyToTrip(7, [10], undefined, { include_notes: true, tag_ids: [4] })
expect(collectionsApi.copyToTrip).toHaveBeenCalledWith({
trip_id: 7,
place_ids: [10],
force: undefined,
include_notes: true,
tag_ids: [4],
})
})
it('FE-STORE-COLLECTION-065: reorderPlaces() moves the rows and their positions before the request answers', async () => {
useCollectionStore.setState({
activeId: 1,
places: [buildPlace({ id: 10 }), buildPlace({ id: 11 }), buildPlace({ id: 12 })],
})
let during: Array<[number, number | undefined]> = []
vi.mocked(collectionsApi.reorderPlaces).mockImplementation(async () => {
during = store().places.map((p): [number, number | undefined] => [p.id, p.sort_order])
return { success: true }
})
await store().reorderPlaces([12, 10])
expect(collectionsApi.reorderPlaces).toHaveBeenCalledWith(1, [12, 10])
// The place the order left out follows the named ones.
expect(during).toEqual([[12, 0], [10, 1], [11, 2]])
expect(collectionsApi.get).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-066: a refused reorder reloads the list and reaches the caller', async () => {
useCollectionStore.setState({ activeId: 1, places: [buildPlace({ id: 10 }), buildPlace({ id: 11 })] })
vi.mocked(collectionsApi.reorderPlaces).mockRejectedValue(new Error('403'))
await expect(store().reorderPlaces([11, 10])).rejects.toThrow('403')
expect(collectionsApi.get).toHaveBeenCalledWith(1)
})
it('FE-STORE-COLLECTION-067: reorderPlaces() does nothing on the "All saved" union', async () => {
useCollectionStore.setState({ activeId: ALL_SAVED, places: [buildPlace({ id: 10 })] })
await store().reorderPlaces([10])
expect(collectionsApi.reorderPlaces).not.toHaveBeenCalled()
})
})
+30 -3
View File
@@ -13,11 +13,15 @@ import type {
CollectionPlaceUpdateRequest,
CollectionLabel,
CollectionLabelUpdateRequest,
CollectionCopyToTripRequest,
} from '@trek/shared'
/** A pending invitation the current user has received (derived server-side). */
export type IncomingCollectionInvite = CollectionListResponse['incomingInvites'][number]
/** What a copy into a trip takes along besides the places (D9): left out, neither notes nor tags. */
type CopyToTripCarry = Pick<CollectionCopyToTripRequest, 'include_notes' | 'tag_ids'>
/** Sentinel id for the client-side "All saved" union pseudo-list. */
export const ALL_SAVED = 'all' as const
export type ActiveCollectionId = number | typeof ALL_SAVED | null
@@ -64,7 +68,13 @@ interface CollectionState {
ratePlace: (placeId: number, rating: number | null) => Promise<void>
deletePlace: (placeId: number) => Promise<void>
deleteMany: (ids: number[]) => Promise<void>
copyToTrip: (tripId: number, placeIds: number[], force?: boolean) => Promise<{ copied: number; skipped: { id: number; name: string }[] }>
copyToTrip: (
tripId: number,
placeIds: number[],
force?: boolean,
carry?: CopyToTripCarry,
) => Promise<{ copied: number; skipped: { id: number; name: string }[] }>
reorderPlaces: (orderedIds: number[]) => Promise<void>
moveToList: (placeIds: number[], targetId: number) => Promise<void>
duplicateToList: (placeIds: number[], targetId: number) => Promise<void>
@@ -343,11 +353,28 @@ export const useCollectionStore = create<CollectionState>((set, get) => ({
await get().loadAll()
},
copyToTrip: async (tripId: number, placeIds: number[], force?: boolean) => {
const res = await collectionsApi.copyToTrip({ trip_id: tripId, place_ids: placeIds, force })
copyToTrip: async (tripId: number, placeIds: number[], force?: boolean, carry?: CopyToTripCarry) => {
const res = await collectionsApi.copyToTrip({ trip_id: tripId, place_ids: placeIds, force, ...carry })
return res
},
// The open list's places in a new order (PLC-03). Optimistic: the rows move and take their new
// positions at once; a refusal reloads the list as the server has it, then reaches the caller.
reorderPlaces: async (orderedIds: number[]) => {
const listId = get().activeId
if (typeof listId !== 'number') return
const position = new Map(orderedIds.map((id, index) => [id, index]))
const rest = get().places.filter(p => !position.has(p.id))
const named = orderedIds.map(id => get().places.find(p => p.id === id)).filter((p): p is CollectionPlace => !!p)
set({ places: [...named, ...rest].map((p, index) => ({ ...p, sort_order: index })) })
try {
await collectionsApi.reorderPlaces(listId, orderedIds)
} catch (err) {
await get().refreshActive()
throw err
}
},
// Move the selected places into another list (re-point collection_id). They
// leave the current list, so drop them locally + refresh.
moveToList: async (placeIds: number[], targetId: number) => {
+19
View File
@@ -672,3 +672,22 @@
.trek-dash .col-drawer-head button { width: 40px; height: 40px; display: grid; place-items: center; border-radius: var(--r-sm); color: var(--ink-2); }
.trek-dash .col-drawer-head button:hover { background: var(--surface-2); color: var(--ink); }
@media (max-width: 720px) { .trek-dash .col-drawer { padding-top: calc(16px + env(safe-area-inset-top, 0px)); } }
/* The list's own order (#1457): a grip in the row's start padding, shown on hover and
focus, and a line where a dragged place would land. */
.trek-dash .col-lrow.can-reorder { position: relative; }
.trek-dash .col-lgrip {
position: absolute; inset-block: 0; inset-inline-start: 0; width: 16px;
display: grid; place-items: center; color: var(--ink-3); opacity: 0; cursor: grab;
border-radius: var(--r-md) 0 0 var(--r-md); transition: opacity .12s;
}
.trek-dash .col-lgrip:active { cursor: grabbing; }
.trek-dash .col-lrow:hover .col-lgrip, .trek-dash .col-lgrip:focus-visible { opacity: 1; }
.trek-dash .col-lrow.dragging { opacity: .45; }
.trek-dash .col-lrow.drop-before::before, .trek-dash .col-lrow.drop-after::after {
content: ''; position: absolute; inset-inline: 8px; height: 2px; border-radius: 2px;
background: var(--accent); pointer-events: none;
}
.trek-dash .col-lrow.drop-before::before { top: -5px; }
.trek-dash .col-lrow.drop-after::after { bottom: -5px; }
.trek-dash .col-reorder-note { display: flex; align-items: center; gap: 6px; margin: 0 2px 8px; font-size: 12px; color: var(--ink-3); }
+4
View File
@@ -159,6 +159,10 @@ export interface Settings {
/** Places not planned into any day are drawn as small markers without their photo (#2024). */
map_compact_unplanned?: boolean
map_booking_labels?: boolean
/** The names of a trip's places stand beside their pins on the trip map (PLC-05); absent reads as off. */
map_place_labels?: boolean
/** Place names beside the trip map's markers (#2796). */
map_place_labels?: boolean
map_poi_pill_enabled?: boolean
/** The trip map pans to where the assistant searches and suggests places; absent reads as on. */
assistant_map_follow?: boolean