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
+12
View File
@@ -291,6 +291,18 @@
"desktop": ["src/components/Collections/CollectionPlaceDetail.tsx"],
"mobile": ["src/mobile/screens/collections/MCollPlaceSheet.tsx"]
},
{
"feature": "Collection place order",
"hooks": ["src/components/Collections/usePlaceReorder.ts"],
"desktop": ["src/components/Collections/CollectionList.tsx"],
"mobile": ["src/mobile/screens/collections/MCollections.tsx"]
},
{
"feature": "Collection place position search",
"hooks": ["src/components/shared/useLocationSearch.ts"],
"desktop": ["src/components/Collections/CollectionLocationSearch.tsx"],
"mobile": ["src/mobile/screens/collections/MCollLocationSearch.tsx"]
},
{
"feature": "Collection sharing",
"hooks": ["src/components/Collections/useCollectionSharing.ts"],
+2 -2
View File
@@ -5,9 +5,9 @@
"src/components/Admin/AdminPluginsPanel.tsx": 1265,
"src/components/Budget/CostsPanel.test.tsx": 2725,
"src/components/Budget/CostsPanel.tsx": 1607,
"src/components/Map/MapView.tsx": 1200,
"src/components/Map/MapView.tsx": 1191,
"src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2116,
"src/components/Map/MapViewGL.tsx": 2107,
"src/components/Planner/DayDetailPanel.test.tsx": 2331,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2908,
+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
@@ -113,7 +113,7 @@ describe('MCollTripPickerSheet', () => {
const { onCopy, onClose } = setup()
fireEvent.click(await screen.findByRole('button', { name: /Japan 2020/ }))
await waitFor(() => expect(onClose).toHaveBeenCalled())
expect(onCopy).toHaveBeenCalledWith(1)
expect(onCopy).toHaveBeenCalledWith(1, {})
expect(addToast).toHaveBeenCalledWith('Copied 1 place', 'success', undefined)
})
+1 -1
View File
@@ -27,7 +27,7 @@
"src/nest/roadtrip/google-route.mcp.ts": 2,
"src/nest/roadtrip/roadtrip.mcp.ts": 16,
"src/nest/school-holidays/school-holidays.mcp.ts": 2,
"src/nest/settings/settings.mcp.ts": 21,
"src/nest/settings/settings.mcp.ts": 17,
"src/nest/share/share.mcp.ts": 7,
"src/nest/tags/tags.mcp.ts": 4,
"src/nest/todo/todo.mcp.ts": 14,
+1 -1
View File
@@ -8,7 +8,7 @@
"src/nest/atlas/atlas.service.ts": 1166,
"src/nest/auth/auth.service.ts": 1115,
"src/nest/budget/budget.service.ts": 1607,
"src/nest/collections/collections.service.ts": 1414,
"src/nest/collections/collections.service.ts": 1410,
"src/nest/doc-sync/doc-sync.service.ts": 1060,
"src/nest/doc-sync/providers/synology-drive.client.ts": 1160,
"src/nest/journey/journey-domain.service.ts": 1659,
@@ -81,9 +81,8 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
* per the plan's own "do not collapse" instruction for that pair).
* `saveFromTripPlaces`'s own call site passes `status: 'idea', links:
* null` explicitly, reproducing the literal exactly. `em.insert()`
* returns the generated id; `sort_order` is never in the column list
* either statement writes, so the table's own `DEFAULT 0` fills it,
* matching both legacy statements.
* returns the generated id. `sort_order` is the caller's: a new place goes
* after the last one of its list (PLC-03), read in the same transaction.
*/
async insertSavedPlace(row: {
collection_id: number;
@@ -108,6 +107,7 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
source_trip_id: number | null;
source_place_id: number | null;
links: string | null;
sort_order: number;
}): Promise<number> {
return await this.insert({
collection: row.collection_id,
@@ -132,9 +132,35 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
source_trip_id: row.source_trip_id,
source_place_id: row.source_place_id,
links: row.links,
sort_order: row.sort_order,
});
}
/** A list's place ids in the list's order: `sort_order`, then `created_at`, then `id`, as listPlaceRows reads them. */
async idsInOrder(collectionId: number): Promise<number[]> {
const rows = await this.db_()
.selectFrom('collection_places')
.select('id')
.where('collection_id', '=', collectionId)
.orderBy((eb) => eb.fn.coalesce('sort_order', eb.val(0)))
.orderBy((eb) => eb.fn.coalesce('created_at', eb.val('')))
.orderBy('id')
.execute();
return rows.map((r) => r.id);
}
/** `UPDATE collection_places SET sort_order=? WHERE id=? AND collection_id=?`, per place, inside the caller's transaction. */
async setSortOrders(collectionId: number, orderedIds: number[]): Promise<void> {
for (const [position, id] of orderedIds.entries()) {
await this.db_()
.updateTable('collection_places')
.set({ sort_order: position })
.where('id', '=', id)
.where('collection_id', '=', collectionId)
.execute();
}
}
// ---------------------------------------------------------------------
// CL47/CL48 — updatePlace
// ---------------------------------------------------------------------
@@ -180,6 +206,7 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
currency: string | null;
collection_id: number;
owner_id: number;
sort_order: number;
}>,
): Promise<void> {
if (Object.keys(write).length === 0) return;
@@ -350,20 +377,6 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
.executeTakeFirst();
}
// ---------------------------------------------------------------------
// CL67 — copyToTrip's per-source tag read (loop, TX)
// ---------------------------------------------------------------------
/** CL67 (`copyToTrip`, loop, TX) — `SELECT tag_id FROM collection_place_tags WHERE collection_place_id=?`. Pivot table, Kysely. */
async tagIdsFor(collectionPlaceId: number): Promise<number[]> {
const rows = await this.db_()
.selectFrom('collection_place_tags')
.select('tag_id')
.where('collection_place_id', '=', collectionPlaceId)
.execute();
return rows.map((r) => r.tag_id);
}
// ---------------------------------------------------------------------
// CL69 — findMembership (library-wide membership lookup)
// ---------------------------------------------------------------------
@@ -10,7 +10,7 @@ import { PLACE_IMAGE_FILE_FILTER } from '../common/place-image-upload';
import { ResponseContract } from '../common/response-contract';
import { rowId } from '../common/row-id.pipe';
import { SpoolCleanupInterceptor } from '../common/spool-cleanup.interceptor';
import { CollectionGpxError } from '../place-import/place-import.types';
import { CollectionGpxError, CollectionMapError } from '../place-import/place-import.types';
import { placeImageUrl } from '../places/place-image';
import { PlaceRatingDto } from '../places/places.dto';
import { StorageService } from '../storage/storage.service';
@@ -38,6 +38,7 @@ import {
CollectionImportDto,
CollectionImportIntoDto,
CollectionGpxReadDto,
CollectionPlacesReorderDto,
} from './collections.dto';
import { CollectionsService } from './collections.service';
import {
@@ -58,12 +59,19 @@ import {
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { collectionKmlExportSchema } from '@trek/shared';
import {
collectionKmlExportSchema,
collectionMapReadResultSchema,
MAX_COLLECTION_MAP_UPLOAD_BYTES,
successResponseSchema,
} from '@trek/shared';
import type { Options } from 'multer';
import { memoryStorage, type Options } from 'multer';
import path from 'path';
export const MAX_COVER_SIZE = 20 * 1024 * 1024;
// A map file is read and dropped, never stored: held in memory under the trip map import's cap.
const MAP_UPLOAD = { storage: memoryStorage(), limits: { fileSize: MAX_COLLECTION_MAP_UPLOAD_BYTES } };
// Duplicated on purpose from trips.controller.ts (historical parity — no
// drive-by consolidation). Quirk preserved: a plain Error without statusCode
// maps to 500, not 400. Passed inline on the cover route; the storage engine
@@ -295,6 +303,26 @@ export class CollectionsController {
}
}
/**
* A KML or KMZ map read into the list file it amounts to (PLC-22), like
* gpx/read above: nothing is written, so 200, and the browser sends what the
* user keeps of it to /import or /:id/import. A multipart upload, checked in
* the handler; the list's own rights apply where the places are written.
*/
@Post('map/read')
@HttpCode(200)
@UseInterceptors(FileInterceptor('file', MAP_UPLOAD))
@ResponseContract(collectionMapReadResultSchema)
async readMap(@UploadedFile() file: Express.Multer.File | undefined) {
if (!file) throw new HttpException({ error: 'No file uploaded', code: 'no-file' }, 400);
try {
return await this.collections.readCollectionMap(file.buffer, file.originalname);
} catch (err) {
if (!(err instanceof CollectionMapError)) throw err;
throw new HttpException({ error: err.message, code: err.code }, err.code === 'too-large' ? 413 : 400);
}
}
@Post('copy-to-trip')
@HttpCode(200)
copyToTrip(
@@ -540,6 +568,23 @@ export class CollectionsController {
return this.collections.importIntoCollection(user.id, id, body, socketId);
}
/**
* The list's places in a new order (PLC-03). Anyone who may edit the list,
* every id one of its places; the members' open tabs reload it, the asking
* one left out.
*/
@Put(':id/places/reorder')
@ResponseContract(successResponseSchema)
async reorderPlaces(
@CurrentUser() user: User,
@Param('id', rowId('Collection not found')) id: number,
@Body() body: CollectionPlacesReorderDto,
@Headers('x-socket-id') socketId?: string,
) {
await this.collections.reorderPlaces(user.id, id, body.orderedIds, socketId);
return { success: true as const };
}
@Get(':id/importable/:tripId')
importable(
@CurrentUser() user: User,
@@ -22,6 +22,7 @@ import {
collectionLabelAssignRequestSchema,
collectionImportRequestSchema,
collectionGpxReadRequestSchema,
collectionPlacesReorderRequestSchema,
} from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
@@ -56,3 +57,4 @@ export class CollectionLabelUpdateDto extends createZodDto(collectionLabelUpdate
export class CollectionLabelAssignDto extends createZodDto(collectionLabelAssignRequestSchema) {}
export class CollectionImportDto extends createZodDto(collectionImportRequestSchema) {}
export class CollectionGpxReadDto extends createZodDto(collectionGpxReadRequestSchema) {}
export class CollectionPlacesReorderDto extends createZodDto(collectionPlacesReorderRequestSchema) {}
@@ -1,5 +1,14 @@
import type { CollectionPlacePosition, CollectionPlaceRow } from '../../db/repositories/Collections.repository';
import type { CollectionFilePlace, CollectionLink, CollectionPlaceUpdateRequest, CollectionStatus } from '@trek/shared';
import type { PlaceRow } from '../../db/repositories/Places.repository';
import type { DedupSet } from '../places/places.helpers';
import { externalIdsOf } from '@trek/shared';
import type {
CollectionFilePlace,
CollectionLink,
CollectionPlaceUpdateRequest,
CollectionStatus,
PlaceMatchCandidate,
} from '@trek/shared';
import { z } from 'zod';
@@ -107,3 +116,55 @@ export function decodePlacesCursor(cursor: string): CollectionPlacePosition | nu
const [sortOrder, createdAt, id] = parsed.data;
return { sortOrder, createdAt, id };
}
/** Rows grouped by their pid, each group in the order the rows came, for the batched hydration reads. */
export function groupByPid<R extends { pid: number }, V>(rows: R[], value: (row: R) => V): Record<number, V[]> {
const out: Record<number, V[]> = {};
for (const row of rows) (out[row.pid] ??= []).push(value(row));
return out;
}
/** What saving a trip place into a list takes from it, for the single and the bulk save alike. */
export function tripPlaceFields(p: PlaceRow) {
return {
name: p.name,
description: p.description ?? null,
lat: p.lat ?? null,
lng: p.lng ?? null,
address: p.address ?? null,
category_id: p.category_id ?? null,
price: p.price ?? null,
currency: p.currency ?? null,
notes: p.notes ?? null,
image_url: p.image_url ?? null,
google_place_id: p.google_place_id ?? null,
google_ftid: p.google_ftid ?? null,
osm_id: p.osm_id ?? null,
website: p.website ?? null,
phone: p.phone ?? null,
};
}
/** The importers' dedup set over a trip's places: a place renamed in the trip is still known by its provider id (#1550). */
export function tripDedupSet(existing: PlaceMatchCandidate[]): DedupSet {
const dedup: DedupSet = { names: new Set(), coords: [], externalIds: new Set() };
for (const r of existing) {
for (const id of externalIdsOf(r)) dedup.externalIds.add(id);
if (r.name) dedup.names.add(r.name.trim().toLowerCase());
else if (r.lat != null && r.lng != null) dedup.coords.push({ lat: r.lat, lng: r.lng });
}
return dedup;
}
/**
* A list's ids in the order a reorder asks for (PLC-03): the named ones first,
* then the ones it did not name in the order they had, so a place saved by
* somebody else since the list was loaded is kept rather than dropped.
* Null when the request names an id twice or one the list does not hold.
*/
export function placeOrderOf(current: number[], requested: number[]): number[] | null {
const held = new Set(current);
const named = new Set(requested);
if (named.size !== requested.length || requested.some((id) => !held.has(id))) return null;
return [...requested, ...current.filter((id) => !named.has(id))];
}
+24 -1
View File
@@ -25,6 +25,7 @@ import {
collectionSavePlaceRequestSchema,
collectionPlaceUpdateRequestSchema,
collectionCopyToTripRequestSchema,
collectionPlacesReorderRequestSchema,
collectionLabelCreateRequestSchema,
collectionLabelUpdateRequestSchema,
collectionLabelAssignRequestSchema,
@@ -45,6 +46,7 @@ import type {
CollectionSavePlaceRequest,
CollectionPlaceUpdateRequest,
CollectionCopyToTripRequest,
CollectionPlacesReorderRequest,
CollectionInviteRequest,
CollectionLabelCreateRequest,
CollectionLabelUpdateRequest,
@@ -445,7 +447,7 @@ export class CollectionsMcp {
@Tool({
name: 'copy_collection_places_to_trip',
description:
'Copy one or more saved collection places into a trip (dedup precheck on the server). Ratings (#1435) travel into the trip; trip members keep voting there. Requires edit access to the target trip.',
"Copy one or more saved collection places into a trip (dedup precheck on the server). Ratings (#1435) travel into the trip; trip members keep voting there. A saved place's notes and tags stay in the list unless asked for: include_notes: true copies the notes, tag_ids names the tags (of those the places carry) to bring, each as a tag of the trip, reusing a trip tag of the same name. Without either field, neither is copied. Requires edit access to the target trip.",
inputSchema: collectionCopyToTripRequestSchema.shape,
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: collectionsAddonOn,
@@ -460,6 +462,27 @@ export class CollectionsMcp {
}
}
@Tool({
name: 'reorder_collection_places',
description:
"Put a list's saved places in a new order, the order every member sees and get_collection and list_collection_places read. Pass the list's place ids (collection place ids) first to last; places left out follow in the order they had. Every id must be a place of that list. Needs edit rights on the list (owner, admin or editor).",
inputSchema: { collectionId: idSchema, ...collectionPlacesReorderRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE,
when: collectionsAddonOn,
access: { group: 'collections', mode: 'write' },
})
async reorderCollectionPlaces(
{ collectionId, orderedIds }: { collectionId: number } & CollectionPlacesReorderRequest,
ctx: McpContext,
) {
try {
await this.collections.reorderPlaces(ctx.userId, collectionId, orderedIds);
return ok({ success: true });
} catch (err) {
return fail(err);
}
}
// ── Labels ────────────────────────────────────────────────────────────
@Tool({
@@ -31,13 +31,7 @@ import { Tags } from '../../db/entities/Tags.entity';
import type { TagsRepository } from '../../db/repositories/Tags.repository';
import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import {
COORD_DEDUP_TOLERANCE,
externalIdsOf,
isPlaceDuplicate,
trackInsertedInDedupSet,
type DedupSet,
} from '../places/places.helpers';
import { COORD_DEDUP_TOLERANCE, isPlaceDuplicate, trackInsertedInDedupSet } from '../places/places.helpers';
import {
placeMatchStrategies,
collectionFilePlaceSchema,
@@ -55,6 +49,7 @@ import {
type CollectionKmlExport,
type CollectionGpxReadRequest,
type CollectionGpxReadResult,
type CollectionMapReadResult,
} from '@trek/shared';
import type {
Collection,
@@ -76,7 +71,9 @@ import type {
import { NotificationsService } from '../notifications/notifications.service';
import { PlaceImportService, type ExportedCollectionFile } from '../place-import/place-import.service';
import { UnitOfWork } from '../database/unit-of-work';
import { filePlaceOf, listingWriteOf, parseLinks, serializeLinks } from './collections.helpers';
import {
filePlaceOf, groupByPid, listingWriteOf, parseLinks, placeOrderOf, serializeLinks, tripDedupSet, tripPlaceFields,
} from './collections.helpers';
// Errors: a DomainError carrying a status; TrekExceptionFilter maps it to that code with an `{ error }` body.
@@ -190,13 +187,7 @@ export class CollectionsService {
// -------------------------------------------------------------------------
private async loadTagsByCollectionPlaceIds(placeIds: number[]): Promise<Record<number, { id: number; name: string; color: string }[]>> {
const out: Record<number, { id: number; name: string; color: string }[]> = {};
const rows = await this.collectionsRepo.loadTagsByPlaceIds(placeIds);
for (const r of rows) {
if (!out[r.pid]) out[r.pid] = [];
out[r.pid].push({ id: r.id, name: r.name, color: r.color });
}
return out;
return groupByPid(await this.collectionsRepo.loadTagsByPlaceIds(placeIds), r => ({ id: r.id, name: r.name, color: r.color }));
}
/** A list's own label definitions, in display order. */
@@ -206,24 +197,12 @@ export class CollectionsService {
/** Assigned label ids per place, batched (mirrors loadTagsByCollectionPlaceIds). */
private async loadLabelIdsByPlaceIds(placeIds: number[]): Promise<Record<number, number[]>> {
const out: Record<number, number[]> = {};
const rows = await this.collectionsRepo.loadLabelIdsByPlaceIds(placeIds);
for (const r of rows) {
if (!out[r.pid]) out[r.pid] = [];
out[r.pid].push(r.label_id);
}
return out;
return groupByPid(await this.collectionsRepo.loadLabelIdsByPlaceIds(placeIds), r => r.label_id);
}
/** Per-voter rating rows (#1435), batched (mirrors loadTagsByCollectionPlaceIds). */
private async loadRatingsByCollectionPlaceIds(placeIds: number[]): Promise<Record<number, { user_id: number; username: string; avatar: string | null; rating: number }[]>> {
const out: Record<number, { user_id: number; username: string; avatar: string | null; rating: number }[]> = {};
const rows = await this.collectionsRepo.loadRatingsByPlaceIds(placeIds);
for (const { pid, ...rest } of rows) {
if (!out[pid]) out[pid] = [];
out[pid].push(rest);
}
return out;
return groupByPid(await this.collectionsRepo.loadRatingsByPlaceIds(placeIds), ({ pid: _pid, ...vote }) => vote);
}
private async hydratePlaces(rows: PlaceRow[]): Promise<CollectionPlace[]> {
@@ -372,6 +351,11 @@ export class CollectionsService {
return this.placeImport.readCollectionGpx(body.gpx, body.file_name);
}
/** A KML or KMZ upload read the same way (PLC-22): nothing written, the result goes to an import route. */
readCollectionMap(file: Buffer, fileName: string): Promise<CollectionMapReadResult> {
return this.placeImport.readCollectionMap(file, fileName);
}
/**
* Read a file back as a new list of the caller's own.
*
@@ -616,6 +600,21 @@ export class CollectionsService {
if (moved) this.realtime.broadcastToUser(userId, { type: 'collections:updated', collectionId: moved }, socketId);
}
/**
* The list's places in the order its members set by hand (PLC-03), for anyone who may edit it. The whole
* list is written 0..n-1 in one transaction, so a first reorder fixes exactly the order asked for, and a
* place saved meanwhile by somebody else follows the named ones instead of being dropped.
*/
async reorderPlaces(userId: number, collectionId: number, orderedIds: number[], socketId?: string): Promise<void> {
await this.assertCanEdit(userId, collectionId);
await this.uow.transactional(async () => {
const order = placeOrderOf(await this.collectionPlaces.idsInOrder(collectionId), orderedIds);
if (!order) httpError(400, 'Every place of the order must be in this list, once');
await this.collectionPlaces.setSortOrders(collectionId, order);
});
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
}
// -------------------------------------------------------------------------
// Dedup (collection-scoped ports of placeService helpers)
// -------------------------------------------------------------------------
@@ -709,31 +708,22 @@ export class CollectionsService {
// Insert + tags + ratings-copy are one logical write — atomic since the
// post-fold quirk pass (the relocation carried them un-transacted).
const placeId = await this.uow.transactional(async () => {
// source_place_id/source_trip_id are raw client input: kept only when the caller can see that
// trip and the place lives in it, else both are stored as null, and only then do the trip's
// ratings come along, so nobody harvests votes from a trip they cannot open. R6's two-layer
// order: assertCanEdit (the entry guard, above) ran FIRST; the trip-access check (AP1) SECOND.
const source = await this.verifiedSource(userId, body.source_trip_id, body.source_place_id);
const id = await this.collectionPlaces.insertSavedPlace({
collection_id: body.collection_id, owner_id: ownerId, saved_by: userId,
name: body.name, description: body.description ?? null, lat: body.lat ?? null, lng: body.lng ?? null, address: body.address ?? null,
category_id: body.category_id ?? null, price: body.price ?? null, currency: body.currency ?? null, notes: body.notes ?? null,
image_url: body.image_url ?? null, google_place_id: body.google_place_id ?? null, google_ftid: body.google_ftid ?? null,
osm_id: body.osm_id ?? null, website: body.website ?? null, phone: body.phone ?? null,
status: body.status ?? 'idea', source_trip_id: body.source_trip_id ?? null, source_place_id: body.source_place_id ?? null,
links: serializeLinks(body.links),
status: body.status ?? 'idea', source_trip_id: source?.tripId ?? null, source_place_id: source?.placeId ?? null,
links: serializeLinks(body.links), sort_order: await this.nextPlaceOrder(body.collection_id),
});
await this.attachTags(id, body.tag_ids);
// Carry trip ratings ONLY when the caller can actually see the source place.
// source_place_id/source_trip_id are raw client input, so verify trip access +
// that the place lives in that trip before reading place_ratings — otherwise a
// member could harvest co-members' votes on places in trips they cannot access
// (mirrors the canAccessTrip gate in saveFromTripPlace). R6's two-layer order:
// assertCanEdit (this method's own entry guard, above) ran FIRST; the trip-access
// check (AP1) runs SECOND, here, inside the write path — never reversed.
if (
body.source_place_id && body.source_trip_id &&
(await this.trips.findAccessible(body.source_trip_id, userId)) &&
(await this.tripPlaces.existsInTrip(body.source_place_id, body.source_trip_id))
) {
await this.copyTripRatings(body.source_place_id, id, body.collection_id);
}
if (source) await this.copyTripRatings(source.placeId, id, body.collection_id);
return id;
});
await this.notifyCollectionUsers(body.collection_id, socketId, 'collections:updated');
@@ -750,28 +740,21 @@ export class CollectionsService {
if (!place) httpError(404, 'Place not found');
return this.savePlace(userId, {
collection_id: collectionId,
name: place.name,
description: place.description ?? null,
lat: place.lat ?? null,
lng: place.lng ?? null,
address: place.address ?? null,
category_id: place.category_id ?? null,
price: place.price ?? null,
currency: place.currency ?? null,
notes: place.notes ?? null,
image_url: place.image_url ?? null,
google_place_id: place.google_place_id ?? null,
google_ftid: place.google_ftid ?? null,
osm_id: place.osm_id ?? null,
website: place.website ?? null,
phone: place.phone ?? null,
source_trip_id: tripId,
source_place_id: placeId,
force,
collection_id: collectionId, ...tripPlaceFields(place), source_trip_id: tripId, source_place_id: placeId, force,
}, socketId);
}
/** The source a save names, when the caller can open that trip and the place is one of its own; null otherwise. */
private async verifiedSource(userId: number, tripId?: number | null, placeId?: number | null) {
if (!tripId || !placeId || !(await this.trips.findAccessible(tripId, userId))) return null;
return (await this.tripPlaces.existsInTrip(placeId, tripId)) ? { tripId, placeId } : null;
}
/** Where a new place goes in a list: after its last one (PLC-03). Read inside the writing transaction. */
private async nextPlaceOrder(collectionId: number): Promise<number> {
return (await this.collectionsRepo.maxPlaceSortOrder(collectionId)) + 1;
}
/** The trip's places as offered to the bulk import, each already carrying the verdict
* saveFromTripPlaces would reach for it. Reusing findDuplicateCollectionPlace is the
* whole point: a row the dialog shows as new can never come back as `skipped`, and a
@@ -815,6 +798,7 @@ export class CollectionsService {
const skipped: { id: number; name: string }[] = [];
// The whole batch is one logical write — atomic since the post-fold quirk pass.
await this.uow.transactional(async () => {
let sortOrder = await this.nextPlaceOrder(collectionId);
for (const placeId of placeIds) {
const p = await this.tripPlaces.findInTrip(placeId, tripId);
if (!p) continue;
@@ -834,17 +818,10 @@ export class CollectionsService {
skipped.push({ id: placeId, name });
continue;
}
// Same 22-column insert shape as `savePlace` (CL42), with `status`/`links`
// hardcoded ('idea'/null) exactly the way the legacy statement bound them
// as literals rather than placeholders — see `insertSavedPlace`'s own
// docstring for why this is the SAME method, not a second insert shape.
// savePlace's insert (CL42), with `status`/`links` as the legacy literals ('idea'/null).
const newId = await this.collectionPlaces.insertSavedPlace({
collection_id: collectionId, owner_id: ownerId, saved_by: userId,
name, description: p.description ?? null, lat, lng, address: p.address ?? null,
category_id: p.category_id ?? null, price: p.price ?? null, currency: p.currency ?? null, notes: p.notes ?? null,
image_url: p.image_url ?? null, google_place_id: p.google_place_id ?? null, google_ftid: p.google_ftid ?? null,
osm_id: p.osm_id ?? null, website: p.website ?? null, phone: p.phone ?? null,
status: 'idea', source_trip_id: tripId, source_place_id: placeId, links: null,
collection_id: collectionId, owner_id: ownerId, saved_by: userId, ...tripPlaceFields(p),
status: 'idea', source_trip_id: tripId, source_place_id: placeId, links: null, sort_order: sortOrder++,
});
await this.copyTripRatings(placeId, newId, collectionId);
copied++;
@@ -882,6 +859,7 @@ export class CollectionsService {
// Field update + tag rewrite + label rewrite are one logical write, so one transaction.
await this.uow.transactional(async () => {
if (movedTo) write.sort_order = await this.nextPlaceOrder(movedTo); // a moved place joins the end of its new list
await this.collectionPlaces.updateFields(placeId, write);
if (body.tag_ids !== undefined) {
@@ -1084,19 +1062,21 @@ export class CollectionsService {
sources.push(row);
}
// The importers' dedup set: a place renamed in the trip is still known by its provider id (#1550).
const existing = await this.tripPlaces.dedupCandidatesForTrip(body.trip_id);
const dedup: DedupSet = { names: new Set(), coords: [], externalIds: new Set() };
for (const r of existing) {
for (const id of externalIdsOf(r)) dedup.externalIds.add(id);
if (r.name) dedup.names.add(r.name.trim().toLowerCase());
else if (r.lat != null && r.lng != null) dedup.coords.push({ lat: r.lat, lng: r.lng });
}
const dedup = tripDedupSet(await this.tripPlaces.dedupCandidatesForTrip(body.trip_id));
// D9: only the tags asked for, where the saved place carries them, and as tags of the trip, never the person's own.
const asked = new Set(body.tag_ids ?? []);
const carried = asked.size
? groupByPid((await this.collectionsRepo.loadTagsByPlaceIds(sources.map(s => s.id))).filter(t => asked.has(t.id)), t => t)
: null;
const tripTags = new Map<string, number>(); // by name, read in the transaction that adds to them
let tagsBefore = 0;
const created: CollectionCopyToTripResponse['created'] = []; // each new trip place by the saved place it came from
const skipped: { id: number; name: string }[] = [];
// The whole copy is one logical write — atomic since the post-fold quirk pass.
await this.uow.transactional(async () => {
if (carried) for (const t of await this.tags.listByTrip(body.trip_id)) tripTags.set(t.name.trim().toLowerCase(), t.id);
tagsBefore = tripTags.size;
for (const s of sources) {
if (!body.force && isPlaceDuplicate({
name: s.name, lat: s.lat, lng: s.lng,
@@ -1109,11 +1089,11 @@ export class CollectionsService {
const newPlaceId = await this.tripPlaces.insertFromCollectionPlace({
trip_id: body.trip_id, name: s.name, description: s.description, lat: s.lat, lng: s.lng,
address: s.address, category_id: s.category_id, price: s.price, currency: s.currency,
notes: s.notes, image_url: s.image_url, google_place_id: s.google_place_id, google_ftid: s.google_ftid,
notes: body.include_notes === true ? s.notes : null, // a note stays in the list unless asked for (D9)
image_url: s.image_url, google_place_id: s.google_place_id, google_ftid: s.google_ftid,
website: s.website, phone: s.phone, osm_id: s.osm_id,
});
const tagIds = await this.collectionPlaces.tagIdsFor(s.id);
await this.tags.insertIgnore(newPlaceId, tagIds);
await this.tags.insertIgnore(newPlaceId, await this.tripTagIds(body.trip_id, userId, carried?.[s.id] ?? [], tripTags));
// Ratings of trip members travel along (#1435); nothing is mirrored back.
const votes = await this.collectionPlaceRatings.listForPlace(s.id);
for (const v of votes) if (tripMemberIds.has(v.user_id)) await this.tripPlaceRatings.insertIgnore(newPlaceId, v.user_id, v.rating);
@@ -1121,6 +1101,7 @@ export class CollectionsService {
created.push({ id: newPlaceId, source_id: s.id });
}
});
if (tripTags.size > tagsBefore) events.emit('tripTags:changed', {});
const rows = await Promise.all(created.map(({ id }) => this.tripPlaces.findWithTagsAndRatings(id))); // reads only
for (const [i, place] of rows.entries()) {
if (place) events.emit('place:created', { place }); // as the place routes send it
@@ -1129,6 +1110,17 @@ export class CollectionsService {
return { copied: created.length, skipped, created };
}
/** The trip's own tag of each name: the one it has, or one made now; `known` keeps the new ones for the next place. */
private async tripTagIds(tripId: number, userId: number, tags: { name: string; color: string }[], known: Map<string, number>): Promise<number[]> {
const ids: number[] = [];
for (const { name, color } of tags) {
const key = name.trim().toLowerCase();
if (!known.has(key)) known.set(key, (await this.tags.createTag({ user_id: userId, trip_id: tripId, name: name.trim(), color })).id);
ids.push(known.get(key)!);
}
return ids;
}
// -------------------------------------------------------------------------
// Library-wide membership lookup (inspector indicator)
// -------------------------------------------------------------------------
@@ -1,5 +1,6 @@
import { PlaceImportService } from './place-import.service';
import { CollectionGpxProvider } from './providers/collection-gpx.provider';
import { CollectionKmlProvider } from './providers/collection-kml.provider';
import { GoogleDirectionsProvider } from './providers/google-directions.provider';
import { GoogleListProvider } from './providers/google-list.provider';
import { GoogleMapsShortLinkProvider } from './providers/google-maps-short-link.provider';
@@ -24,6 +25,7 @@ import { Module } from '@nestjs/common';
GpxProvider,
CollectionGpxProvider,
KmlProvider,
CollectionKmlProvider,
GoogleListProvider,
GoogleDirectionsProvider,
NaverListProvider,
@@ -12,6 +12,7 @@ import type {
ShortLinkOutcome,
} from './place-import.types';
import { CollectionGpxProvider, type ExportedCollectionFile } from './providers/collection-gpx.provider';
import { CollectionKmlProvider } from './providers/collection-kml.provider';
import { GoogleDirectionsProvider } from './providers/google-directions.provider';
import { GoogleListProvider } from './providers/google-list.provider';
import { GoogleMapsShortLinkProvider } from './providers/google-maps-short-link.provider';
@@ -25,7 +26,12 @@ import {
import { KmlProvider } from './providers/kml.provider';
import { NaverListProvider } from './providers/naver-list.provider';
import { Injectable } from '@nestjs/common';
import type { CollectionGpxExport, CollectionGpxReadResult, CollectionKmlExport } from '@trek/shared';
import type {
CollectionGpxExport,
CollectionGpxReadResult,
CollectionKmlExport,
CollectionMapReadResult,
} from '@trek/shared';
// The directions-link reading is also what the road trip planner reads a
// shared route with, what the import routes dispatch on, and what the city
@@ -61,6 +67,7 @@ export class PlaceImportService {
private readonly gpx: GpxProvider,
private readonly collectionGpx: CollectionGpxProvider,
private readonly kml: KmlProvider,
private readonly collectionKml: CollectionKmlProvider,
private readonly googleList: GoogleListProvider,
private readonly googleDirections: GoogleDirectionsProvider,
private readonly naverList: NaverListProvider,
@@ -131,6 +138,11 @@ export class PlaceImportService {
return this.kml.tripFilename(tripTitle);
}
/** A .kml or .kmz upload as the list file it amounts to (PLC-22). Throws CollectionMapError on a refusal. */
readCollectionMap(fileBuffer: Buffer, fileName: string): Promise<CollectionMapReadResult> {
return this.collectionKml.read(fileBuffer, fileName);
}
/** A list file as KML pins for Google My Maps (#1866). */
writeCollectionKml(file: ExportedCollectionFile): CollectionKmlExport {
return this.kml.writeCollection(file);
@@ -4,7 +4,7 @@
* insert, track colours, enrichment) stays with the domain that owns the rows,
* PlacesService for a trip and CollectionsService for a list.
*/
import type { CollectionGpxProblem } from '@trek/shared';
import type { CollectionGpxProblem, CollectionMapProblem } from '@trek/shared';
/** One place parsed out of a GPX file, not yet persisted. */
export interface PreparedGpxPlace {
@@ -155,6 +155,17 @@ export class CollectionGpxError extends Error {
}
}
/** Why a KML or KMZ file was refused for a list (PLC-22), carried to the controller as the response's `code`. */
export class CollectionMapError extends Error {
constructor(
readonly code: CollectionMapProblem,
message: string,
) {
super(message);
this.name = 'CollectionMapError';
}
}
/**
* CW-06: where a Google Maps short link led. `refused` when a hop or the
* landing link is not one the walk import may follow or read, `unreachable`
@@ -0,0 +1,106 @@
/**
* A KML or KMZ map (Google My Maps, Google Earth) read into the list file it
* amounts to (PLC-22), the way a GPX is: nothing is written here, the file
* goes back to the browser and comes in again through the list import, so a
* map passes the same contract and the same one transaction as any list file.
*
* A list holds points. A placemark with a line or an area, or with no
* geometry at all, is reported with its reason instead of being guessed into
* a pin. Each place keeps the folder it sat in beside the file, for a later
* mapping onto categories or labels; nothing reads it yet.
*/
import { CollectionMapError, KmlReadError, type KmlDocumentRead, type ParsedKmlPlacemark } from '../place-import.types';
import { KmlProvider } from './kml.provider';
import { Injectable } from '@nestjs/common';
import {
COLLECTION_FILE_FORMAT,
COLLECTION_FILE_VERSION,
MAX_COLLECTION_FILE_BYTES,
MAX_COLLECTION_FILE_PLACES,
collectionFilePlaceSchema,
type CollectionFilePlace,
type CollectionMapReadResult,
type CollectionMapSkipReason,
} from '@trek/shared';
import path from 'path';
const MAP_EXTENSIONS = new Set(['.kml', '.kmz']);
/** The list's name: the file's own name without its extension, or a plain one when that is empty. */
function listNameOf(fileName: string): string {
return (
path
.basename(fileName)
.replace(/\.km[lz]$/i, '')
.trim()
.slice(0, 120) || 'KML import'
);
}
/** Why a placemark cannot be a place of a list, or null for a pin. */
function reasonToLeaveOut(placemark: ParsedKmlPlacemark): CollectionMapSkipReason | null {
if (placemark.routeGeometry !== null) return 'line';
if (placemark.lat === null || placemark.lng === null) return 'no_point';
return null;
}
/** The placemarks of a read map as a list file, every one left out named with its reason. */
export function kmlToCollectionFile(read: KmlDocumentRead, fileName: string): CollectionMapReadResult {
const places: CollectionFilePlace[] = [];
const folders: Array<string | null> = [];
const skipped: CollectionMapReadResult['skipped'] = [];
for (const [index, placemark] of read.placemarks.entries()) {
const folder = placemark.folderName ?? null;
const place =
reasonToLeaveOut(placemark) ??
collectionFilePlaceSchema.safeParse({
// Unnamed pins are numbered by their place in the document, as the trip import names them.
name: (placemark.name || `Placemark ${index + 1}`).slice(0, 500),
description: placemark.description ? placemark.description.slice(0, 5000) : null,
lat: placemark.lat,
lng: placemark.lng,
});
if (typeof place === 'string' || !place.success) {
skipped.push({ name: placemark.name, folder, reason: typeof place === 'string' ? place : 'invalid' });
continue;
}
places.push(place.data);
folders.push(folder);
}
if (places.length > MAX_COLLECTION_FILE_PLACES) {
throw new CollectionMapError('too-many-places', `That map file has more than ${MAX_COLLECTION_FILE_PLACES} places`);
}
const file = {
format: COLLECTION_FILE_FORMAT,
version: COLLECTION_FILE_VERSION,
name: listNameOf(fileName),
places,
} as const;
// What comes back has to fit the import's body again, which takes a list file of this size.
if (Buffer.byteLength(JSON.stringify(file), 'utf8') > MAX_COLLECTION_FILE_BYTES) {
throw new CollectionMapError('too-large', 'That map file holds more text than a list file can take');
}
return { file, folders, skipped };
}
/** KML and KMZ for lists: the trip import's reader (and its KMZ size cap), its placemarks as a list file. */
@Injectable()
export class CollectionKmlProvider {
constructor(private readonly kml: KmlProvider) {}
async read(fileBuffer: Buffer, fileName: string): Promise<CollectionMapReadResult> {
if (!MAP_EXTENSIONS.has(path.extname(fileName).toLowerCase())) {
throw new CollectionMapError('not-map', 'Please upload a .kml or .kmz file');
}
let read: KmlDocumentRead;
try {
read = await this.kml.readMapFile(fileBuffer, fileName);
} catch (err) {
if (!(err instanceof KmlReadError)) throw err;
throw new CollectionMapError(err.reason === 'archive_too_large' ? 'too-large' : 'unreadable', err.message);
}
return kmlToCollectionFile(read, fileName);
}
}
+10 -5
View File
@@ -49,6 +49,9 @@ export { MAX_DASHBOARD_TIMEZONES };
* refusal it can act on instead of parking 'kelvin' in a row the client then
* silently ignores.
*/
/** A display switch the client keeps as true or false. */
const onOff = z.boolean();
const DISPLAY_PREFERENCES = {
start_page: z.enum(['dashboard', 'active_trip']),
// The planner falls back to its plan view for a tab that does not exist, and
@@ -79,11 +82,13 @@ const DISPLAY_PREFERENCES = {
// path accepts, and refusing them here would make a value TREK itself wrote
// unwritable through this tool.
dark_mode: z.union([z.enum(['light', 'dark', 'auto']), z.boolean()]),
map_booking_labels: z.boolean(),
map_always_show_routes: z.boolean(),
map_poi_pill_enabled: z.boolean(),
blur_booking_codes: z.boolean(),
optimize_from_accommodation: z.boolean(),
map_booking_labels: onOff,
// The names of a trip's places beside their pins on the trip map (PLC-05).
map_place_labels: onOff,
map_always_show_routes: onOff,
map_poi_pill_enabled: onOff,
blur_booking_codes: onOff,
optimize_from_accommodation: onOff,
// The dashboard world clocks (#3044). [] is a valid choice and shows none;
// leaving the key unset keeps the widget's own fallback list.
dashboard_timezones: dashboardTimezonesSchema,
+122
View File
@@ -886,4 +886,126 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () =>
).toBe(200);
expect(await countRows(orm, Collections, { id: col.id })).toBe(0);
});
// ── PLC-03: the order of a list's places ──────────────────────────────────
it('COLLECTIONS-E2E-093: PUT /:id/places/reorder sets the order for an editor, refuses a foreign id, a viewer and a stranger', async () => {
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const col = (await request(server).post('/api/addons/collections').set(as(ownerId)).send({ name: 'Ordered' })).body;
const ids: number[] = [];
for (const name of ['One', 'Two', 'Three']) {
const saved = await request(server)
.post('/api/addons/collections/places')
.set(as(ownerId))
.send({ collection_id: col.id, name });
ids.push(saved.body.place.id);
}
const reorder = (userId: number | null, orderedIds: number[]) => {
const req = request(server).put(`/api/addons/collections/${col.id}/places/reorder`);
return (userId === null ? req : req.set(as(userId))).send({ orderedIds });
};
const names = async () =>
(await request(server).get(`/api/addons/collections/${col.id}`).set(as(ownerId))).body.places.map(
(p: { name: string }) => p.name,
);
expect(await names()).toEqual(['One', 'Two', 'Three']);
const done = await reorder(ownerId, [ids[2], ids[0]]);
expect(done.status).toBe(200);
expect(done.body).toEqual({ success: true });
expect(await names()).toEqual(['Three', 'One', 'Two']);
const foreign = await reorder(ownerId, [ids[0], 999_999]);
expect(foreign.status).toBe(400);
expect(foreign.body).toEqual({ error: 'Every place of the order must be in this list, once' });
expect((await reorder(ownerId, [])).status).toBe(400);
// Not on the list: 404, no hint the list exists. A viewer: the read-only 403. No session: 401.
expect((await reorder(otherId, [ids[0]])).status).toBe(404);
await request(server)
.post('/api/addons/collections/invite')
.set(as(ownerId))
.send({ collection_id: col.id, user_id: otherId, role: 'viewer' });
await request(server)
.post('/api/addons/collections/invite/accept')
.set(as(otherId))
.send({ collection_id: col.id });
expect((await reorder(otherId, [ids[0]])).status).toBe(403);
expect((await reorder(null, [ids[0]])).status).toBe(401);
expect(await names()).toEqual(['Three', 'One', 'Two']);
});
// ── PLC-22: a KML or KMZ map read into a list file ────────────────────────
it('COLLECTIONS-E2E-094: POST /map/read reads an uploaded KML into a list file that /import then writes', async () => {
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const kml = `<?xml version="1.0"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document>
<Folder><name>Food</name><Placemark><name>Pasteis</name><Point><coordinates>-9.2,38.69</coordinates></Point></Placemark></Folder>
<Placemark><name>Walk</name><LineString><coordinates>-9.1,38.7 -9.2,38.71</coordinates></LineString></Placemark>
</Document></kml>`;
const read = await request(server)
.post('/api/addons/collections/map/read')
.set(as(ownerId))
.attach('file', Buffer.from(kml), 'Lisbon.kml');
expect(read.status).toBe(200);
expect(read.body.file).toMatchObject({ name: 'Lisbon', places: [{ name: 'Pasteis', lat: 38.69, lng: -9.2 }] });
expect(read.body.folders).toEqual(['Food']);
expect(read.body.skipped).toEqual([{ name: 'Walk', folder: null, reason: 'line' }]);
// Reading wrote nothing.
expect(await countRows(orm, CollectionPlaces, { name: 'Pasteis' })).toBe(0);
const imported = await request(server)
.post('/api/addons/collections/import')
.set(as(ownerId))
.send({ file: read.body.file });
expect(imported.status).toBe(201);
expect(imported.body).toMatchObject({ imported: 1, skipped: 0 });
});
it('COLLECTIONS-E2E-095: /map/read refuses a missing file, another type and a broken map with a code, and needs a session', async () => {
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const upload = (content: string, name: string) =>
request(server)
.post('/api/addons/collections/map/read')
.set(as(ownerId))
.attach('file', Buffer.from(content), name);
const none = await request(server).post('/api/addons/collections/map/read').set(as(ownerId)).field('x', '1');
expect(none.status).toBe(400);
expect(none.body).toEqual({ error: 'No file uploaded', code: 'no-file' });
const gpx = await upload('<gpx/>', 'route.gpx');
expect(gpx.status).toBe(400);
expect(gpx.body).toEqual({ error: expect.any(String), code: 'not-map' });
const broken = await upload('<kml><Document>', 'broken.kml');
expect(broken.status).toBe(400);
expect(broken.body).toEqual({ error: expect.any(String), code: 'unreadable' });
// Without a body: a guard answering while an upload still streams would reset the socket.
expect((await request(server).post('/api/addons/collections/map/read')).status).toBe(401);
});
// ── D9: notes of a copy into a trip ───────────────────────────────────────
it('COLLECTIONS-E2E-096: copy-to-trip leaves the notes behind unless include_notes is sent', async () => {
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const col = (await request(server).post('/api/addons/collections').set(as(ownerId)).send({ name: 'Notes' })).body;
const save = (name: string, notes: string) =>
request(server)
.post('/api/addons/collections/places')
.set(as(ownerId))
.send({ collection_id: col.id, name, notes });
const quiet = await save('Quiet bar', 'my own note');
const open = await save('Open bar', 'for everyone');
const copy = (body: Record<string, unknown>) =>
request(server)
.post('/api/addons/collections/copy-to-trip')
.set(as(ownerId))
.send({ trip_id: tripId, ...body });
expect((await copy({ place_ids: [quiet.body.place.id] })).status).toBe(200);
expect((await copy({ place_ids: [open.body.place.id], include_notes: true })).status).toBe(200);
expect((await findRow(orm, Places, { trip: tripId, name: 'Quiet bar' }))?.notes).toBeNull();
expect((await findRow(orm, Places, { trip: tripId, name: 'Open bar' }))?.notes).toBe('for everyone');
});
});
+4 -1
View File
@@ -1,5 +1,6 @@
import { PlaceImportService } from '../../src/nest/place-import/place-import.service';
import { CollectionGpxProvider } from '../../src/nest/place-import/providers/collection-gpx.provider';
import { CollectionKmlProvider } from '../../src/nest/place-import/providers/collection-kml.provider';
import { GoogleDirectionsProvider } from '../../src/nest/place-import/providers/google-directions.provider';
import { GoogleListProvider } from '../../src/nest/place-import/providers/google-list.provider';
import { GoogleMapsShortLinkProvider } from '../../src/nest/place-import/providers/google-maps-short-link.provider';
@@ -12,10 +13,12 @@ import { NaverListProvider } from '../../src/nest/place-import/providers/naver-l
* providers over the global fetch a test stubs.
*/
export function buildPlaceImportService(): PlaceImportService {
const kml = new KmlProvider();
return new PlaceImportService(
new GpxProvider(),
new CollectionGpxProvider(),
new KmlProvider(),
kml,
new CollectionKmlProvider(kml),
new GoogleListProvider(),
new GoogleDirectionsProvider(),
new NaverListProvider(),
@@ -802,6 +802,18 @@ const collectionCases: ParityCase[] = [
rest: { method: 'post', path: () => `${COLLECTIONS}/reorder`, body: (s) => ({ orderedIds: [s.collection.id] }) },
expect: [{ event: 'collections:updated', user: 'actor' }],
},
{
// PLC-03: the members' tabs reload the list, the asking one left out.
tool: 'reorder_collection_places',
needs: ['collection'],
args: (s) => ({ collectionId: s.collection.id, orderedIds: [s.collectionPlace.id] }),
rest: {
method: 'put',
path: (s) => `${COLLECTIONS}/${s.collection.id}/places/reorder`,
body: (s) => ({ orderedIds: [s.collectionPlace.id] }),
},
expect: [{ event: 'collections:updated', user: 'actor' }],
},
{
tool: 'save_place_to_collection',
needs: ['collection'],
@@ -185,6 +185,7 @@ describe('longitude on write', () => {
source_trip_id: null,
source_place_id: null,
links: null,
sort_order: 0,
});
const lngOf = async () => (await findRow(t.orm, CollectionPlaces, { id }))?.lng;
expect(await lngOf()).toBeCloseTo(2.35, 9);
@@ -784,6 +784,86 @@ describe('Tool: copy_collection_places_to_trip', () => {
// A refused copy reaches nobody.
expect(realtime.broadcastMock.mock.calls.filter(([, event]) => event === 'place:created')).toHaveLength(0);
});
it('MCP-COLL-COPY-002: the notes stay in the list unless include_notes is passed (D9)', async () => {
const { user } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, user.id);
const col = await seedCollection(user.id, 'Plan');
const quiet = await insertRow(orm, CollectionPlaces, {
collection: col,
owner: user.id,
name: 'Quiet',
notes: 'mine',
});
const open = await insertRow(orm, CollectionPlaces, {
collection: col,
owner: user.id,
name: 'Open',
notes: 'ours',
});
await withHarness(user.id, async (h) => {
await h.client.callTool({
name: 'copy_collection_places_to_trip',
arguments: { trip_id: trip.id, place_ids: [quiet] },
});
await h.client.callTool({
name: 'copy_collection_places_to_trip',
arguments: { trip_id: trip.id, place_ids: [open], include_notes: true },
});
});
expect((await findRow(orm, Places, { trip: trip.id, name: 'Quiet' }))?.notes).toBeNull();
expect((await findRow(orm, Places, { trip: trip.id, name: 'Open' }))?.notes).toBe('ours');
});
});
describe('Tool: reorder_collection_places', () => {
it('MCP-COLL-ORDER-001: puts the places in the order named, the rest after them, as get_collection reads it', async () => {
const { user } = await makeUser(orm);
const col = await seedCollection(user.id, 'Order');
const a = await seedPlace(col, user.id, 'A');
const b = await seedPlace(col, user.id, 'B');
const c = await seedPlace(col, user.id, 'C');
await withHarness(user.id, async (h) => {
const done = parseToolResult(
await h.client.callTool({
name: 'reorder_collection_places',
arguments: { collectionId: col, orderedIds: [c, a] },
}),
);
expect(done).toEqual({ success: true });
const detail = parseToolResult(
await h.client.callTool({ name: 'get_collection', arguments: { collectionId: col } }),
) as { places: { id: number }[] };
expect(detail.places.map((p) => p.id)).toEqual([c, a, b]);
});
});
it('MCP-COLL-ORDER-002: a place of another list is refused with the REST text, a viewer gets the read-only one', async () => {
const { user: owner } = await makeUser(orm);
const { user: viewer } = await makeUser(orm);
const col = await seedCollection(owner.id, 'Mine');
const other = await seedCollection(owner.id, 'Other');
const a = await seedPlace(col, owner.id, 'A');
const foreign = await seedPlace(other, owner.id, 'Foreign');
await addMember(col, viewer.id, 'viewer');
await withHarness(owner.id, async (h) => {
const result = await h.client.callTool({
name: 'reorder_collection_places',
arguments: { collectionId: col, orderedIds: [foreign, a] },
});
expect(result.isError).toBe(true);
expect(errorText(result)).toBe('Every place of the order must be in this list, once');
});
await withHarness(viewer.id, async (h) => {
const result = await h.client.callTool({
name: 'reorder_collection_places',
arguments: { collectionId: col, orderedIds: [a] },
});
expect(result.isError).toBe(true);
expect(errorText(result)).toBe('You have read-only access to this list');
});
});
});
// ---------------------------------------------------------------------------
@@ -1138,6 +1218,7 @@ const WRITE_TOOLS = [
'rate_collection_place',
'delete_collection_place',
'copy_collection_places_to_trip',
'reorder_collection_places',
'create_collection_label',
'update_collection_label',
'delete_collection_label',
@@ -1161,7 +1242,7 @@ describe('Collection tools — scope gating', () => {
}
}
it('registers all 29 tools with null scopes (full access)', async () => {
it('registers all 30 tools with null scopes (full access)', async () => {
const { user } = await makeUser(orm);
const names = await listToolNames(user.id, null);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).toContain(tool);
+3 -1
View File
@@ -324,15 +324,17 @@ describe('Tool: update_display_settings', () => {
await withHarness(user.id, async (h) => {
const result = await update(h, {
map_booking_labels: true,
map_place_labels: true,
map_always_show_routes: false,
map_poi_pill_enabled: true,
blur_booking_codes: false,
optimize_from_accommodation: true,
});
const data = parseToolResult(result) as any;
expect(data.updated).toBe(5);
expect(data.updated).toBe(6);
expect(data.settings).toEqual({
map_booking_labels: true,
map_place_labels: true,
map_always_show_routes: false,
map_poi_pill_enabled: true,
blur_booking_codes: false,
@@ -2,11 +2,11 @@ import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.serv
import { CollectionsController } from '../../../src/nest/collections/collections.controller';
import type { CollectionsService } from '../../../src/nest/collections/collections.service';
import { DomainError } from '../../../src/nest/common/domain-error';
import { CollectionGpxError } from '../../../src/nest/place-import/place-import.types';
import { CollectionGpxError, CollectionMapError } from '../../../src/nest/place-import/place-import.types';
import type { StorageService } from '../../../src/nest/storage/storage.service';
import type { User } from '../../../src/types';
import { HttpException } from '@nestjs/common';
import type { CollectionGpxProblem } from '@trek/shared';
import type { CollectionGpxProblem, CollectionMapProblem } from '@trek/shared';
import { describe, it, expect, vi, afterEach } from 'vitest';
@@ -454,4 +454,64 @@ describe('CollectionsController', () => {
expect(() => c.readGpx({ gpx: 'x' })).toThrow('disk on fire');
});
});
describe('map/read (PLC-22)', () => {
const upload = { buffer: Buffer.from('<kml/>'), originalname: 'lisbon.kml' } as Express.Multer.File;
/** The status and body an async handler rejects with. */
async function rejected(run: Promise<unknown>): Promise<{ status: number; body: unknown }> {
try {
await run;
} catch (err) {
expect(err).toBeInstanceOf(HttpException);
const e = err as HttpException;
return { status: e.getStatus(), body: e.getResponse() };
}
throw new Error('expected a refusal');
}
it('hands the upload to the service and answers what it read', async () => {
const read = { file: { name: 'Lisbon' }, folders: [], skipped: [] };
const svc = makeService({ readCollectionMap: vi.fn().mockResolvedValue(read) });
const c = new CollectionsController(svc, new RuntimeEnvService(), storageStub);
expect(await c.readMap(upload)).toBe(read);
expect(svc.readCollectionMap).toHaveBeenCalledWith(upload.buffer, 'lisbon.kml');
});
it('answers 400 no-file without an upload, a refusal with its code, 413 for size', async () => {
const c = new CollectionsController(makeService(), new RuntimeEnvService(), storageStub);
expect(await rejected(c.readMap(undefined))).toEqual({
status: 400,
body: { error: 'No file uploaded', code: 'no-file' },
});
const refuse = (code: CollectionMapProblem) =>
new CollectionsController(
makeService({ readCollectionMap: vi.fn().mockRejectedValue(new CollectionMapError(code, 'refused')) }),
new RuntimeEnvService(),
storageStub,
);
for (const code of ['not-map', 'unreadable', 'too-many-places'] as const) {
expect(await rejected(refuse(code).readMap(upload))).toEqual({ status: 400, body: { error: 'refused', code } });
}
expect(await rejected(refuse('too-large').readMap(upload))).toEqual({
status: 413,
body: { error: 'refused', code: 'too-large' },
});
});
it('lets any other failure through untouched', async () => {
const svc = makeService({ readCollectionMap: vi.fn().mockRejectedValue(new Error('disk on fire')) });
const c = new CollectionsController(svc, new RuntimeEnvService(), storageStub);
await expect(c.readMap(upload)).rejects.toThrow('disk on fire');
});
});
describe('PUT /:id/places/reorder (PLC-03)', () => {
it('forwards the list, the order and the socket id, and answers { success: true }', async () => {
const svc = makeService({ reorderPlaces: vi.fn() });
const c = new CollectionsController(svc, new RuntimeEnvService(), storageStub);
expect(await c.reorderPlaces(user, 3, { orderedIds: [9, 8] }, 'sock-1')).toEqual({ success: true });
expect(svc.reorderPlaces).toHaveBeenCalledWith(1, 3, [9, 8], 'sock-1');
});
});
});
@@ -3,14 +3,20 @@
* place goes out to the trip room as `place:created`, shaped as the place routes
* send it, and runs the places domain's journey hook, so open planners show the
* copies without a reload. A skipped duplicate and a refused copy send nothing.
*
* And what a copy takes along (D9): a saved place's notes and tags stay in the
* list unless the request asks for them, and an asked-for tag arrives as a tag
* of the trip, never as somebody's personal tag.
*/
import { Places } from '../../../src/db/entities/Places.entity';
import { Tags } from '../../../src/db/entities/Tags.entity';
import { CollectionsModule } from '../../../src/nest/collections/collections.module';
import { CollectionsService } from '../../../src/nest/collections/collections.service';
import { PlacesService } from '../../../src/nest/places/places.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { addCollectionMember } from '../../helpers/factories/collections';
import { makeCategory, makePlace, makeTag } from '../../helpers/factories/places';
import { findRow } from '../../helpers/factories/rows';
import { countRows, findRow, findRows } from '../../helpers/factories/rows';
import { makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { resetTestDb } from '../../helpers/test-db';
@@ -71,7 +77,7 @@ describe('CollectionsService.copyToTrip: the trip hears its new places', () => {
const res = await svc.copyToTrip(
user.id,
{ trip_id: trip.id, place_ids: [bar.id, dup.id] },
{ trip_id: trip.id, place_ids: [bar.id, dup.id], tag_ids: [tag.id] },
svc.tripEvents(trip.id, 'sock-copy'),
);
@@ -88,9 +94,10 @@ describe('CollectionsService.copyToTrip: the trip hears its new places', () => {
// The trip room, the REST socket left out, the place as the place routes send it.
const [room, payload, sid] = sent[0];
expect([room, sid]).toEqual([trip.id, 'sock-copy']);
expect((payload as { place: { id: number; tags: { id: number }[] } }).place).toMatchObject({
// The tag arrives as one of the trip's own, under the same name.
expect((payload as { place: { id: number; tags: { name: string }[] } }).place).toMatchObject({
id: copy.id,
tags: [expect.objectContaining({ id: tag.id })],
tags: [expect.objectContaining({ name: 'rooftop' })],
});
expect(onCreated.mock.calls).toEqual([[String(trip.id), copy.id]]);
});
@@ -124,3 +131,109 @@ describe('CollectionsService.copyToTrip: the trip hears its new places', () => {
expect(placeCreated().map(([room, , sid]) => [room, sid])).toEqual([[trip.id, undefined]]);
});
});
/** Every tag on the trip place, as [name, trip_id, user_id]. */
async function tagsOf(placeId: number) {
return (await findRows(orm, Tags, { place_tags_inverse: placeId })).map((t) => [t.name, t.trip_id, t.user_id]);
}
const tripTagEvents = () => t.realtime.broadcastMock.mock.calls.filter(([, event]) => event === 'tripTags:changed');
describe('CollectionsService.copyToTrip: notes and tags only when asked for (D9)', () => {
it('COLLECTIONS-SVC-226: a body without the new fields copies the place with neither its notes nor its tags', async () => {
const { user } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, user.id);
const tag = await makeTag(orm, user.id, { name: 'private' });
const col = await svc.createCollection(user.id, { name: 'Mine' });
const spot = await saved(user.id, { collection_id: col.id, name: 'Cafe', notes: 'ask for Ana', tag_ids: [tag.id] });
t.realtime.broadcastMock.mockClear();
await svc.copyToTrip(user.id, { trip_id: trip.id, place_ids: [spot.id] }, svc.tripEvents(trip.id, undefined));
const copy = await findRow(orm, Places, { trip: trip.id, name: 'Cafe' });
expect(copy?.notes).toBeNull();
expect(await tagsOf(copy!.id)).toEqual([]);
expect(tripTagEvents()).toEqual([]);
});
it('COLLECTIONS-SVC-227: include_notes: true brings the notes along', async () => {
const { user } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, user.id);
const col = await svc.createCollection(user.id, { name: 'Mine' });
const spot = await saved(user.id, { collection_id: col.id, name: 'Bakery', notes: 'open at 7' });
await svc.copyToTrip(
user.id,
{ trip_id: trip.id, place_ids: [spot.id], include_notes: true },
svc.tripEvents(trip.id, undefined),
);
expect((await findRow(orm, Places, { trip: trip.id, name: 'Bakery' }))?.notes).toBe('open at 7');
});
it('COLLECTIONS-SVC-228: asked-for tags become trip tags: one of the same name is reused, a new one made once, no personal tag is linked', async () => {
const { user: owner } = await makeUser(orm);
const { user: friend } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, owner.id);
const existing = await makeTag(orm, owner.id, { name: 'Rooftop', trip: trip.id });
const col = await svc.createCollection(owner.id, { name: 'Shared' });
await addCollectionMember(orm, col.id, friend.id);
// Both personal tags of the list's people: the friend's, and one the copy is not asked for.
const rooftop = await makeTag(orm, friend.id, { name: 'rooftop ' });
const brunch = await makeTag(orm, friend.id, { name: 'Brunch' });
const quiet = await makeTag(orm, owner.id, { name: 'quiet' });
const a = await saved(friend.id, {
collection_id: col.id,
name: 'Sky Bar',
tag_ids: [rooftop.id, brunch.id, quiet.id],
});
const b = await saved(friend.id, { collection_id: col.id, name: 'Garden', tag_ids: [brunch.id] });
t.realtime.broadcastMock.mockClear();
await svc.copyToTrip(
owner.id,
{ trip_id: trip.id, place_ids: [a.id, b.id], tag_ids: [rooftop.id, brunch.id, 999_999] },
svc.tripEvents(trip.id, 'sock-1'),
);
const skyBar = await findRow(orm, Places, { trip: trip.id, name: 'Sky Bar' });
const garden = await findRow(orm, Places, { trip: trip.id, name: 'Garden' });
const sky = await tagsOf(skyBar!.id);
expect(sky).toHaveLength(2);
expect(sky).toEqual(
expect.arrayContaining([
['Rooftop', trip.id, owner.id],
['Brunch', trip.id, owner.id],
]),
);
expect(await tagsOf(garden!.id)).toEqual([['Brunch', trip.id, owner.id]]);
// One new trip tag for both places, the trip's own one reused, the personal tags left where they were.
expect(await countRows(orm, Tags, { trip: trip.id })).toBe(2);
expect((await findRows(orm, Tags, { place_tags_inverse: skyBar!.id })).map((tag) => tag.id)).toContain(existing.id);
expect(tripTagEvents()).toEqual([[trip.id, 'tripTags:changed', {}, 'sock-1']]);
});
it('COLLECTIONS-SVC-229: a skipped duplicate makes no trip tag', async () => {
const { user } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, user.id);
await makePlace(orm, trip.id, { name: 'Pantheon' });
const tag = await makeTag(orm, user.id, { name: 'ancient' });
const col = await svc.createCollection(user.id, { name: 'Rome' });
const dup = await saved(user.id, { collection_id: col.id, name: 'Pantheon', tag_ids: [tag.id] });
t.realtime.broadcastMock.mockClear();
const res = await svc.copyToTrip(
user.id,
{ trip_id: trip.id, place_ids: [dup.id], tag_ids: [tag.id] },
svc.tripEvents(trip.id, undefined),
);
expect(res.copied).toBe(0);
expect(await countRows(orm, Tags, { trip: trip.id })).toBe(0);
expect(tripTagEvents()).toEqual([]);
});
});
@@ -2,16 +2,23 @@
* The pure helpers of the collections domain: the link helpers, which read and
* write the JSON TEXT column a list or a saved place keeps its links in, the
* listing fields an update writes, the cursor of a page of places, and a saved
* place as the list file carries it. COLLECTIONS-HELPERS-001 to 009.
* place as the list file carries it, the grouping of the batched hydration
* reads, the trip dedup set a copy checks, the place fields a trip save takes
* and the order a reorder writes. COLLECTIONS-HELPERS-001 to 013.
*/
import type { CollectionPlaceRow } from '../../../src/db/repositories/Collections.repository';
import type { PlaceRow } from '../../../src/db/repositories/Places.repository';
import {
decodePlacesCursor,
encodePlacesCursor,
filePlaceOf,
groupByPid,
listingWriteOf,
parseLinks,
placeOrderOf,
serializeLinks,
tripDedupSet,
tripPlaceFields,
} from '../../../src/nest/collections/collections.helpers';
import { describe, expect, it } from 'vitest';
@@ -156,3 +163,79 @@ describe('filePlaceOf', () => {
});
});
});
describe('groupByPid', () => {
it('COLLECTIONS-HELPERS-010: groups the rows by their place, each group in the order the rows came', () => {
const rows = [
{ pid: 2, v: 'a' },
{ pid: 1, v: 'b' },
{ pid: 2, v: 'c' },
];
expect(groupByPid(rows, (r) => r.v)).toEqual({ 1: ['b'], 2: ['a', 'c'] });
expect(groupByPid([], (r: { pid: number }) => r)).toEqual({});
});
});
describe('tripDedupSet', () => {
it('COLLECTIONS-HELPERS-011: names by their trimmed lower case, coordinates only for a nameless place, every provider id', () => {
const set = tripDedupSet([
{ name: ' Pantheon ', lat: 41.9, lng: 12.47, google_place_id: 'g1', google_ftid: null, osm_id: null },
{ name: '', lat: 41.8, lng: 12.4, google_place_id: null, google_ftid: 'f1', osm_id: 'node/2' },
]);
expect([...set.names]).toEqual(['pantheon']);
expect(set.coords).toEqual([{ lat: 41.8, lng: 12.4 }]);
expect([...set.externalIds].sort()).toEqual(['f1', 'g1', 'node/2']);
});
});
describe('tripPlaceFields', () => {
it('COLLECTIONS-HELPERS-012: takes what a list keeps of a trip place and nothing of its itinerary', () => {
const place = {
id: 5,
trip_id: 1,
name: 'Louvre',
description: 'Museum',
lat: 48.86,
lng: 2.34,
address: 'Rue de Rivoli',
category_id: 3,
price: 22,
currency: 'EUR',
notes: 'Go early',
image_url: null,
google_place_id: 'g',
google_ftid: null,
osm_id: null,
website: 'https://louvre.fr',
phone: null,
place_time: '09:00',
reservation_status: 'confirmed',
} as unknown as PlaceRow;
expect(tripPlaceFields(place)).toEqual({
name: 'Louvre',
description: 'Museum',
lat: 48.86,
lng: 2.34,
address: 'Rue de Rivoli',
category_id: 3,
price: 22,
currency: 'EUR',
notes: 'Go early',
image_url: null,
google_place_id: 'g',
google_ftid: null,
osm_id: null,
website: 'https://louvre.fr',
phone: null,
});
});
});
describe('placeOrderOf (PLC-03)', () => {
it('COLLECTIONS-HELPERS-013: the named ids first, the rest after them as they were; null for a foreign or doubled id', () => {
expect(placeOrderOf([1, 2, 3, 4], [3, 1])).toEqual([3, 1, 2, 4]);
expect(placeOrderOf([1, 2], [2, 1])).toEqual([2, 1]);
expect(placeOrderOf([1, 2], [2, 9])).toBeNull();
expect(placeOrderOf([1, 2], [2, 2])).toBeNull();
});
});
@@ -0,0 +1,238 @@
/**
* The order of a list's places (PLC-03) and the provenance a save keeps.
*
* reorderPlaces sets the order by hand for anyone who may edit the list; every
* way a place comes into a list puts it after the last one; and the source
* trip and place a save names are kept only when the caller can open that
* trip and the place is one of its own.
*
* Real in-memory SQLite over the container: the service comes out of
* CollectionsModule, the rows are seeded and read through the ORM factories.
*/
import { CollectionPlaces } from '../../../src/db/entities/CollectionPlaces.entity';
import { CollectionsModule } from '../../../src/nest/collections/collections.module';
import { CollectionsService } from '../../../src/nest/collections/collections.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { addCollectionMember, makeCollectionPlace } from '../../helpers/factories/collections';
import { makeCategory, makePlace } from '../../helpers/factories/places';
import { findRow, findRows } from '../../helpers/factories/rows';
import { makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { MikroORM } from '@mikro-orm/core';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let svc: CollectionsService;
const orm = () => t.get(MikroORM);
beforeAll(async () => {
t = await createTestModule({ db, imports: [CollectionsModule] });
svc = t.get(CollectionsService);
});
beforeEach(() => {
resetTestDb(db);
t.realtime.reset();
});
afterAll(async () => {
await t.close();
db.close();
});
/** The list's place names in the order the detail read answers them. */
async function namesInOrder(userId: number, collectionId: number): Promise<string[]> {
return (await svc.getCollection(userId, collectionId)).places.map((p) => p.name);
}
/** A place saved through the service, so it takes the position a save gives it. */
async function save(userId: number, collectionId: number, name: string) {
const { place } = await svc.savePlace(userId, { collection_id: collectionId, name });
if (!place) throw new Error(`expected ${name} to be saved`);
return place;
}
describe('reorderPlaces (PLC-03)', () => {
it('COLLECTIONS-ORDER-001: sets the order the request names, which every read then follows', async () => {
const { user } = await makeUser(orm());
const col = await svc.createCollection(user.id, { name: 'Lisbon' });
const a = await save(user.id, col.id, 'Alfama');
const b = await save(user.id, col.id, 'Belem');
const c = await save(user.id, col.id, 'Chiado');
await svc.reorderPlaces(user.id, col.id, [c.id, a.id, b.id], 'sock-1');
expect(await namesInOrder(user.id, col.id)).toEqual(['Chiado', 'Alfama', 'Belem']);
const rows = await findRows(orm(), CollectionPlaces, { collection: col.id }, { sort_order: 'asc' });
expect(rows.map((r) => [r.name, r.sort_order])).toEqual([
['Chiado', 0],
['Alfama', 1],
['Belem', 2],
]);
// The members' tabs reload the list, the asking one left out.
expect(t.realtime.broadcastToUserMock).toHaveBeenCalledWith(
user.id,
{ type: 'collections:updated', collectionId: col.id },
'sock-1',
);
});
it('COLLECTIONS-ORDER-002: places the request leaves out follow the named ones in the order they had', async () => {
const { user } = await makeUser(orm());
const col = await svc.createCollection(user.id, { name: 'Porto' });
const a = await save(user.id, col.id, 'A');
await save(user.id, col.id, 'B');
const c = await save(user.id, col.id, 'C');
await svc.reorderPlaces(user.id, col.id, [c.id, a.id]);
expect(await namesInOrder(user.id, col.id)).toEqual(['C', 'A', 'B']);
});
it('COLLECTIONS-ORDER-003: an id of another list, or one named twice, is refused and nothing moves', async () => {
const { user } = await makeUser(orm());
const col = await svc.createCollection(user.id, { name: 'Here' });
const other = await svc.createCollection(user.id, { name: 'There' });
const a = await save(user.id, col.id, 'A');
const b = await save(user.id, col.id, 'B');
const foreign = await save(user.id, other.id, 'Foreign');
t.realtime.reset();
for (const ids of [
[b.id, foreign.id],
[b.id, b.id, a.id],
]) {
await expect(svc.reorderPlaces(user.id, col.id, ids)).rejects.toMatchObject({
status: 400,
message: 'Every place of the order must be in this list, once',
});
}
expect(await namesInOrder(user.id, col.id)).toEqual(['A', 'B']);
expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled();
});
it('COLLECTIONS-ORDER-004: an editor may reorder, a viewer gets the read-only refusal, a stranger a 404', async () => {
const { user: owner } = await makeUser(orm());
const { user: editor } = await makeUser(orm());
const { user: viewer } = await makeUser(orm());
const { user: stranger } = await makeUser(orm());
const col = await svc.createCollection(owner.id, { name: 'Shared' });
await addCollectionMember(orm(), col.id, editor.id, { role: 'editor' });
await addCollectionMember(orm(), col.id, viewer.id, { role: 'viewer' });
const a = await save(owner.id, col.id, 'A');
const b = await save(owner.id, col.id, 'B');
await svc.reorderPlaces(editor.id, col.id, [b.id, a.id]);
expect(await namesInOrder(owner.id, col.id)).toEqual(['B', 'A']);
await expect(svc.reorderPlaces(viewer.id, col.id, [a.id, b.id])).rejects.toMatchObject({ status: 403 });
await expect(svc.reorderPlaces(stranger.id, col.id, [a.id, b.id])).rejects.toMatchObject({
status: 404,
message: 'Collection not found',
});
});
it('COLLECTIONS-ORDER-005: places that all still stand at 0 read oldest first, by id, until a reorder fixes them', async () => {
const { user } = await makeUser(orm());
const col = await svc.createCollection(user.id, { name: 'Old list' });
// Rows from before PLC-03 all carry the column default.
const first = await makeCollectionPlace(orm(), col.id, user.id, { name: 'First', sort_order: 0 });
await makeCollectionPlace(orm(), col.id, user.id, { name: 'Second', sort_order: 0 });
const third = await makeCollectionPlace(orm(), col.id, user.id, { name: 'Third', sort_order: 0 });
expect(await namesInOrder(user.id, col.id)).toEqual(['First', 'Second', 'Third']);
await svc.reorderPlaces(user.id, col.id, [third.id, first.id]);
expect(await namesInOrder(user.id, col.id)).toEqual(['Third', 'First', 'Second']);
});
});
describe('a new place goes after the last one (PLC-03)', () => {
it('COLLECTIONS-ORDER-006: a save, a save from a trip and a bulk save from a trip all append', async () => {
const { user } = await makeUser(orm());
await makeCategory(orm());
const trip = await makeTrip(orm(), user.id);
const tower = await makePlace(orm(), trip.id, { name: 'Tower', lat: 38.69, lng: -9.21 });
const tram = await makePlace(orm(), trip.id, { name: 'Tram', lat: 38.71, lng: -9.13 });
const view = await makePlace(orm(), trip.id, { name: 'View', lat: 38.72, lng: -9.14 });
const col = await svc.createCollection(user.id, { name: 'Lisbon' });
const a = await save(user.id, col.id, 'A');
const b = await save(user.id, col.id, 'B');
await svc.reorderPlaces(user.id, col.id, [b.id, a.id]);
await svc.saveFromTripPlace(user.id, col.id, trip.id, tower.id);
await svc.saveFromTripPlaces(user.id, col.id, trip.id, [tram.id, view.id]);
await save(user.id, col.id, 'Last');
expect(await namesInOrder(user.id, col.id)).toEqual(['B', 'A', 'Tower', 'Tram', 'View', 'Last']);
});
it('COLLECTIONS-ORDER-007: a place moved into another list joins the end of that list', async () => {
const { user } = await makeUser(orm());
const from = await svc.createCollection(user.id, { name: 'From' });
const to = await svc.createCollection(user.id, { name: 'To' });
await save(user.id, to.id, 'Already here');
await save(user.id, to.id, 'Also here');
const moving = await save(user.id, from.id, 'Moving');
await svc.updatePlace(user.id, moving.id, { collection_id: to.id });
expect(await namesInOrder(user.id, to.id)).toEqual(['Already here', 'Also here', 'Moving']);
expect((await findRow(orm(), CollectionPlaces, { id: moving.id }))?.sort_order).toBe(2);
});
it('COLLECTIONS-ORDER-008: an edit that names no coordinates keeps them, null clears them (PLC-04)', async () => {
const { user } = await makeUser(orm());
const col = await svc.createCollection(user.id, { name: 'Coords' });
const { place } = await svc.savePlace(user.id, { collection_id: col.id, name: 'Pin', lat: 38.7, lng: -9.1 });
await svc.updatePlace(user.id, place!.id, { address: 'Rua Augusta 1' });
expect(await findRow(orm(), CollectionPlaces, { id: place!.id })).toMatchObject({ lat: 38.7, lng: -9.1 });
await svc.updatePlace(user.id, place!.id, { lat: null, lng: null });
expect(await findRow(orm(), CollectionPlaces, { id: place!.id })).toMatchObject({ lat: null, lng: null });
await svc.updatePlace(user.id, place!.id, { lat: 38.71, lng: -9.14 });
expect(await findRow(orm(), CollectionPlaces, { id: place!.id })).toMatchObject({ lat: 38.71, lng: -9.14 });
});
});
describe('savePlace keeps only a provenance the caller can stand behind', () => {
it('COLLECTIONS-ORDER-009: a trip the caller can open, holding the place, is kept', async () => {
const { user } = await makeUser(orm());
await makeCategory(orm());
const trip = await makeTrip(orm(), user.id);
const place = await makePlace(orm(), trip.id, { name: 'Castle' });
const col = await svc.createCollection(user.id, { name: 'Mine' });
const { place: saved } = await svc.savePlace(user.id, {
collection_id: col.id,
name: 'Castle',
source_trip_id: trip.id,
source_place_id: place.id,
});
expect(saved).toMatchObject({ source_trip_id: trip.id, source_place_id: place.id });
});
it('COLLECTIONS-ORDER-010: a trip the caller cannot open, a place of another trip, or half a pair is stored as null', async () => {
const { user } = await makeUser(orm());
const { user: other } = await makeUser(orm());
await makeCategory(orm());
const mine = await makeTrip(orm(), user.id);
const theirs = await makeTrip(orm(), other.id);
const minePlace = await makePlace(orm(), mine.id, { name: 'Mine' });
const theirPlace = await makePlace(orm(), theirs.id, { name: 'Theirs' });
const col = await svc.createCollection(user.id, { name: 'Mine' });
const claims = [
{ source_trip_id: theirs.id, source_place_id: theirPlace.id }, // a trip they cannot open
{ source_trip_id: mine.id, source_place_id: theirPlace.id }, // a place that is not in that trip
{ source_trip_id: mine.id }, // half a pair
{ source_place_id: minePlace.id },
];
for (const [i, claim] of claims.entries()) {
const { place } = await svc.savePlace(user.id, { collection_id: col.id, name: `Claim ${i}`, ...claim });
const row = await findRow(orm(), CollectionPlaces, { id: place!.id });
expect([row?.source_trip_id, row?.source_place_id], JSON.stringify(claim)).toEqual([null, null]);
}
});
});
@@ -500,7 +500,7 @@ describe('status + updatePlace move', () => {
// ── copy to trip ─────────────────────────────────────────────────────────────
describe('copyToTrip', () => {
it('COLLECTIONS-SVC-020: reduced INSERT (itinerary defaults), skips dups, copies tags', async () => {
it('COLLECTIONS-SVC-020: reduced INSERT (itinerary defaults), skips dups, leaves tags unless asked (D9)', async () => {
const u = createUser(testDb).user;
createCategory(testDb);
const trip = createTrip(testDb, u.id);
@@ -520,7 +520,7 @@ describe('copyToTrip', () => {
expect(inserted.reservation_status).toBe('none'); // itinerary column took the table default
expect(inserted.duration_minutes).toBe(60);
const tagLink = { n: await countRows(await orm(), Tags, { place_tags_inverse: inserted.id }) };
expect(tagLink).toEqual({ n: 1 });
expect(tagLink).toEqual({ n: 0 }); // collections.copy-to-trip.test.ts covers the tags that are asked for
});
it('COLLECTIONS-SVC-021: rejects place_ids from a collection the user cannot see', async () => {
@@ -0,0 +1,126 @@
/**
* PLC-22: a KML or KMZ map read into a list file. Pins become places, a line,
* an area or a placemark without geometry is named with its reason, each
* place keeps its folder beside the file, and a refusal carries the code the
* client translates. Nothing here touches a table.
*/
import { CollectionMapError } from '../../../../src/nest/place-import/place-import.types';
import {
CollectionKmlProvider,
kmlToCollectionFile,
} from '../../../../src/nest/place-import/providers/collection-kml.provider';
import { KmlProvider } from '../../../../src/nest/place-import/providers/kml.provider';
import { buildPlaceImportService } from '../../../helpers/place-import';
import { COLLECTION_FILE_FORMAT, collectionFilePlaceSchema, MAX_COLLECTION_FILE_PLACES } from '@trek/shared';
import archiver from 'archiver';
import { PassThrough } from 'stream';
import { describe, expect, it } from 'vitest';
const KML = `<?xml version="1.0"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>Lisbon</name>
<Placemark><name>Rossio</name><description>The square</description><Point><coordinates>-9.14,38.71</coordinates></Point></Placemark>
<Folder><name>Views</name>
<Placemark><name>Miradouro</name><Point><coordinates>-9.13,38.72,0</coordinates></Point></Placemark>
<Placemark><Point><coordinates>-9.15,38.70</coordinates></Point></Placemark>
<Placemark><name>Tram 28</name><LineString><coordinates>-9.14,38.71 -9.13,38.72</coordinates></LineString></Placemark>
<Placemark><name>Park</name><Polygon><outerBoundaryIs><LinearRing><coordinates>-9.1,38.7 -9.2,38.7 -9.2,38.8 -9.1,38.7</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
</Folder>
<Placemark><name>Nowhere</name></Placemark>
<Placemark><name>Off the map</name><Point><coordinates>-9.1,95</coordinates></Point></Placemark>
</Document></kml>`;
/** A KMZ archive holding these entries. */
async function kmz(entries: Record<string, string>): Promise<Buffer> {
const chunks: Buffer[] = [];
const output = new PassThrough();
output.on('data', (chunk: Buffer) => chunks.push(chunk));
const archive = archiver('zip', { zlib: { level: 1 } });
archive.pipe(output);
for (const [name, content] of Object.entries(entries)) archive.append(Buffer.from(content), { name });
await archive.finalize();
return Buffer.concat(chunks);
}
/** The code of the refusal a read ends in. */
async function refusal(read: Promise<unknown>): Promise<string> {
try {
await read;
} catch (err) {
if (err instanceof CollectionMapError) return err.code;
throw err;
}
throw new Error('expected a refusal');
}
describe('CollectionKmlProvider.read', () => {
const provider = new CollectionKmlProvider(new KmlProvider());
it('COLLECTION-KML-001: pins become places with their folder, everything else is named with its reason', async () => {
const read = await provider.read(Buffer.from(KML), 'Lisbon trip.kml');
expect(read.file).toMatchObject({ format: COLLECTION_FILE_FORMAT, version: 1, name: 'Lisbon trip' });
// A level's own placemarks come before its folders', as the trip import reads them.
expect(read.file.places).toEqual([
{ name: 'Rossio', description: 'The square', lat: 38.71, lng: -9.14, status: 'idea' },
{ name: 'Miradouro', description: null, lat: 38.72, lng: -9.13, status: 'idea' },
// An unnamed pin is numbered by where it stands among the placemarks, as the trip import names it.
{ name: 'Placemark 5', description: null, lat: 38.7, lng: -9.15, status: 'idea' },
]);
expect(read.folders).toEqual([null, 'Views', 'Views']);
expect(read.skipped).toEqual([
{ name: 'Nowhere', folder: null, reason: 'no_point' },
{ name: 'Off the map', folder: null, reason: 'invalid' },
{ name: 'Tram 28', folder: 'Views', reason: 'line' },
{ name: 'Park', folder: 'Views', reason: 'no_point' },
]);
// Each place passes the contract the import applies to it again.
for (const place of read.file.places) expect(collectionFilePlaceSchema.safeParse(place).success).toBe(true);
});
it('COLLECTION-KML-002: a KMZ is unpacked by its extension and read the same way', async () => {
const archive = await kmz({ 'doc.kml': KML, 'images/pin.png': 'png' });
const read = await provider.read(archive, 'Lisbon.KMZ');
expect(read.file.name).toBe('Lisbon');
expect(read.file.places.map((p) => (p as { name: string }).name)).toEqual(['Rossio', 'Miradouro', 'Placemark 5']);
});
it('COLLECTION-KML-003: another file type, a broken document and an archive without KML are refused with their code', async () => {
expect(await refusal(provider.read(Buffer.from(KML), 'lisbon.gpx'))).toBe('not-map');
expect(await refusal(provider.read(Buffer.from('<kml><Document>'), 'broken.kml'))).toBe('unreadable');
expect(await refusal(provider.read(await kmz({ 'photo.jpg': 'jpeg' }), 'photos.kmz'))).toBe('unreadable');
expect(await refusal(provider.read(Buffer.from('not a zip'), 'broken.kmz'))).toBe('unreadable');
});
it('COLLECTION-KML-004: reaches the place import service as readCollectionMap', async () => {
const read = await buildPlaceImportService().readCollectionMap(Buffer.from(KML), 'map.kml');
expect(read.file.places).toHaveLength(3);
});
});
describe('kmlToCollectionFile', () => {
const summary = { totalPlacemarks: 0, createdCount: 0, skippedCount: 0, warnings: [], errors: [] };
const pin = (name: string) => ({ name, description: null, lat: 1, lng: 2, folderName: null, routeGeometry: null });
it(`COLLECTION-KML-005: more than ${MAX_COLLECTION_FILE_PLACES} pins are refused rather than cut`, () => {
const placemarks = Array.from({ length: MAX_COLLECTION_FILE_PLACES + 1 }, (_, i) => pin(`Pin ${i}`));
expect(() => kmlToCollectionFile({ placemarks, summary }, 'big.kml')).toThrow(CollectionMapError);
});
it('COLLECTION-KML-006: a file whose places would not fit the import body again is refused as too large', () => {
const long = 'x'.repeat(5000);
const placemarks = Array.from({ length: 300 }, (_, i) => ({ ...pin(`Pin ${i}`), description: long }));
try {
kmlToCollectionFile({ placemarks, summary }, 'long.kml');
expect.unreachable('expected a refusal');
} catch (err) {
expect((err as CollectionMapError).code).toBe('too-large');
}
});
it('COLLECTION-KML-007: a file name without a usable name gives the list a plain one, a long one is cut', () => {
expect(kmlToCollectionFile({ placemarks: [], summary }, '.kml').file.name).toBe('KML import');
expect(kmlToCollectionFile({ placemarks: [], summary }, `${'a'.repeat(200)}.kml`).file.name).toHaveLength(120);
});
});
@@ -1,6 +1,8 @@
import {
COLLECTION_GPX_PLACE_FIELDS,
MAX_COLLECTION_FILE_BYTES,
COLLECTION_FILE_FORMAT,
collectionMapReadResultSchema,
collectionFilePlaceSchema,
collectionGpxReadRequestSchema,
} from './collection-file.schema';
@@ -56,3 +58,21 @@ describe('collectionFilePlaceSchema website (#2483)', () => {
expect(place('Chapelle').website).toBeNull();
});
});
describe('collectionMapReadResultSchema (PLC-22)', () => {
const file = { format: COLLECTION_FILE_FORMAT, version: 1, name: 'Lisbon', places: [{ name: 'Miradouro' }] };
it('carries the file, a folder per place and every placemark left out with its reason', () => {
const read = {
file,
folders: ['Views'],
skipped: [{ name: 'Tram 28', folder: null, reason: 'line' }],
};
expect(collectionMapReadResultSchema.parse(read)).toEqual(read);
});
it('refuses a skip reason it does not know', () => {
const read = { file, folders: [null], skipped: [{ name: null, folder: null, reason: 'polygon' }] };
expect(collectionMapReadResultSchema.safeParse(read).success).toBe(false);
});
});
@@ -285,6 +285,50 @@ export interface CollectionGpxReadResult {
track_points: number;
}
/*
* ── KML and KMZ in (PLC-22) ──────────────────────────────────────────────
*
* Google My Maps and Google Earth hand out KML or KMZ. Read the same way as a
* GPX: the server turns the uploaded file into a list file and touches no
* table, the browser shows it, and what the user keeps of it goes through the
* same import routes as any other file.
*/
/** The most bytes a KML or KMZ upload may have, the trip map import's cap. */
export const MAX_COLLECTION_MAP_UPLOAD_BYTES = 10 * 1024 * 1024;
/** Why a KML or KMZ file was not read, as the `code` of the 4xx that says so. */
export const COLLECTION_MAP_PROBLEMS = ['no-file', 'not-map', 'unreadable', 'too-large', 'too-many-places'] as const;
export type CollectionMapProblem = (typeof COLLECTION_MAP_PROBLEMS)[number];
/**
* Why a placemark did not become a place: `line` for a path (a list has no
* lines), `no_point` for an area or a placemark without any geometry,
* `invalid` for one the place contract refused (coordinates out of range).
*/
export const COLLECTION_MAP_SKIP_REASONS = ['line', 'no_point', 'invalid'] as const;
export type CollectionMapSkipReason = (typeof COLLECTION_MAP_SKIP_REASONS)[number];
export const collectionMapReadResultSchema = z.object({
/** The list file the map amounts to, ready for the import routes. */
file: collectionFileSchema,
/**
* The KML folder each place sat in, by its index in `file.places` (null at
* the top level). Carried for a later mapping onto categories or labels; the
* import does not read it.
*/
folders: z.array(z.string().nullable()),
/** Every placemark that did not become a place, in document order. */
skipped: z.array(
z.object({
name: z.string().nullable(),
folder: z.string().nullable(),
reason: z.enum(COLLECTION_MAP_SKIP_REASONS),
}),
),
});
export type CollectionMapReadResult = z.infer<typeof collectionMapReadResultSchema>;
export interface CollectionGpxExport {
/** The list's name, for the file name. */
name: string;
@@ -1,8 +1,10 @@
import {
collectionCopyToTripRequestSchema,
collectionDeleteManyRequestSchema,
collectionItemsRequestSchema,
collectionMembershipSchema,
collectionPlacesPageRequestSchema,
collectionPlacesReorderRequestSchema,
collectionPlaceUpdateRequestSchema,
collectionReorderRequestSchema,
COLLECTION_PLACES_PAGE_DEFAULT,
@@ -161,3 +163,34 @@ describe('collectionPlacesPageRequestSchema', () => {
expect(COLLECTION_PLACES_PAGE_DEFAULT).toBe(100);
});
});
describe('collectionCopyToTripRequestSchema', () => {
// D9: notes and tags only travel when asked for, so an older body still parses and carries neither.
it('takes the old body as it was, and the two opt-ins beside it', () => {
expect(collectionCopyToTripRequestSchema.parse({ trip_id: 3, place_ids: [1] })).toEqual({
trip_id: 3,
place_ids: [1],
});
const full = { trip_id: 3, place_ids: [1, 2], force: true, include_notes: true, tag_ids: [7, 8] };
expect(collectionCopyToTripRequestSchema.parse(full)).toEqual(full);
});
it('refuses a fractional tag id and more than 50 of them', () => {
expect(collectionCopyToTripRequestSchema.safeParse({ trip_id: 3, place_ids: [1], tag_ids: [1.5] }).success).toBe(
false,
);
const many = Array.from({ length: 51 }, (_, i) => i + 1);
expect(collectionCopyToTripRequestSchema.safeParse({ trip_id: 3, place_ids: [1], tag_ids: many }).success).toBe(
false,
);
});
});
describe('collectionPlacesReorderRequestSchema', () => {
// PLC-03: a list's places in the order its members want them.
it('takes the ids in order and refuses an empty list or a fractional id', () => {
expect(collectionPlacesReorderRequestSchema.parse({ orderedIds: [5, 3, 4] })).toEqual({ orderedIds: [5, 3, 4] });
expect(collectionPlacesReorderRequestSchema.safeParse({ orderedIds: [] }).success).toBe(false);
expect(collectionPlacesReorderRequestSchema.safeParse({ orderedIds: [1.5] }).success).toBe(false);
});
});
+35 -1
View File
@@ -271,11 +271,28 @@ export const collectionDeleteManyRequestSchema = z.object({
});
export type CollectionDeleteManyRequest = z.infer<typeof collectionDeleteManyRequestSchema>;
/** Copy one or many saved places INTO a trip (dedup precheck on server). */
/**
* Copy one or many saved places INTO a trip (dedup precheck on server).
*
* A saved place's notes and tags stay in the list unless the request asks for
* them (D9): a note is often private, and a tag is somebody's own. Older clients
* that send neither field get the places without both.
*/
export const collectionCopyToTripRequestSchema = z.object({
trip_id: z.number().int(),
place_ids: z.array(z.number().int()).min(1),
force: z.boolean().optional(),
include_notes: z
.boolean()
.optional()
.describe("true copies each saved place's notes into the trip; left out or false, the notes stay in the list"),
tag_ids: z
.array(z.number().int())
.max(50)
.optional()
.describe(
'Ids of tags the saved places carry that should come along. Each becomes a tag of the trip, reusing a trip tag of the same name; ids a place does not carry are ignored. Left out, no tags are copied',
),
});
export type CollectionCopyToTripRequest = z.infer<typeof collectionCopyToTripRequestSchema>;
@@ -287,6 +304,23 @@ export const collectionCopyToTripResponseSchema = z.object({
});
export type CollectionCopyToTripResponse = z.infer<typeof collectionCopyToTripResponseSchema>;
/** The most places one reorder names; well past the size lists grow to. */
export const MAX_COLLECTION_REORDER_PLACES = 10000;
/**
* A list's places in the order its members want them (PLC-03). Every id must
* be a place of that list. Places it leaves out (saved by someone else since
* the list was loaded) keep their relative order and follow the named ones.
*/
export const collectionPlacesReorderRequestSchema = z.object({
orderedIds: z
.array(z.number().int())
.min(1)
.max(MAX_COLLECTION_REORDER_PLACES)
.describe("The list's place ids (collection place ids) in the new order, first to last"),
});
export type CollectionPlacesReorderRequest = z.infer<typeof collectionPlacesReorderRequestSchema>;
/** Saved places and labels asked for by their ids, across every list the caller can see (get_collection_items). */
export const collectionItemsRequestSchema = z.object({
placeIds: z.array(idSchema).max(50).optional(),
+30 -1
View File
@@ -118,9 +118,18 @@ const collection: TranslationStrings = {
'collections.importDoneSkipped.few': '{count} أماكن كانت في القائمة بالفعل وبقيت كما هي',
'collections.importDoneSkipped.many': '{count} مكانًا كانت في القائمة بالفعل وبقيت كما هي',
'collections.importDoneClean': 'جميعها الآن في {name}',
'collections.sort.default': 'افتراضي',
'collections.sort.default': 'ترتيبي الخاص',
'collections.reorderBlocked': 'امسح البحث والفلاتر لتتمكن من سحب الأماكن إلى ترتيبك الخاص.',
'collections.reorderHandle': 'انقل {name} أو استخدم مفاتيح الأسهم',
'collections.sort.nameAsc': 'الاسم (أ–ي)',
'collections.coordinates': 'الإحداثيات',
'collections.findPosition': 'العثور على الموقع',
'collections.findPositionPlaceholder': 'ابحث عن هذا المكان على الخريطة',
'collections.findPositionHint':
'ليس لهذا المكان إحداثيات بعد، لذا لا يظهر على الخريطة. ابحث عنه أدناه واختر النتيجة الصحيحة.',
'collections.findPositionPicked': 'تم اختيار الموقع. احفظ ليظهر المكان على الخريطة.',
'collections.addNoPositionHint':
'من دون اختيار نتيجة من البحث أعلاه، لن تكون لهذا المكان إحداثيات ولن يظهر على الخريطة.',
'collections.showList': 'إظهار القائمة',
'collections.expandMap': 'توسيع الخريطة',
'collections.hero.mine': 'مجموعتي',
@@ -181,6 +190,12 @@ const collection: TranslationStrings = {
'collections.copyN.few': 'نسخ {count} أماكن إلى رحلة',
'collections.copyN.many': 'نسخ {count} مكانًا إلى رحلة',
'collections.copyToTripSearch': 'البحث عن الرحلات',
'collections.copyCarry.title': 'ما يُصطحب معه',
'collections.copyCarry.notes': 'ملاحظات',
'collections.copyCarry.notesHint':
'عند الإيقاف تبقى الملاحظات في القائمة، وعند التشغيل يمكن لكل من في الرحلة قراءتها.',
'collections.copyCarry.tags': 'الوسوم',
'collections.copyCarry.tagsHint': 'يصبح الوسم المختار وسمًا للرحلة ويظهر لكل المسافرين معك.',
'collections.searchLists': 'بحث في القوائم',
'collections.copyToTripConfirm': 'نسخ',
'collections.noTrips': 'لا توجد رحلات بعد',
@@ -323,6 +338,20 @@ const collection: TranslationStrings = {
'يحتوي هذا الملف أيضًا على {count} نقطة مسار. لا تُستورد المسارات، بل نقاط الطريق فقط.',
'collections.file.gpxEmpty': 'لا يحتوي ملف GPX هذا على نقاط طريق، فلا يوجد ما يُستورد.',
'collections.file.errorNotGpx': 'هذا ليس ملف GPX.',
'collections.file.errorNotMap': 'هذا الملف ليس خريطة KML أو KMZ يمكن لـ TREK قراءتها.',
'collections.file.mapPicked': 'تم اختيار {picked} من {total}',
'collections.file.mapAll': 'اختيار الكل',
'collections.file.mapNone': 'عدم اختيار أي شيء',
'collections.file.mapSkipped': 'استُبعد {count} إدخال',
'collections.file.mapSkipped.zero': 'لم يُستبعد أي إدخال',
'collections.file.mapSkipped.one': 'استُبعد إدخال واحد',
'collections.file.mapSkipped.two': 'استُبعد إدخالان',
'collections.file.mapSkipped.few': 'استُبعدت {count} إدخالات',
'collections.file.mapSkipped.many': 'استُبعد {count} إدخالًا',
'collections.file.mapUnnamed': 'بلا اسم',
'collections.file.mapSkipLine': 'خط وليس مكانًا',
'collections.file.mapSkipNoPoint': 'مساحة أو بلا موقع',
'collections.file.mapSkipInvalid': 'إحداثيات خارج النطاق',
'collections.file.errorTooManyPlaces':
'يحتوي هذا الملف على أكثر من {count} مكان. قسّمه واستورد الأجزاء واحدًا تلو الآخر.',
'collections.file.errorTooManyPlaces.zero':
+2
View File
@@ -30,6 +30,8 @@ const map: TranslationStrings = {
'تم حظر الوصول إلى الموقع. تحقق من إعدادات الجهاز؛ فالتطبيق المثبت لديه إذن موقع خاص به منفصل عن المتصفح.',
'map.location.unavailable': 'تعذر تحديد موقعك.',
'map.location.timeout': 'استغرق تحديد موقعك وقتًا طويلًا. حاول مرة أخرى تحت سماء مكشوفة.',
'map.placeNames.show': 'إظهار أسماء الأماكن',
'map.placeNames.hide': 'إخفاء أسماء الأماكن',
'map.overview.show': 'عرض الرحلة كاملة',
'map.lock.lock': 'قفل عرض الخريطة',
'map.lock.unlock': 'دع الخريطة تتبع التحديد',
+26 -1
View File
@@ -70,9 +70,18 @@ const collection: TranslationStrings = {
'collections.importDoneSkipped': '{count} məkan artıq siyahıda olduğu üçün dəyişdirilmədi',
'collections.importDoneSkipped.one': '{count} məkan artıq siyahıda olduğu üçün dəyişdirilmədi',
'collections.importDoneClean': 'İndi hamısı {name} siyahısındadır',
'collections.sort.default': 'Standart',
'collections.sort.default': 'Öz sıram',
'collections.reorderBlocked': 'Yerləri öz sırana çəkmək üçün axtarışı və filtrləri təmizlə.',
'collections.reorderHandle': '{name} yerini köçür və ya ox düymələrindən istifadə et',
'collections.sort.nameAsc': 'Ad (A–Z)',
'collections.coordinates': 'Koordinatlar',
'collections.findPosition': 'Mövqeyi tap',
'collections.findPositionPlaceholder': 'Bu məkanı xəritədə axtar',
'collections.findPositionHint':
'Bu məkanın hələ koordinatları yoxdur, buna görə xəritədə görünmür. Aşağıda axtar və düzgün nəticəni seç.',
'collections.findPositionPicked': 'Mövqe seçildi. Məkanı xəritəyə əlavə etmək üçün yadda saxla.',
'collections.addNoPositionHint':
'Yuxarıdakı axtarışdan nəticə seçilməsə, bu məkanın koordinatları olmayacaq və xəritədə görünməyəcək.',
'collections.showList': 'Siyahını göstər',
'collections.expandMap': 'Xəritəni genişləndir',
'collections.hero.mine': 'Mənim kolleksiyam',
@@ -125,6 +134,12 @@ const collection: TranslationStrings = {
'collections.copyN': '{count} məkanı səyahətə kopyala',
'collections.copyN.one': 'Səyahətə kopyala',
'collections.copyToTripSearch': 'Səyahətləri axtar',
'collections.copyCarry.title': 'Özünlə apar',
'collections.copyCarry.notes': 'Qeydlər',
'collections.copyCarry.notesHint':
'Söndürülü olduqda qeydlər siyahıda qalır, aktiv olduqda səyahətdəki hər kəs onları oxuya bilər.',
'collections.copyCarry.tags': 'Etiketlər',
'collections.copyCarry.tagsHint': 'Seçilmiş etiket səyahətin etiketinə çevrilir və yol yoldaşları ilə paylaşılır.',
'collections.searchLists': 'Siyahıları axtar',
'collections.copyToTripConfirm': 'Kopyala',
'collections.noTrips': 'Hələ səyahət yoxdur',
@@ -220,6 +235,16 @@ const collection: TranslationStrings = {
'Bu faylda həmçinin {count} iz nöqtəsi var. İzlər deyil, yalnız yol nöqtələri idxal edilir.',
'collections.file.gpxEmpty': 'Bu GPX faylında yol nöqtəsi yoxdur, buna görə idxal ediləcək heç nə yoxdur.',
'collections.file.errorNotGpx': 'Bu, GPX faylı deyil.',
'collections.file.errorNotMap': 'Bu fayl TREK-in oxuya biləcəyi KML və ya KMZ xəritəsi deyil.',
'collections.file.mapPicked': '{total} içindən {picked} seçildi',
'collections.file.mapAll': 'Hamısını seç',
'collections.file.mapNone': 'Heç birini seçmə',
'collections.file.mapSkipped': '{count} qeyd kənarda qalır',
'collections.file.mapSkipped.one': '{count} qeyd kənarda qalır',
'collections.file.mapUnnamed': 'Adsız',
'collections.file.mapSkipLine': 'xətt, məkan deyil',
'collections.file.mapSkipNoPoint': 'sahə və ya mövqesiz',
'collections.file.mapSkipInvalid': 'koordinatlar diapazondan kənardadır',
'collections.file.errorTooManyPlaces':
'Bu faylda {count} ədəddən çox məkan var. Faylı hissələrə bölün və hər hissəni ayrıca idxal edin.',
'collections.file.errorTooManyPlaces.one':
+2
View File
@@ -35,6 +35,8 @@ const map: TranslationStrings = {
'map.location.unavailable': 'Mövcud yerinizi müəyyən etmək mümkün olmadı.',
'map.location.timeout':
'Məkanınızı müəyyən etmək çox vaxt apardı. Səmanın daha açıq göründüyü yerdə yenidən cəhd edin.',
'map.placeNames.show': 'Məkan adlarını göstər',
'map.placeNames.hide': 'Məkan adlarını gizlət',
'map.overview.show': 'Bütün səyahəti göstər',
'map.lock.lock': 'Xəritə görünüşünü kilidlə',
+26 -1
View File
@@ -70,9 +70,18 @@ const collection: TranslationStrings = {
'collections.importDoneSkipped': '{count} já estavam na lista e ficaram como estavam',
'collections.importDoneSkipped.one': '{count} já estava na lista e ficou como estava',
'collections.importDoneClean': 'Agora estão todos em {name}',
'collections.sort.default': 'Padrão',
'collections.sort.default': 'Ordem própria',
'collections.reorderBlocked': 'Limpe a busca e os filtros para arrastar os lugares para a sua própria ordem.',
'collections.reorderHandle': 'Mover {name}, ou usar as setas do teclado',
'collections.sort.nameAsc': 'Nome (A–Z)',
'collections.coordinates': 'Coordenadas',
'collections.findPosition': 'Encontrar a posição',
'collections.findPositionPlaceholder': 'Buscar este lugar no mapa',
'collections.findPositionHint':
'Este lugar ainda não tem coordenadas e por isso não aparece no mapa. Busque-o abaixo e escolha o resultado certo.',
'collections.findPositionPicked': 'Posição escolhida. Salve para colocar o lugar no mapa.',
'collections.addNoPositionHint':
'Sem escolher um resultado da busca acima, este lugar fica sem coordenadas e não aparece no mapa.',
'collections.showList': 'Mostrar lista',
'collections.expandMap': 'Ampliar mapa',
'collections.hero.mine': 'Minha coleção',
@@ -125,6 +134,12 @@ const collection: TranslationStrings = {
'collections.copyN': 'Copiar {count} para viagem',
'collections.copyN.one': 'Copiar {count} para viagem',
'collections.copyToTripSearch': 'Buscar viagens',
'collections.copyCarry.title': 'Levar junto',
'collections.copyCarry.notes': 'Notas',
'collections.copyCarry.notesHint': 'Desativado, as notas ficam na lista. Ativado, todos da viagem podem lê-las.',
'collections.copyCarry.tags': 'Etiquetas',
'collections.copyCarry.tagsHint':
'Uma etiqueta escolhida passa a ser uma etiqueta da viagem, compartilhada com os viajantes.',
'collections.searchLists': 'Buscar listas',
'collections.copyToTripConfirm': 'Copiar',
'collections.noTrips': 'Nenhuma viagem ainda',
@@ -218,6 +233,16 @@ const collection: TranslationStrings = {
'Este arquivo também tem {count} ponto de trilha. Trilhas não são importadas, apenas pontos de referência.',
'collections.file.gpxEmpty': 'Este arquivo GPX não tem pontos de referência, então não há nada para importar.',
'collections.file.errorNotGpx': 'Esse não é um arquivo GPX.',
'collections.file.errorNotMap': 'Este arquivo não é um mapa KML ou KMZ que o TREK consiga ler.',
'collections.file.mapPicked': '{picked} de {total} escolhidos',
'collections.file.mapAll': 'Escolher todos',
'collections.file.mapNone': 'Não escolher nenhum',
'collections.file.mapSkipped': '{count} entradas ficam de fora',
'collections.file.mapSkipped.one': '{count} entrada fica de fora',
'collections.file.mapUnnamed': 'Sem nome',
'collections.file.mapSkipLine': 'uma linha, não um lugar',
'collections.file.mapSkipNoPoint': 'uma área ou sem posição',
'collections.file.mapSkipInvalid': 'coordenadas fora do intervalo',
'collections.file.errorTooManyPlaces':
'Esse arquivo tem mais de {count} lugares. Divida-o e importe as partes uma de cada vez.',
'collections.file.errorTooManyPlaces.one':
+2
View File
@@ -31,6 +31,8 @@ const map: TranslationStrings = {
'O acesso à localização está bloqueado. Verifique as configurações do aparelho; um app instalado tem permissão de localização própria, separada do navegador.',
'map.location.unavailable': 'Não foi possível determinar sua localização.',
'map.location.timeout': 'A localização demorou demais. Tente de novo com uma visão mais aberta do céu.',
'map.placeNames.show': 'Mostrar nomes de lugares',
'map.placeNames.hide': 'Ocultar nomes de lugares',
'map.overview.show': 'Mostrar a viagem inteira',
'map.lock.lock': 'Travar a visualização do mapa',
'map.lock.unlock': 'Deixar o mapa seguir a seleção',
+27 -1
View File
@@ -70,9 +70,18 @@ const collection: TranslationStrings = {
'collections.importDoneSkipped': '{count} ja hi eren i s’han deixat igual',
'collections.importDoneSkipped.one': '{count} ja hi era i s’ha deixat igual',
'collections.importDoneClean': 'Ara són tots a {name}',
'collections.sort.default': 'Predeterminat',
'collections.sort.default': 'Ordre propi',
'collections.reorderBlocked': 'Esborra la cerca i els filtres per arrossegar els llocs al teu propi ordre.',
'collections.reorderHandle': 'Mou {name} o fes servir les tecles de fletxa',
'collections.sort.nameAsc': 'Nom (A–Z)',
'collections.coordinates': 'Coordenades',
'collections.findPosition': 'Trobar la posició',
'collections.findPositionPlaceholder': 'Cerca aquest lloc al mapa',
'collections.findPositionHint':
'Aquest lloc encara no té coordenades, per això no surt al mapa. Cerca’l a sota i tria el resultat correcte.',
'collections.findPositionPicked': 'Posició triada. Desa per posar el lloc al mapa.',
'collections.addNoPositionHint':
'Sense triar un resultat de la cerca de dalt, aquest lloc no tindrà coordenades i no sortirà al mapa.',
'collections.showList': 'Mostra la llista',
'collections.expandMap': 'Ampliar el mapa',
'collections.hero.mine': 'La meva col·lecció',
@@ -120,6 +129,13 @@ const collection: TranslationStrings = {
'collections.copyN': 'Copia {count} al viatge',
'collections.copyN.one': 'Copia al viatge',
'collections.copyToTripSearch': 'Cercar viatges',
'collections.copyCarry.title': 'Emporta’t',
'collections.copyCarry.notes': 'Notes', // same-as-en
'collections.copyCarry.notesHint':
'Desactivat, les notes es queden a la llista. Activat, tothom al viatge les pot llegir.',
'collections.copyCarry.tags': 'Etiquetes',
'collections.copyCarry.tagsHint':
'Una etiqueta triada passa a ser una etiqueta del viatge, compartida amb els viatgers.',
'collections.searchLists': 'Cerca llistes',
'collections.copyToTripConfirm': 'Copiar',
'collections.noTrips': 'Encara no hi ha viatges',
@@ -209,6 +225,16 @@ const collection: TranslationStrings = {
'Aquest fitxer també té {count} punt de traça. Les traces no s’importen, només els punts de pas.',
'collections.file.gpxEmpty': 'Aquest fitxer GPX no té punts de pas, així que no hi ha res per importar.',
'collections.file.errorNotGpx': 'Això no és un fitxer GPX.',
'collections.file.errorNotMap': 'Aquest fitxer no és un mapa KML o KMZ que TREK pugui llegir.',
'collections.file.mapPicked': '{picked} de {total} triats',
'collections.file.mapAll': 'Tria-ho tot',
'collections.file.mapNone': 'No triïs res',
'collections.file.mapSkipped': '{count} entrades es deixen fora',
'collections.file.mapSkipped.one': '{count} entrada es deixa fora',
'collections.file.mapUnnamed': 'Sense nom',
'collections.file.mapSkipLine': 'una línia, no un lloc',
'collections.file.mapSkipNoPoint': 'una àrea o sense posició',
'collections.file.mapSkipInvalid': 'coordenades fora de rang',
'collections.file.errorTooManyPlaces':
'Aquest fitxer té més de {count} llocs. Divideix-lo i importa’n les parts d’una en una.',
'collections.file.errorTooManyPlaces.one':
+2
View File
@@ -31,6 +31,8 @@ const map: TranslationStrings = {
'L’accés a la ubicació està bloquejat. Revisa la configuració del dispositiu; una app instal·lada té el seu propi permís d’ubicació, separat del navegador.',
'map.location.unavailable': 'No s’ha pogut determinar la teva ubicació.',
'map.location.timeout': 'La localització ha trigat massa. Torna-ho a provar amb una vista més clara del cel.',
'map.placeNames.show': 'Mostra els noms dels llocs',
'map.placeNames.hide': 'Amaga els noms dels llocs',
'map.overview.show': 'Mostra tot el viatge',
'map.lock.lock': 'Bloqueja la vista del mapa',
'map.lock.unlock': 'Deixa que el mapa segueixi la selecció',

Some files were not shown because too many files have changed in this diff Show More