diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.json index f57edfb5c..d5a6c160e 100644 --- a/client/scripts/feature-pairs.json +++ b/client/scripts/feature-pairs.json @@ -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"], diff --git a/client/scripts/size-baseline.json b/client/scripts/size-baseline.json index 621a1bd7c..d70f63ce7 100644 --- a/client/scripts/size-baseline.json +++ b/client/scripts/size-baseline.json @@ -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, diff --git a/client/src/api/collections.test.ts b/client/src/api/collections.test.ts index c0796d3e0..4daca74a7 100644 --- a/client/src/api/collections.test.ts +++ b/client/src/api/collections.test.ts @@ -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: '', 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([''], 'lisbon.kml')) + + expect(upload).not.toBeNull() + expect((upload as unknown as File).name).toBe('lisbon.kml') + expect(res).toEqual(read) + }) }) diff --git a/client/src/api/collections.ts b/client/src/api/collections.ts index bce9d0a5e..f737b182b 100644 --- a/client/src/api/collections.ts +++ b/client/src/api/collections.ts @@ -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 => 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 => { + 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 => ax.get(`${base}/${id}/export/kml`).then((r: AxiosResponse) => r.data), @@ -94,6 +102,10 @@ export const collectionsApi = { reorder: (orderedIds: number[]): Promise => 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 => ax.post(`${base}/places`, body satisfies CollectionSavePlaceRequest).then((r: AxiosResponse) => r.data), saveFromTrip: (body: CollectionSaveFromTripRequest): Promise => diff --git a/client/src/components/Collections/AddPlaceToCollectionModal.test.tsx b/client/src/components/Collections/AddPlaceToCollectionModal.test.tsx index 8ea653c5a..161521f80 100644 --- a/client/src/components/Collections/AddPlaceToCollectionModal.test.tsx +++ b/client/src/components/Collections/AddPlaceToCollectionModal.test.tsx @@ -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() + }) }) diff --git a/client/src/components/Collections/AddPlaceToCollectionModal.tsx b/client/src/components/Collections/AddPlaceToCollectionModal.tsx index bbceb68e0..661489cb5 100644 --- a/client/src/components/Collections/AddPlaceToCollectionModal.tsx +++ b/client/src/components/Collections/AddPlaceToCollectionModal.tsx @@ -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). */} -
- - setAddress(e.target.value)} - placeholder={t('places.formAddressPlaceholder')} - className={INPUT} - /> - -
- - - - - - -
-
+ ({ address: setAddress, lat: setLat, lng: setLng })[field](value)} + warnWithoutCoordinates + /> diff --git a/client/src/components/Collections/CollectionList.tsx b/client/src/components/Collections/CollectionList.tsx index af34ec6fd..39d822888 100644 --- a/client/src/components/Collections/CollectionList.tsx +++ b/client/src/components/Collections/CollectionList.tsx @@ -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 (
+ {reorderBlocked && ( +

{t('collections.reorderBlocked')}

+ )} {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 && ( + e.stopPropagation()} + {...reorder.handleProps(place.id)} + > + + + )} {selectMode ? ( {selected && } ) : ( diff --git a/client/src/components/Collections/CollectionLocationSearch.tsx b/client/src/components/Collections/CollectionLocationSearch.tsx new file mode 100644 index 000000000..e1bbf3918 --- /dev/null +++ b/client/src/components/Collections/CollectionLocationSearch.tsx @@ -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 ( +
+
+ {t('collections.findPosition')} +
+ {!picked && ( +

+

+ )} + {picked && ( +

+

+ )} +
{ + e.preventDefault(); + void search(); + }} + > + setQuery(e.target.value)} + placeholder={t('collections.findPositionPlaceholder')} + aria-label={t('collections.findPosition')} + className="col-detail-input flex-1" + /> + +
+ {noResults &&

{t('planner.noPlacesFound')}

} + {results.length > 0 && ( +
    + {results.map((spot, i) => ( +
  • + +
  • + ))} +
+ )} +
+ ); +} diff --git a/client/src/components/Collections/CollectionPlaceDetail.tsx b/client/src/components/Collections/CollectionPlaceDetail.tsx index c4612f9e5..6296b785a 100644 --- a/client/src/components/Collections/CollectionPlaceDetail.tsx +++ b/client/src/components/Collections/CollectionPlaceDetail.tsx @@ -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(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({ })}
+ {/* A place that has no position yet can be looked up here (#2837). */} + {needsPosition && } {/* Address (#1870): free text, the coordinates stay separate */}
{t('places.formAddress')}
diff --git a/client/src/components/Collections/CopyCarryPanel.test.tsx b/client/src/components/Collections/CopyCarryPanel.test.tsx new file mode 100644 index 000000000..1bdcd1eee --- /dev/null +++ b/client/src/components/Collections/CopyCarryPanel.test.tsx @@ -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( + + ); + 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( + + ); + expect(screen.queryByText('collections.copyCarry.notes')).toBeNull(); + expect(screen.getByRole('button', { name: 'Coffee' })).toHaveAttribute('aria-pressed', 'false'); + }); +}); diff --git a/client/src/components/Collections/CopyCarryPanel.tsx b/client/src/components/Collections/CopyCarryPanel.tsx new file mode 100644 index 000000000..66f2cdc6c --- /dev/null +++ b/client/src/components/Collections/CopyCarryPanel.tsx @@ -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 ( +
+
{t('collections.copyCarry.title')}
+ {options.hasNotes && ( +
+
+ )} + {options.tags.length > 0 && ( +
+
+ )} +
+ ); +} diff --git a/client/src/components/Collections/CopyToTripModal.test.tsx b/client/src/components/Collections/CopyToTripModal.test.tsx index 6fc5fe5b8..de43e4aa1 100644 --- a/client/src/components/Collections/CopyToTripModal.test.tsx +++ b/client/src/components/Collections/CopyToTripModal.test.tsx @@ -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); }); diff --git a/client/src/components/Collections/CopyToTripModal.tsx b/client/src/components/Collections/CopyToTripModal.tsx index b7f941d0d..35cd4a81d 100644 --- a/client/src/components/Collections/CopyToTripModal.tsx +++ b/client/src/components/Collections/CopyToTripModal.tsx @@ -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`} />
+ {offersCarry && carryOptions && ( + + )} {loading ? (
diff --git a/client/src/components/Collections/ImportCollectionModal.tsx b/client/src/components/Collections/ImportCollectionModal.tsx index 49fa38ba4..dcc7a7de3 100644 --- a/client/src/components/Collections/ImportCollectionModal.tsx +++ b/client/src/components/Collections/ImportCollectionModal.tsx @@ -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 @@ -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 = { 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(null) const titleId = useId() const nameId = useId() const [file, setFile] = useState(null) const [leftovers, setLeftovers] = useState(null) + // A map's placemarks, each one to keep or not: all of them to start with. + const [map, setMap] = useState(null) + const [picked, setPicked] = useState>(new Set()) const [name, setName] = useState('') const [error, setError] = useState(null) const [failedMessage, setFailedMessage] = useState(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 ( { void take(e.target.files?.[0]); e.target.value = '' }} /> @@ -314,7 +333,7 @@ export default function ImportCollectionModal({ {reading ? t('collections.file.reading') : t('collections.file.choose')} - {COLLECTION_FILE_EXTENSION}{COLLECTION_GPX_EXTENSION} + {COLLECTION_FILE_EXTENSION}{COLLECTION_GPX_EXTENSION}{onReadMap && <>{COLLECTION_KML_EXTENSION}{COLLECTION_KMZ_EXTENSION}} ) : ( <> @@ -322,7 +341,7 @@ export default function ImportCollectionModal({
- {leftovers ? : } + {leftovers || map ? : } {file.name} @@ -348,6 +367,16 @@ export default function ImportCollectionModal({ )} {leftovers && } + {map && ( + 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} + /> + )}
{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')} > ) => (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(); + 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(); + 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(); + }); +}); diff --git a/client/src/components/Collections/MapImportPreview.tsx b/client/src/components/Collections/MapImportPreview.tsx new file mode 100644 index 000000000..4329b8c62 --- /dev/null +++ b/client/src/components/Collections/MapImportPreview.tsx @@ -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 = { + line: 'collections.file.mapSkipLine', + no_point: 'collections.file.mapSkipNoPoint', + invalid: 'collections.file.mapSkipInvalid', +}; + +interface MapImportPreviewProps { + file: CollectionFile; + map: Pick; + /** Indexes into `file.places` that will be imported. */ + picked: Set; + 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 ( +
+
+ + {t('collections.file.mapPicked', { picked: picked.size, total: file.places.length })} + + +
+
    + {file.places.map((place, index) => { + const on = picked.has(index); + const folder = map.folders[index]; + return ( +
  • + +
  • + ); + })} +
+ {map.skipped.length > 0 && ( +
+ + {showSkipped && ( +
    + {map.skipped.map((entry, i) => ( +
  • + {entry.name || t('collections.file.mapUnnamed')}: {t(SKIP_KEYS[entry.reason])} +
  • + ))} +
+ )} +
+ )} +
+ ); +} diff --git a/client/src/components/Collections/collectionFile.test.ts b/client/src/components/Collections/collectionFile.test.ts index f5094ec0b..d98085eca 100644 --- a/client/src/components/Collections/collectionFile.test.ts +++ b/client/src/components/Collections/collectionFile.test.ts @@ -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([''], 'trip.kml'), + new File([new Uint8Array([0x50, 0x4b, 3, 4])], 'trip.kmz'), + new File([''], '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([''], '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([''], '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() + }) +}) + diff --git a/client/src/components/Collections/collectionFile.ts b/client/src/components/Collections/collectionFile.ts index a7a45b12d..ca8ec3f46 100644 --- a/client/src/components/Collections/collectionFile.ts +++ b/client/src/components/Collections/collectionFile.ts @@ -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 | 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 +/** 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 + +/** 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 { + 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 /]/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 { + 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 { +export async function readCollectionFile(file: File, readGpxFile: GpxReader, readMapFile?: MapReader): Promise { + 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 { diff --git a/client/src/components/Collections/useAddPlaceToCollection.test.ts b/client/src/components/Collections/useAddPlaceToCollection.test.ts index 85d6d0f2d..a7069dbab 100644 --- a/client/src/components/Collections/useAddPlaceToCollection.test.ts +++ b/client/src/components/Collections/useAddPlaceToCollection.test.ts @@ -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; - 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', () => { diff --git a/client/src/components/Collections/useAddPlaceToCollection.ts b/client/src/components/Collections/useAddPlaceToCollection.ts index 5d31c6043..ea2104b5e 100644 --- a/client/src/components/Collections/useAddPlaceToCollection.ts +++ b/client/src/components/Collections/useAddPlaceToCollection.ts @@ -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) => 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) => { - 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, }; } diff --git a/client/src/components/Collections/useCollectionPlaceForm.test.ts b/client/src/components/Collections/useCollectionPlaceForm.test.ts index 786990821..8696a8fec 100644 --- a/client/src/components/Collections/useCollectionPlaceForm.test.ts +++ b/client/src/components/Collections/useCollectionPlaceForm.test.ts @@ -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' }) + ); + }); }); diff --git a/client/src/components/Collections/useCollectionPlaceForm.ts b/client/src/components/Collections/useCollectionPlaceForm.ts index 7af75304c..6d3577d94 100644 --- a/client/src/components/Collections/useCollectionPlaceForm.ts +++ b/client/src/components/Collections/useCollectionPlaceForm.ts @@ -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(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, diff --git a/client/src/components/Collections/usePlaceReorder.test.ts b/client/src/components/Collections/usePlaceReorder.test.ts new file mode 100644 index 000000000..9ca8554ac --- /dev/null +++ b/client/src/components/Collections/usePlaceReorder.test.ts @@ -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> = {}) => + ({ + 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; + +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) => 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({}); + }); +}); diff --git a/client/src/components/Collections/usePlaceReorder.ts b/client/src/components/Collections/usePlaceReorder.ts new file mode 100644 index 000000000..3f3339634 --- /dev/null +++ b/client/src/components/Collections/usePlaceReorder.ts @@ -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(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) => { + 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)), + }; +} diff --git a/client/src/components/Collections/useTripCopyPicker.test.ts b/client/src/components/Collections/useTripCopyPicker.test.ts index 58856e3ea..a827a9c3d 100644 --- a/client/src/components/Collections/useTripCopyPicker.test.ts +++ b/client/src/components/Collections/useTripCopyPicker.test.ts @@ -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); + }); }); diff --git a/client/src/components/Collections/useTripCopyPicker.ts b/client/src/components/Collections/useTripCopyPicker.ts index 9e98901b8..b0a5cc21b 100644 --- a/client/src/components/Collections/useTripCopyPicker.ts +++ b/client/src/components/Collections/useTripCopyPicker.ts @@ -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; + onCopy: (tripId: number, carry: CopyCarry) => Promise; + /** 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([]); const [loading, setLoading] = useState(false); const [search, setSearch] = useState(''); const [busyTripId, setBusyTripId] = useState(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([]); + 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, + }; } diff --git a/client/src/components/Map/LeafletPlaceNames.tsx b/client/src/components/Map/LeafletPlaceNames.tsx new file mode 100644 index 000000000..3496ba6f3 --- /dev/null +++ b/client/src/components/Map/LeafletPlaceNames.tsx @@ -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; +} diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx index e38b4f3c7..2308a0a2c 100644 --- a/client/src/components/Map/MapView.tsx +++ b/client/src/components/Map/MapView.tsx @@ -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 = `${label}` - } + 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({ + {placeNames && } diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx index 7d8f8c59c..dac95549b 100644 --- a/client/src/components/Map/MapViewGL.tsx +++ b/client/src/components/Map/MapViewGL.tsx @@ -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 = `${label}` - } + 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(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(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. diff --git a/client/src/components/Map/PlaceNamesPill.test.tsx b/client/src/components/Map/PlaceNamesPill.test.tsx new file mode 100644 index 000000000..536d7ae1c --- /dev/null +++ b/client/src/components/Map/PlaceNamesPill.test.tsx @@ -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(); + 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(); + 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'); + }); +}); diff --git a/client/src/components/Map/PlaceNamesPill.tsx b/client/src/components/Map/PlaceNamesPill.tsx new file mode 100644 index 000000000..d9051f591 --- /dev/null +++ b/client/src/components/Map/PlaceNamesPill.tsx @@ -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 ( + { + void toggle(); + }} + label={on ? t('map.placeNames.hide') : t('map.placeNames.show')} + testId="place-names-pill" + icon={} + /> + ); +} diff --git a/client/src/components/Map/mapViewContract.ts b/client/src/components/Map/mapViewContract.ts index 11cc01030..d5566df8a 100644 --- a/client/src/components/Map/mapViewContract.ts +++ b/client/src/components/Map/mapViewContract.ts @@ -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 diff --git a/client/src/components/Map/placeNameLabels.test.ts b/client/src/components/Map/placeNameLabels.test.ts new file mode 100644 index 000000000..07d50b37a --- /dev/null +++ b/client/src/components/Map/placeNameLabels.test.ts @@ -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 = (node: T): T => { + if (node instanceof HTMLElement) place(node, pin.label); + return original(node); + }; + } + return container; +} + +const labels = (c: HTMLElement) => Array.from(c.querySelectorAll('.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: '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); + expect(labels(c)).toHaveLength(1); + expect(labels(c)[0].textContent).toBe('Senso-ji'); + 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([]); + }); +}); diff --git a/client/src/components/Map/placeNameLabels.ts b/client/src/components/Map/placeNameLabels.ts new file mode 100644 index 000000000..f79b4f093 --- /dev/null +++ b/client/src/components/Map/placeNameLabels.ts @@ -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(`: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(`[${PLACE_NAME_ATTR}]`)); + if (!enabled) { + container.querySelectorAll(`.${LABEL_CLASS}`).forEach((label) => label.remove()); + return; + } + const frame = container.getBoundingClientRect(); + const markerBoxes = new Map(); + 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(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'; diff --git a/client/src/components/Map/placeNames.css b/client/src/components/Map/placeNames.css new file mode 100644 index 000000000..2975bb246 --- /dev/null +++ b/client/src/components/Map/placeNames.css @@ -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; +} diff --git a/client/src/components/Map/ratingBadge.test.ts b/client/src/components/Map/ratingBadge.test.ts index 10ef7ad16..c439c5d1c 100644 --- a/client/src/components/Map/ratingBadge.test.ts +++ b/client/src/components/Map/ratingBadge.test.ts @@ -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'); + }); +}); diff --git a/client/src/components/Map/ratingBadge.ts b/client/src/components/Map/ratingBadge.ts index 35d763e67..7b0bf8788 100644 --- a/client/src/components/Map/ratingBadge.ts +++ b/client/src/components/Map/ratingBadge.ts @@ -25,3 +25,30 @@ export function ratingBadgeHtml(rating: number | null | undefined): string { box-sizing:border-box;white-space:nowrap; ">${label}`; } + +/** + * 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 `${orderNumbers.join(' · ')}`; +} diff --git a/client/src/components/Map/usePlaceNameLayout.test.ts b/client/src/components/Map/usePlaceNameLayout.test.ts new file mode 100644 index 000000000..c2945762c --- /dev/null +++ b/client/src/components/Map/usePlaceNameLayout.test.ts @@ -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)); + }); +}); diff --git a/client/src/components/Map/usePlaceNameLayout.ts b/client/src/components/Map/usePlaceNameLayout.ts new file mode 100644 index 000000000..3c18260ae --- /dev/null +++ b/client/src/components/Map/usePlaceNameLayout.ts @@ -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); +} diff --git a/client/src/components/Planner/placeCoordinates.ts b/client/src/components/Planner/placeCoordinates.ts index ac847f075..8537d4153 100644 --- a/client/src/components/Planner/placeCoordinates.ts +++ b/client/src/components/Planner/placeCoordinates.ts @@ -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); +} diff --git a/client/src/components/shared/useLocationSearch.test.ts b/client/src/components/shared/useLocationSearch.test.ts new file mode 100644 index 000000000..d49a41277 --- /dev/null +++ b/client/src/components/shared/useLocationSearch.test.ts @@ -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([]); + }); +}); diff --git a/client/src/components/shared/useLocationSearch.ts b/client/src/components/shared/useLocationSearch.ts new file mode 100644 index 000000000..0bd6cb3f5 --- /dev/null +++ b/client/src/components/shared/useLocationSearch.ts @@ -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([]); + 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 }; +} diff --git a/client/src/mobile/screens/collections/MCollAddSheet.tsx b/client/src/mobile/screens/collections/MCollAddSheet.tsx index eb956cc30..9db51d6b2 100644 --- a/client/src/mobile/screens/collections/MCollAddSheet.tsx +++ b/client/src/mobile/screens/collections/MCollAddSheet.tsx @@ -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). */} {t('places.formAddress').toUpperCase()} setAddress(e.target.value)} placeholder={t('places.formAddressPlaceholder')} className={INPUT_CLS} /> + {positionMissing && ( +

+

+ )} {t('collections.category').toUpperCase()} diff --git a/client/src/mobile/screens/collections/MCollLocationSearch.test.tsx b/client/src/mobile/screens/collections/MCollLocationSearch.test.tsx new file mode 100644 index 000000000..5b112c5d6 --- /dev/null +++ b/client/src/mobile/screens/collections/MCollLocationSearch.test.tsx @@ -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(); + expect(screen.getByText('collections.findPositionHint')).toBeInTheDocument(); + rerender(); + 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(); + 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()); + }); +}); diff --git a/client/src/mobile/screens/collections/MCollLocationSearch.tsx b/client/src/mobile/screens/collections/MCollLocationSearch.tsx new file mode 100644 index 000000000..41f9131e4 --- /dev/null +++ b/client/src/mobile/screens/collections/MCollLocationSearch.tsx @@ -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 ( + <> + {t('collections.findPosition').toUpperCase()} + {!picked && ( +

+

+ )} + {picked && ( +

+

+ )} +
{ + e.preventDefault(); + void search(); + }} + > + setQuery(e.target.value)} + placeholder={t('collections.findPositionPlaceholder')} + aria-label={t('collections.findPosition')} + enterKeyHint="search" + className={INPUT_CLS} + /> + +
+ {noResults &&

{t('planner.noPlacesFound')}

} + {results.length > 0 && ( +
    + {results.map((spot, i) => ( +
  • + +
  • + ))} +
+ )} + + ); +} diff --git a/client/src/mobile/screens/collections/MCollPlaceRow.tsx b/client/src/mobile/screens/collections/MCollPlaceRow.tsx index 29fada868..5a287d6a2 100644 --- a/client/src/mobile/screens/collections/MCollPlaceRow.tsx +++ b/client/src/mobile/screens/collections/MCollPlaceRow.tsx @@ -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 & { draggable?: boolean } + row: React.HTMLAttributes + 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 (
+ {reorder && ( + + + + )}
+ {offersCarry && carryOptions && ( +
+ +
+ )} {loading ? ( ) : filtered.length === 0 ? ( diff --git a/client/src/mobile/screens/collections/MCollections.tsx b/client/src/mobile/screens/collections/MCollections.tsx index c8e943d63..5d476f8aa 100644 --- a/client/src/mobile/screens/collections/MCollections.tsx +++ b/client/src/mobile/screens/collections/MCollections.tsx @@ -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() { } title={t('collections.empty.noMatchTitle')} /> ) : ( // Two columns of rows where the page has the room for them. + <> + {c.reorderBlocked && ( +

+ {t('collections.reorderBlocked')} +

+ )}
{c.visiblePlaces.map(p => ( 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} /> ))}
+ ) )} @@ -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} /> diff --git a/client/src/mobile/screens/trip/map/MMapArea.tsx b/client/src/mobile/screens/trip/map/MMapArea.tsx index 47ca3ca8e..9844d0ee8 100644 --- a/client/src/mobile/screens/trip/map/MMapArea.tsx +++ b/client/src/mobile/screens/trip/map/MMapArea.tsx @@ -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)]" /> )} +
)}
diff --git a/client/src/pages/CollectionsPage.tsx b/client/src/pages/CollectionsPage.tsx index 47bb876fd..3ba8a5475 100644 --- a/client/src/pages/CollectionsPage.tsx +++ b/client/src/pages/CollectionsPage.tsx @@ -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} /> diff --git a/client/src/pages/collections/collectionsModel.test.ts b/client/src/pages/collections/collectionsModel.test.ts index ee2a5e7d5..d21fd8201 100644 --- a/client/src/pages/collections/collectionsModel.test.ts +++ b/client/src/pages/collections/collectionsModel.test.ts @@ -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', () => { diff --git a/client/src/pages/collections/collectionsModel.ts b/client/src/pages/collections/collectionsModel.ts index df976c1e3..e94ec4675 100644 --- a/client/src/pages/collections/collectionsModel.ts +++ b/client/src/pages/collections/collectionsModel.ts @@ -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) + diff --git a/client/src/pages/collections/useCollections.test.tsx b/client/src/pages/collections/useCollections.test.tsx index 4cc8c5059..a5654c187 100644 --- a/client/src/pages/collections/useCollections.test.tsx +++ b/client/src/pages/collections/useCollections.test.tsx @@ -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) => {}), 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 & { id: number }), + place({ id: 5, notes: 'Go early', tags: [{ id: 7, name: 'Coffee', color: '#f00' }, { id: 8, name: 'Late' }] } as Partial & { 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 }) + }) }) diff --git a/client/src/pages/collections/useCollections.ts b/client/src/pages/collections/useCollections.ts index 83dc48f41..2ca1e1cb6 100644 --- a/client/src/pages/collections/useCollections.ts +++ b/client/src/pages/collections/useCollections.ts @@ -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(() => { + const picked = places.filter(p => (copyIds ?? []).includes(p.id)) + const tags = new Map() + 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, diff --git a/client/src/pages/tripPlanner/PlanMapStage.tsx b/client/src/pages/tripPlanner/PlanMapStage.tsx index 3be3842c4..715968693 100644 --- a/client/src/pages/tripPlanner/PlanMapStage.tsx +++ b/client/src/pages/tripPlanner/PlanMapStage.tsx @@ -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 ( <> )} + {/* 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 diff --git a/client/src/repo/mapMatchRepo.test.ts b/client/src/repo/mapMatchRepo.test.ts index e912db2a6..7ef0ee58c 100644 --- a/client/src/repo/mapMatchRepo.test.ts +++ b/client/src/repo/mapMatchRepo.test.ts @@ -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(); + }); +}); diff --git a/client/src/repo/mapMatchRepo.ts b/client/src/repo/mapMatchRepo.ts index 0b4a62893..de340ea47 100644 --- a/client/src/repo/mapMatchRepo.ts +++ b/client/src/repo/mapMatchRepo.ts @@ -34,14 +34,32 @@ export async function findOnMap(queries: string[], lang?: string): Promise 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 { + 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); +} diff --git a/client/src/store/collectionStore.test.ts b/client/src/store/collectionStore.test.ts index d95a257c2..ebcc6c57a 100644 --- a/client/src/store/collectionStore.test.ts +++ b/client/src/store/collectionStore.test.ts @@ -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() + }) +}) diff --git a/client/src/store/collectionStore.ts b/client/src/store/collectionStore.ts index 031daf665..f937870fd 100644 --- a/client/src/store/collectionStore.ts +++ b/client/src/store/collectionStore.ts @@ -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 + /** 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 deletePlace: (placeId: number) => Promise deleteMany: (ids: number[]) => Promise - 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 moveToList: (placeIds: number[], targetId: number) => Promise duplicateToList: (placeIds: number[], targetId: number) => Promise @@ -343,11 +353,28 @@ export const useCollectionStore = create((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) => { diff --git a/client/src/styles/collections.css b/client/src/styles/collections.css index 55c177253..8dd7622e7 100644 --- a/client/src/styles/collections.css +++ b/client/src/styles/collections.css @@ -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); } diff --git a/client/src/types.ts b/client/src/types.ts index fc6e168c1..b888651d7 100644 --- a/client/src/types.ts +++ b/client/src/types.ts @@ -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 diff --git a/client/tests/unit/mobile/collections/MCollTripPickerSheet.test.tsx b/client/tests/unit/mobile/collections/MCollTripPickerSheet.test.tsx index 360994f92..585ddd0a7 100644 --- a/client/tests/unit/mobile/collections/MCollTripPickerSheet.test.tsx +++ b/client/tests/unit/mobile/collections/MCollTripPickerSheet.test.tsx @@ -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) }) diff --git a/server/scripts/mcp-inline-zod-baseline.json b/server/scripts/mcp-inline-zod-baseline.json index f8bbe3893..87afc36bd 100644 --- a/server/scripts/mcp-inline-zod-baseline.json +++ b/server/scripts/mcp-inline-zod-baseline.json @@ -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, diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json index ad3ee5073..a2f7abcd0 100644 --- a/server/scripts/size-baseline.json +++ b/server/scripts/size-baseline.json @@ -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, diff --git a/server/src/db/repositories/CollectionPlaces.repository.ts b/server/src/db/repositories/CollectionPlaces.repository.ts index 52578b0c2..9c1f5f2ff 100644 --- a/server/src/db/repositories/CollectionPlaces.repository.ts +++ b/server/src/db/repositories/CollectionPlaces.repository.ts @@ -81,9 +81,8 @@ export class CollectionPlacesRepository extends TrekRepository * 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 source_trip_id: number | null; source_place_id: number | null; links: string | null; + sort_order: number; }): Promise { return await this.insert({ collection: row.collection_id, @@ -132,9 +132,35 @@ export class CollectionPlacesRepository extends TrekRepository 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 { + 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 { + 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 currency: string | null; collection_id: number; owner_id: number; + sort_order: number; }>, ): Promise { if (Object.keys(write).length === 0) return; @@ -350,20 +377,6 @@ export class CollectionPlacesRepository extends TrekRepository .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 { - 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) // --------------------------------------------------------------------- diff --git a/server/src/nest/collections/collections.controller.ts b/server/src/nest/collections/collections.controller.ts index 82f6e3a0e..10cf043e7 100644 --- a/server/src/nest/collections/collections.controller.ts +++ b/server/src/nest/collections/collections.controller.ts @@ -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, diff --git a/server/src/nest/collections/collections.dto.ts b/server/src/nest/collections/collections.dto.ts index c9d00b299..f5d0f222b 100644 --- a/server/src/nest/collections/collections.dto.ts +++ b/server/src/nest/collections/collections.dto.ts @@ -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) {} diff --git a/server/src/nest/collections/collections.helpers.ts b/server/src/nest/collections/collections.helpers.ts index 3aa4f8754..bed71f95a 100644 --- a/server/src/nest/collections/collections.helpers.ts +++ b/server/src/nest/collections/collections.helpers.ts @@ -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(rows: R[], value: (row: R) => V): Record { + const out: Record = {}; + 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))]; +} diff --git a/server/src/nest/collections/collections.mcp.ts b/server/src/nest/collections/collections.mcp.ts index 58ce7ec68..a68d963b9 100644 --- a/server/src/nest/collections/collections.mcp.ts +++ b/server/src/nest/collections/collections.mcp.ts @@ -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({ diff --git a/server/src/nest/collections/collections.service.ts b/server/src/nest/collections/collections.service.ts index 73303f78a..8e72413e4 100644 --- a/server/src/nest/collections/collections.service.ts +++ b/server/src/nest/collections/collections.service.ts @@ -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> { - const out: Record = {}; - 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> { - const out: Record = {}; - 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> { - const out: Record = {}; - 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 { @@ -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 { + 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 { + 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 { + 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(); // 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): Promise { + 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) // ------------------------------------------------------------------------- diff --git a/server/src/nest/place-import/place-import.module.ts b/server/src/nest/place-import/place-import.module.ts index a8407d278..40738d7c4 100644 --- a/server/src/nest/place-import/place-import.module.ts +++ b/server/src/nest/place-import/place-import.module.ts @@ -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, diff --git a/server/src/nest/place-import/place-import.service.ts b/server/src/nest/place-import/place-import.service.ts index 05e099461..237e69bd7 100644 --- a/server/src/nest/place-import/place-import.service.ts +++ b/server/src/nest/place-import/place-import.service.ts @@ -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 { + 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); diff --git a/server/src/nest/place-import/place-import.types.ts b/server/src/nest/place-import/place-import.types.ts index c7a1ba7f3..69fa7deff 100644 --- a/server/src/nest/place-import/place-import.types.ts +++ b/server/src/nest/place-import/place-import.types.ts @@ -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` diff --git a/server/src/nest/place-import/providers/collection-kml.provider.ts b/server/src/nest/place-import/providers/collection-kml.provider.ts new file mode 100644 index 000000000..b51247165 --- /dev/null +++ b/server/src/nest/place-import/providers/collection-kml.provider.ts @@ -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 = []; + 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 { + 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); + } +} diff --git a/server/src/nest/settings/settings.mcp.ts b/server/src/nest/settings/settings.mcp.ts index da09e7a11..b52ac944c 100644 --- a/server/src/nest/settings/settings.mcp.ts +++ b/server/src/nest/settings/settings.mcp.ts @@ -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, diff --git a/server/tests/e2e/collections.e2e.test.ts b/server/tests/e2e/collections.e2e.test.ts index 690c3e2a9..aa6cd8fbf 100644 --- a/server/tests/e2e/collections.e2e.test.ts +++ b/server/tests/e2e/collections.e2e.test.ts @@ -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 = ` + FoodPasteis-9.2,38.69 + Walk-9.1,38.7 -9.2,38.71 + `; + + 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('', 'route.gpx'); + expect(gpx.status).toBe(400); + expect(gpx.body).toEqual({ error: expect.any(String), code: 'not-map' }); + + const broken = await upload('', '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) => + 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'); + }); }); diff --git a/server/tests/helpers/place-import.ts b/server/tests/helpers/place-import.ts index 11f4ae305..5bbfe2b0c 100644 --- a/server/tests/helpers/place-import.ts +++ b/server/tests/helpers/place-import.ts @@ -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(), diff --git a/server/tests/integration/broadcast-parity/user.cases.ts b/server/tests/integration/broadcast-parity/user.cases.ts index 00cc197cd..1e8880241 100644 --- a/server/tests/integration/broadcast-parity/user.cases.ts +++ b/server/tests/integration/broadcast-parity/user.cases.ts @@ -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'], diff --git a/server/tests/unit/db/repositories/longitude-on-write.test.ts b/server/tests/unit/db/repositories/longitude-on-write.test.ts index 9a1ec4416..0c3c4ccbf 100644 --- a/server/tests/unit/db/repositories/longitude-on-write.test.ts +++ b/server/tests/unit/db/repositories/longitude-on-write.test.ts @@ -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); diff --git a/server/tests/unit/mcp/tools-collections.test.ts b/server/tests/unit/mcp/tools-collections.test.ts index 97a975df1..41710151e 100644 --- a/server/tests/unit/mcp/tools-collections.test.ts +++ b/server/tests/unit/mcp/tools-collections.test.ts @@ -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); diff --git a/server/tests/unit/mcp/tools-settings.test.ts b/server/tests/unit/mcp/tools-settings.test.ts index 7b9f6f804..54c6552d6 100644 --- a/server/tests/unit/mcp/tools-settings.test.ts +++ b/server/tests/unit/mcp/tools-settings.test.ts @@ -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, diff --git a/server/tests/unit/nest/collections.controller.test.ts b/server/tests/unit/nest/collections.controller.test.ts index 54cad11e3..dae181046 100644 --- a/server/tests/unit/nest/collections.controller.test.ts +++ b/server/tests/unit/nest/collections.controller.test.ts @@ -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(''), originalname: 'lisbon.kml' } as Express.Multer.File; + + /** The status and body an async handler rejects with. */ + async function rejected(run: Promise): 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'); + }); + }); }); diff --git a/server/tests/unit/nest/collections.copy-to-trip.test.ts b/server/tests/unit/nest/collections.copy-to-trip.test.ts index 16819dd54..05d3fc615 100644 --- a/server/tests/unit/nest/collections.copy-to-trip.test.ts +++ b/server/tests/unit/nest/collections.copy-to-trip.test.ts @@ -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([]); + }); +}); diff --git a/server/tests/unit/nest/collections.helpers.test.ts b/server/tests/unit/nest/collections.helpers.test.ts index f235a1fc1..4993caea2 100644 --- a/server/tests/unit/nest/collections.helpers.test.ts +++ b/server/tests/unit/nest/collections.helpers.test.ts @@ -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(); + }); +}); diff --git a/server/tests/unit/nest/collections.place-order.test.ts b/server/tests/unit/nest/collections.place-order.test.ts new file mode 100644 index 000000000..3d1f6360c --- /dev/null +++ b/server/tests/unit/nest/collections.place-order.test.ts @@ -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 { + 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]); + } + }); +}); diff --git a/server/tests/unit/nest/collections.service.test.ts b/server/tests/unit/nest/collections.service.test.ts index b33c72b5c..cf7ee81d8 100644 --- a/server/tests/unit/nest/collections.service.test.ts +++ b/server/tests/unit/nest/collections.service.test.ts @@ -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 () => { diff --git a/server/tests/unit/nest/place-import/collection-kml.provider.test.ts b/server/tests/unit/nest/place-import/collection-kml.provider.test.ts new file mode 100644 index 000000000..6c20f9bdd --- /dev/null +++ b/server/tests/unit/nest/place-import/collection-kml.provider.test.ts @@ -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 = `Lisbon + RossioThe square-9.14,38.71 + Views + Miradouro-9.13,38.72,0 + -9.15,38.70 + Tram 28-9.14,38.71 -9.13,38.72 + Park-9.1,38.7 -9.2,38.7 -9.2,38.8 -9.1,38.7 + + Nowhere + Off the map-9.1,95 +`; + +/** A KMZ archive holding these entries. */ +async function kmz(entries: Record): Promise { + 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): Promise { + 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(''), '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); + }); +}); diff --git a/shared/src/collection/collection-file.schema.spec.ts b/shared/src/collection/collection-file.schema.spec.ts index 6c47972ed..775dc1d0e 100644 --- a/shared/src/collection/collection-file.schema.spec.ts +++ b/shared/src/collection/collection-file.schema.spec.ts @@ -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); + }); +}); diff --git a/shared/src/collection/collection-file.schema.ts b/shared/src/collection/collection-file.schema.ts index 6dc13b509..3c38e8302 100644 --- a/shared/src/collection/collection-file.schema.ts +++ b/shared/src/collection/collection-file.schema.ts @@ -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; + export interface CollectionGpxExport { /** The list's name, for the file name. */ name: string; diff --git a/shared/src/collection/collection.schema.spec.ts b/shared/src/collection/collection.schema.spec.ts index 4c1f78d0c..6df258f66 100644 --- a/shared/src/collection/collection.schema.spec.ts +++ b/shared/src/collection/collection.schema.spec.ts @@ -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); + }); +}); diff --git a/shared/src/collection/collection.schema.ts b/shared/src/collection/collection.schema.ts index ac391b70c..dc3e918a4 100644 --- a/shared/src/collection/collection.schema.ts +++ b/shared/src/collection/collection.schema.ts @@ -271,11 +271,28 @@ export const collectionDeleteManyRequestSchema = z.object({ }); export type CollectionDeleteManyRequest = z.infer; -/** 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; @@ -287,6 +304,23 @@ export const collectionCopyToTripResponseSchema = z.object({ }); export type CollectionCopyToTripResponse = z.infer; +/** 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; + /** 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(), diff --git a/shared/src/i18n/ar/collection.ts b/shared/src/i18n/ar/collection.ts index c21f8839e..9066b2ff1 100644 --- a/shared/src/i18n/ar/collection.ts +++ b/shared/src/i18n/ar/collection.ts @@ -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': diff --git a/shared/src/i18n/ar/map.ts b/shared/src/i18n/ar/map.ts index a6d7837fa..f9b3b5251 100644 --- a/shared/src/i18n/ar/map.ts +++ b/shared/src/i18n/ar/map.ts @@ -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': 'دع الخريطة تتبع التحديد', diff --git a/shared/src/i18n/az/collection.ts b/shared/src/i18n/az/collection.ts index 4761a20be..a6681352a 100644 --- a/shared/src/i18n/az/collection.ts +++ b/shared/src/i18n/az/collection.ts @@ -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': diff --git a/shared/src/i18n/az/map.ts b/shared/src/i18n/az/map.ts index f55386bc0..bd4c34188 100644 --- a/shared/src/i18n/az/map.ts +++ b/shared/src/i18n/az/map.ts @@ -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ə', diff --git a/shared/src/i18n/br/collection.ts b/shared/src/i18n/br/collection.ts index 5d3b08d23..83e805877 100644 --- a/shared/src/i18n/br/collection.ts +++ b/shared/src/i18n/br/collection.ts @@ -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': diff --git a/shared/src/i18n/br/map.ts b/shared/src/i18n/br/map.ts index b72677609..362c0cc87 100644 --- a/shared/src/i18n/br/map.ts +++ b/shared/src/i18n/br/map.ts @@ -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', diff --git a/shared/src/i18n/ca/collection.ts b/shared/src/i18n/ca/collection.ts index 8c9addedb..71ac8922d 100644 --- a/shared/src/i18n/ca/collection.ts +++ b/shared/src/i18n/ca/collection.ts @@ -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': diff --git a/shared/src/i18n/ca/map.ts b/shared/src/i18n/ca/map.ts index bbe242446..7e667fbec 100644 --- a/shared/src/i18n/ca/map.ts +++ b/shared/src/i18n/ca/map.ts @@ -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ó', diff --git a/shared/src/i18n/cs/collection.ts b/shared/src/i18n/cs/collection.ts index 13562a9e2..f679a11b8 100644 --- a/shared/src/i18n/cs/collection.ts +++ b/shared/src/i18n/cs/collection.ts @@ -82,9 +82,18 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped.one': '{count} místo už na seznamu bylo a zůstalo beze změny', 'collections.importDoneSkipped.few': '{count} místa už na seznamu byla a zůstala beze změny', 'collections.importDoneClean': 'Teď jsou všechna v {name}', - 'collections.sort.default': 'Výchozí', + 'collections.sort.default': 'Vlastní pořadí', + 'collections.reorderBlocked': 'Smažte hledání a filtry, abyste mohli místa přetahovat do vlastního pořadí.', + 'collections.reorderHandle': 'Přesunout {name} nebo použít šipky na klávesnici', 'collections.sort.nameAsc': 'Název (A–Z)', 'collections.coordinates': 'Souřadnice', + 'collections.findPosition': 'Najít polohu', + 'collections.findPositionPlaceholder': 'Vyhledat toto místo na mapě', + 'collections.findPositionHint': + 'Toto místo zatím nemá souřadnice, a proto není na mapě. Vyhledejte ho níže a vyberte správný výsledek.', + 'collections.findPositionPicked': 'Poloha vybrána. Po uložení se místo objeví na mapě.', + 'collections.addNoPositionHint': + 'Bez výběru výsledku z hledání výše nebude mít toto místo souřadnice a na mapě se nezobrazí.', 'collections.showList': 'Zobrazit seznam', 'collections.expandMap': 'Zvětšit mapu', 'collections.hero.mine': 'Moje sbírka', @@ -138,6 +147,12 @@ const collection: TranslationStrings = { 'collections.copyN.one': 'Kopírovat do výletu', 'collections.copyN.few': 'Kopírovat {count} do výletu', 'collections.copyToTripSearch': 'Hledat výlety', + 'collections.copyCarry.title': 'Vzít s sebou', + 'collections.copyCarry.notes': 'Poznámky', + 'collections.copyCarry.notesHint': + 'Když je vypnuto, poznámky zůstanou v seznamu. Když je zapnuto, může je číst každý ve výletu.', + 'collections.copyCarry.tags': 'Štítky', + 'collections.copyCarry.tagsHint': 'Vybraný štítek se stane štítkem výletu a uvidí ho všichni spolucestující.', 'collections.searchLists': 'Hledat seznamy', 'collections.copyToTripConfirm': 'Kopírovat', 'collections.noTrips': 'Zatím žádné výlety', @@ -240,6 +255,17 @@ const collection: TranslationStrings = { 'collections.file.gpxTrack.few': 'Soubor obsahuje také {count} body stopy. Stopy se neimportují, jen trasové body.', 'collections.file.gpxEmpty': 'Tento soubor GPX neobsahuje žádné trasové body, takže není co importovat.', 'collections.file.errorNotGpx': 'Toto není soubor GPX.', + 'collections.file.errorNotMap': 'Tento soubor není mapa KML ani KMZ, kterou by TREK uměl přečíst.', + 'collections.file.mapPicked': 'Vybráno {picked} z {total}', + 'collections.file.mapAll': 'Vybrat vše', + 'collections.file.mapNone': 'Nevybrat nic', + 'collections.file.mapSkipped': '{count} položek bude vynecháno', + 'collections.file.mapSkipped.one': '{count} položka bude vynechána', + 'collections.file.mapSkipped.few': '{count} položky budou vynechány', + 'collections.file.mapUnnamed': 'Bez názvu', + 'collections.file.mapSkipLine': 'čára, ne místo', + 'collections.file.mapSkipNoPoint': 'plocha nebo bez polohy', + 'collections.file.mapSkipInvalid': 'souřadnice mimo rozsah', 'collections.file.errorTooManyPlaces': 'Tento soubor obsahuje více než {count} míst. Rozdělte ho a importujte části postupně.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/cs/map.ts b/shared/src/i18n/cs/map.ts index 42005c22b..5f63bffe6 100644 --- a/shared/src/i18n/cs/map.ts +++ b/shared/src/i18n/cs/map.ts @@ -30,6 +30,8 @@ const map: TranslationStrings = { 'Přístup k poloze je zablokován. Zkontrolujte nastavení zařízení; nainstalovaná aplikace má vlastní oprávnění k poloze, nezávislé na prohlížeči.', 'map.location.unavailable': 'Vaši polohu se nepodařilo zjistit.', 'map.location.timeout': 'Zjišťování polohy trvalo příliš dlouho. Zkuste to znovu s volným výhledem na oblohu.', + 'map.placeNames.show': 'Zobrazit názvy míst', + 'map.placeNames.hide': 'Skrýt názvy míst', 'map.overview.show': 'Zobrazit celou cestu', 'map.lock.lock': 'Uzamknout zobrazení mapy', 'map.lock.unlock': 'Nechat mapu sledovat výběr', diff --git a/shared/src/i18n/de/collection.ts b/shared/src/i18n/de/collection.ts index 659692abb..92aa7d9b8 100644 --- a/shared/src/i18n/de/collection.ts +++ b/shared/src/i18n/de/collection.ts @@ -70,9 +70,16 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped': '{count} Orte standen schon auf der Liste und blieben unverändert', 'collections.importDoneSkipped.one': '{count} Ort stand schon auf der Liste und blieb unverändert', 'collections.importDoneClean': 'Sie stehen jetzt alle in {name}', - 'collections.sort.default': 'Standard', + 'collections.sort.default': 'Eigene Reihenfolge', + 'collections.reorderBlocked': 'Ohne Suche und Filter kannst du die Orte in deine eigene Reihenfolge ziehen.', + 'collections.reorderHandle': '{name} verschieben, auch mit den Pfeiltasten', 'collections.sort.nameAsc': 'Name (A bis Z)', 'collections.coordinates': 'Koordinaten', + 'collections.findPosition': 'Position suchen', + 'collections.findPositionPlaceholder': 'Diesen Ort auf der Karte suchen', + 'collections.findPositionHint': 'Dieser Ort hat noch keine Koordinaten und erscheint deshalb nicht auf der Karte. Such ihn unten und wähl den passenden Treffer.', + 'collections.findPositionPicked': 'Position übernommen. Nach dem Speichern erscheint der Ort auf der Karte.', + 'collections.addNoPositionHint': 'Ohne einen Treffer aus der Suche oben bekommt dieser Ort keine Koordinaten und erscheint nicht auf der Karte.', 'collections.showList': 'Liste zeigen', 'collections.expandMap': 'Karte vergrößern', 'collections.hero.mine': 'Meine Sammlung', @@ -126,6 +133,11 @@ const collection: TranslationStrings = { 'collections.copyN': '{count} in Reise kopieren', 'collections.copyN.one': 'In Reise kopieren', 'collections.copyToTripSearch': 'Reisen suchen', + 'collections.copyCarry.title': 'Mitnehmen', + 'collections.copyCarry.notes': 'Notizen', + 'collections.copyCarry.notesHint': 'Ausgeschaltet bleiben die Notizen in der Liste, eingeschaltet können alle im Trip sie lesen.', + 'collections.copyCarry.tags': 'Tags', + 'collections.copyCarry.tagsHint': 'Ein gewählter Tag wird ein Tag des Trips und ist für alle Mitreisenden sichtbar.', 'collections.searchLists': 'Listen suchen', 'collections.copyToTripConfirm': 'Kopieren', 'collections.noTrips': 'Noch keine Reisen', @@ -217,6 +229,16 @@ const collection: TranslationStrings = { 'Die Datei enthält außerdem {count} Trackpunkt. Tracks werden nicht importiert, nur Wegpunkte.', 'collections.file.gpxEmpty': 'Diese GPX-Datei enthält keine Wegpunkte, es gibt also nichts zu importieren.', 'collections.file.errorNotGpx': 'Das ist keine GPX-Datei.', + 'collections.file.errorNotMap': 'Diese Datei ist keine KML- oder KMZ-Karte, die TREK lesen kann.', + 'collections.file.mapPicked': '{picked} von {total} ausgewählt', + 'collections.file.mapAll': 'Alle wählen', + 'collections.file.mapNone': 'Keine wählen', + 'collections.file.mapSkipped': '{count} Einträge ausgelassen', + 'collections.file.mapSkipped.one': '{count} Eintrag ausgelassen', + 'collections.file.mapUnnamed': 'Ohne Namen', + 'collections.file.mapSkipLine': 'eine Linie, kein Ort', + 'collections.file.mapSkipNoPoint': 'eine Fläche oder ohne Position', + 'collections.file.mapSkipInvalid': 'Koordinaten außerhalb des gültigen Bereichs', 'collections.file.errorTooManyPlaces': 'Diese Datei enthält mehr als {count} Orte. Teile sie auf und importiere die Teile nacheinander.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/de/map.ts b/shared/src/i18n/de/map.ts index 6b2756297..813754d24 100644 --- a/shared/src/i18n/de/map.ts +++ b/shared/src/i18n/de/map.ts @@ -33,6 +33,8 @@ const map: TranslationStrings = { 'map.location.unavailable': 'Dein Standort konnte nicht ermittelt werden.', 'map.location.timeout': 'Die Standortbestimmung hat zu lange gedauert. Versuche es mit freier Sicht zum Himmel erneut.', + 'map.placeNames.show': 'Ortsnamen anzeigen', + 'map.placeNames.hide': 'Ortsnamen ausblenden', 'map.overview.show': 'Ganze Reise anzeigen', 'map.lock.lock': 'Kartenansicht fixieren', 'map.lock.unlock': 'Karte der Auswahl folgen lassen', diff --git a/shared/src/i18n/en/collection.ts b/shared/src/i18n/en/collection.ts index c98de1c1d..a3807966a 100644 --- a/shared/src/i18n/en/collection.ts +++ b/shared/src/i18n/en/collection.ts @@ -70,9 +70,16 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped': '{count} were already on the list and stayed as they were', 'collections.importDoneSkipped.one': '{count} was already on the list and stayed as it was', 'collections.importDoneClean': 'They are all in {name} now', - 'collections.sort.default': 'Default', + 'collections.sort.default': 'Own order', + 'collections.reorderBlocked': 'Clear the search and filters to drag places into your own order.', + 'collections.reorderHandle': 'Move {name}, or use the arrow keys', 'collections.sort.nameAsc': 'Name (A–Z)', 'collections.coordinates': 'Coordinates', + 'collections.findPosition': 'Find the position', + 'collections.findPositionPlaceholder': 'Search for this place on the map', + 'collections.findPositionHint': 'This place has no coordinates yet, so it is not on the map. Search for it below and pick the right hit.', + 'collections.findPositionPicked': 'Position picked. Save to put the place on the map.', + 'collections.addNoPositionHint': 'Without a pick from the search above, this place gets no coordinates and will not show on the map.', 'collections.showList': 'Show list', 'collections.expandMap': 'Expand map', 'collections.hero.mine': 'My collection', @@ -125,6 +132,11 @@ const collection: TranslationStrings = { 'collections.copyN': 'Copy {count} to trip', 'collections.copyN.one': 'Copy to trip', 'collections.copyToTripSearch': 'Search trips', + 'collections.copyCarry.title': 'Take along', + 'collections.copyCarry.notes': 'Notes', + 'collections.copyCarry.notesHint': 'Off, the notes stay in the list. On, everyone in the trip can read them.', + 'collections.copyCarry.tags': 'Tags', + 'collections.copyCarry.tagsHint': 'A picked tag becomes a tag of the trip, shared with its travellers.', 'collections.searchLists': 'Search lists', 'collections.copyToTripConfirm': 'Copy', 'collections.noTrips': 'No trips yet', @@ -214,6 +226,16 @@ const collection: TranslationStrings = { 'collections.file.gpxTrack.one': 'This file also has {count} track point. Tracks are not imported, only waypoints.', 'collections.file.gpxEmpty': 'This GPX file has no waypoints, so there is nothing to import.', 'collections.file.errorNotGpx': 'That is not a GPX file.', + 'collections.file.errorNotMap': 'This file is not a KML or KMZ map TREK can read.', + 'collections.file.mapPicked': '{picked} of {total} picked', + 'collections.file.mapAll': 'Pick all', + 'collections.file.mapNone': 'Pick none', + 'collections.file.mapSkipped': '{count} entries left out', + 'collections.file.mapSkipped.one': '{count} entry left out', + 'collections.file.mapUnnamed': 'Unnamed', + 'collections.file.mapSkipLine': 'a line, not a place', + 'collections.file.mapSkipNoPoint': 'an area or no position', + 'collections.file.mapSkipInvalid': 'coordinates out of range', 'collections.file.errorTooManyPlaces': 'That file has more than {count} places. Split it and import the parts one at a time.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/en/map.ts b/shared/src/i18n/en/map.ts index 4c64a292b..fdfe8bddf 100644 --- a/shared/src/i18n/en/map.ts +++ b/shared/src/i18n/en/map.ts @@ -31,6 +31,8 @@ const map: TranslationStrings = { 'Location access is blocked. Check your device settings; an installed app has its own location permission, separate from the browser.', 'map.location.unavailable': 'Your location could not be determined.', 'map.location.timeout': 'Locating you took too long. Try again with a clearer view of the sky.', + 'map.placeNames.show': 'Show place names', + 'map.placeNames.hide': 'Hide place names', 'map.overview.show': 'Show whole trip', 'map.lock.lock': 'Lock the map view', 'map.lock.unlock': 'Let the map follow the selection', diff --git a/shared/src/i18n/es/collection.ts b/shared/src/i18n/es/collection.ts index 71eba36c4..d1b1237d6 100644 --- a/shared/src/i18n/es/collection.ts +++ b/shared/src/i18n/es/collection.ts @@ -70,9 +70,18 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped': '{count} ya estaban en la lista y se quedaron igual', 'collections.importDoneSkipped.one': '{count} ya estaba en la lista y se quedó igual', 'collections.importDoneClean': 'Ahora están todos en {name}', - 'collections.sort.default': 'Predeterminado', + 'collections.sort.default': 'Orden propio', + 'collections.reorderBlocked': 'Borra la búsqueda y los filtros para arrastrar los lugares a tu propio orden.', + 'collections.reorderHandle': 'Mover {name} o usar las teclas de flecha', 'collections.sort.nameAsc': 'Nombre (A–Z)', 'collections.coordinates': 'Coordenadas', + 'collections.findPosition': 'Encontrar la posición', + 'collections.findPositionPlaceholder': 'Buscar este lugar en el mapa', + 'collections.findPositionHint': + 'Este lugar aún no tiene coordenadas, así que no aparece en el mapa. Búscalo abajo y elige el resultado correcto.', + 'collections.findPositionPicked': 'Posición elegida. Guarda para poner el lugar en el mapa.', + 'collections.addNoPositionHint': + 'Sin elegir un resultado de la búsqueda de arriba, este lugar no tendrá coordenadas y no aparecerá en el mapa.', 'collections.showList': 'Mostrar lista', 'collections.expandMap': 'Ampliar mapa', 'collections.hero.mine': 'Mi colección', @@ -125,6 +134,13 @@ const collection: TranslationStrings = { 'collections.copyN': 'Copiar {count} al viaje', 'collections.copyN.one': 'Copiar al viaje', 'collections.copyToTripSearch': 'Buscar viajes', + 'collections.copyCarry.title': 'Llevar también', + 'collections.copyCarry.notes': 'Notas', + 'collections.copyCarry.notesHint': + 'Desactivado, las notas se quedan en la lista. Activado, todos los del viaje pueden leerlas.', + 'collections.copyCarry.tags': 'Etiquetas', + 'collections.copyCarry.tagsHint': + 'Una etiqueta elegida pasa a ser una etiqueta del viaje y se comparte con sus viajeros.', 'collections.searchLists': 'Buscar listas', 'collections.copyToTripConfirm': 'Copiar', 'collections.noTrips': 'Aún no hay viajes', @@ -218,6 +234,16 @@ const collection: TranslationStrings = { 'Este archivo también tiene {count} punto de traza. Las trazas no se importan, solo los puntos de ruta.', 'collections.file.gpxEmpty': 'Este archivo GPX no tiene puntos de ruta, así que no hay nada que importar.', 'collections.file.errorNotGpx': 'Ese no es un archivo GPX.', + 'collections.file.errorNotMap': 'Este archivo no es un mapa KML o KMZ que TREK pueda leer.', + 'collections.file.mapPicked': '{picked} de {total} elegidos', + 'collections.file.mapAll': 'Elegir todos', + 'collections.file.mapNone': 'No elegir ninguno', + 'collections.file.mapSkipped': 'Se dejan fuera {count} entradas', + 'collections.file.mapSkipped.one': 'Se deja fuera {count} entrada', + 'collections.file.mapUnnamed': 'Sin nombre', + 'collections.file.mapSkipLine': 'una línea, no un lugar', + 'collections.file.mapSkipNoPoint': 'un área o sin posición', + 'collections.file.mapSkipInvalid': 'coordenadas fuera de rango', 'collections.file.errorTooManyPlaces': 'Ese archivo tiene más de {count} lugares. Divídelo e importa las partes de una en una.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/es/map.ts b/shared/src/i18n/es/map.ts index 5e8c73a5f..cf44acd22 100644 --- a/shared/src/i18n/es/map.ts +++ b/shared/src/i18n/es/map.ts @@ -30,6 +30,8 @@ const map: TranslationStrings = { 'El acceso a la ubicación está bloqueado. Revisa los ajustes del dispositivo; una app instalada tiene su propio permiso de ubicación, independiente del navegador.', 'map.location.unavailable': 'No se pudo determinar tu ubicación.', 'map.location.timeout': 'La localización tardó demasiado. Inténtalo de nuevo con una vista más despejada del cielo.', + 'map.placeNames.show': 'Mostrar nombres de lugares', + 'map.placeNames.hide': 'Ocultar nombres de lugares', 'map.overview.show': 'Mostrar todo el viaje', 'map.lock.lock': 'Bloquear la vista del mapa', 'map.lock.unlock': 'Dejar que el mapa siga la selección', diff --git a/shared/src/i18n/et/collection.ts b/shared/src/i18n/et/collection.ts index 623dce76f..dcfaa445b 100644 --- a/shared/src/i18n/et/collection.ts +++ b/shared/src/i18n/et/collection.ts @@ -70,9 +70,18 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped': '{count} oli juba nimekirjas ja jäi muutmata', 'collections.importDoneSkipped.one': '{count} oli juba nimekirjas ja jäi muutmata', 'collections.importDoneClean': 'Need on nüüd kõik nimekirjas {name}', - 'collections.sort.default': 'Vaikimisi', + 'collections.sort.default': 'Oma järjekord', + 'collections.reorderBlocked': 'Tühjenda otsing ja filtrid, et saaksid kohti oma järjekorda lohistada.', + 'collections.reorderHandle': 'Teisalda {name} või kasuta nooleklahve', 'collections.sort.nameAsc': 'Nimi (A–Z)', 'collections.coordinates': 'Koordinaadid', + 'collections.findPosition': 'Leia asukoht', + 'collections.findPositionPlaceholder': 'Otsi seda kohta kaardilt', + 'collections.findPositionHint': + 'Sellel kohal pole veel koordinaate, seega pole see kaardil. Otsi seda allpool ja vali õige tulemus.', + 'collections.findPositionPicked': 'Asukoht valitud. Salvesta, et koht kaardile panna.', + 'collections.addNoPositionHint': + 'Ilma ülaltoodud otsingust tulemust valimata ei saa see koht koordinaate ega ilmu kaardile.', 'collections.showList': 'Näita nimekirja', 'collections.expandMap': 'Laienda kaarti', 'collections.hero.mine': 'Minu kogumik', @@ -125,6 +134,12 @@ const collection: TranslationStrings = { 'collections.copyN': 'Kopeeri {count} reisile', 'collections.copyN.one': 'Kopeeri reisile', 'collections.copyToTripSearch': 'Otsi reise', + 'collections.copyCarry.title': 'Võta kaasa', + 'collections.copyCarry.notes': 'Märkmed', + 'collections.copyCarry.notesHint': + 'Väljalülitatuna jäävad märkmed nimekirja. Sisselülitatuna saavad kõik reisil olijad neid lugeda.', + 'collections.copyCarry.tags': 'Sildid', + 'collections.copyCarry.tagsHint': 'Valitud silt muutub reisi sildiks ja on nähtav kõigile kaasreisijatele.', 'collections.searchLists': 'Otsi nimekirju', 'collections.copyToTripConfirm': 'Kopeeri', 'collections.noTrips': 'Reise veel pole', @@ -214,6 +229,16 @@ const collection: TranslationStrings = { 'collections.file.gpxTrack.one': 'Failis on ka {count} rajapunkt. Radu ei impordita, ainult teekonnapunkte.', 'collections.file.gpxEmpty': 'Selles GPX-failis pole teekonnapunkte, seega pole midagi importida.', 'collections.file.errorNotGpx': 'See ei ole GPX-fail.', + 'collections.file.errorNotMap': 'See fail pole KML- ega KMZ-kaart, mida TREK suudaks lugeda.', + 'collections.file.mapPicked': '{picked} / {total} valitud', + 'collections.file.mapAll': 'Vali kõik', + 'collections.file.mapNone': 'Ära vali ühtegi', + 'collections.file.mapSkipped': '{count} kirjet jäetakse välja', + 'collections.file.mapSkipped.one': '{count} kirje jäetakse välja', + 'collections.file.mapUnnamed': 'Nimeta', + 'collections.file.mapSkipLine': 'joon, mitte koht', + 'collections.file.mapSkipNoPoint': 'ala või asukohata', + 'collections.file.mapSkipInvalid': 'koordinaadid vahemikust väljas', 'collections.file.errorTooManyPlaces': 'Failis on üle {count} koha. Jaga fail osadeks ja impordi osad ükshaaval.', 'collections.file.errorTooManyPlaces.one': 'Failis on üle {count} koha. Jaga fail osadeks ja impordi osad ükshaaval.', diff --git a/shared/src/i18n/et/map.ts b/shared/src/i18n/et/map.ts index 52897528a..c9bcc0b53 100644 --- a/shared/src/i18n/et/map.ts +++ b/shared/src/i18n/et/map.ts @@ -30,6 +30,8 @@ const map: TranslationStrings = { 'Juurdepääs asukohale on blokeeritud. Kontrolli seadme seadeid; paigaldatud rakendusel on brauserist eraldi asukohaluba.', 'map.location.unavailable': 'Sinu asukohta ei õnnestunud määrata.', 'map.location.timeout': 'Asukoha määramine võttis liiga kaua aega. Proovi uuesti lagedamas kohas.', + 'map.placeNames.show': 'Näita kohanimesid', + 'map.placeNames.hide': 'Peida kohanimed', 'map.overview.show': 'Näita kogu reisi', 'map.lock.lock': 'Lukusta kaardivaade', 'map.lock.unlock': 'Lase kaardil valikut järgida', diff --git a/shared/src/i18n/fr/collection.ts b/shared/src/i18n/fr/collection.ts index 357e7f6fb..333d959f6 100644 --- a/shared/src/i18n/fr/collection.ts +++ b/shared/src/i18n/fr/collection.ts @@ -70,9 +70,19 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped': '{count} y étaient déjà et n’ont pas bougé', 'collections.importDoneSkipped.one': '{count} y était déjà et n’a pas bougé', 'collections.importDoneClean': 'Ils sont tous dans {name} maintenant', - 'collections.sort.default': 'Par défaut', + 'collections.sort.default': 'Ordre personnel', + 'collections.reorderBlocked': + 'Effacez la recherche et les filtres pour faire glisser les lieux dans votre propre ordre.', + 'collections.reorderHandle': 'Déplacer {name}, ou utiliser les touches fléchées', 'collections.sort.nameAsc': 'Nom (A–Z)', 'collections.coordinates': 'Coordonnées', + 'collections.findPosition': 'Trouver la position', + 'collections.findPositionPlaceholder': 'Rechercher ce lieu sur la carte', + 'collections.findPositionHint': + 'Ce lieu n’a pas encore de coordonnées, il n’apparaît donc pas sur la carte. Recherchez-le ci-dessous et choisissez le bon résultat.', + 'collections.findPositionPicked': 'Position choisie. Enregistrez pour placer le lieu sur la carte.', + 'collections.addNoPositionHint': + 'Sans résultat choisi dans la recherche ci-dessus, ce lieu n’aura pas de coordonnées et n’apparaîtra pas sur la carte.', 'collections.showList': 'Afficher la liste', 'collections.expandMap': 'Agrandir la carte', 'collections.hero.mine': 'Ma collection', @@ -125,6 +135,13 @@ const collection: TranslationStrings = { 'collections.copyN': 'Copier {count} vers un voyage', 'collections.copyN.one': 'Copier {count} vers un voyage', 'collections.copyToTripSearch': 'Rechercher des voyages', + 'collections.copyCarry.title': 'À emporter', + 'collections.copyCarry.notes': 'Notes', // same-as-en + 'collections.copyCarry.notesHint': + 'Désactivé, les notes restent dans la liste. Activé, tous les participants du voyage peuvent les lire.', + 'collections.copyCarry.tags': 'Étiquettes', + 'collections.copyCarry.tagsHint': + 'Une étiquette choisie devient une étiquette du voyage, partagée avec ses voyageurs.', 'collections.searchLists': 'Rechercher des listes', 'collections.copyToTripConfirm': 'Copier', 'collections.noTrips': 'Aucun voyage pour le moment', @@ -219,6 +236,16 @@ const collection: TranslationStrings = { 'Ce fichier contient aussi {count} point de trace. Les traces ne sont pas importées, seulement les points de passage.', 'collections.file.gpxEmpty': 'Ce fichier GPX ne contient aucun point de passage, il n’y a donc rien à importer.', 'collections.file.errorNotGpx': 'Ce n’est pas un fichier GPX.', + 'collections.file.errorNotMap': 'Ce fichier n’est pas une carte KML ou KMZ que TREK peut lire.', + 'collections.file.mapPicked': '{picked} sur {total} choisis', + 'collections.file.mapAll': 'Tout choisir', + 'collections.file.mapNone': 'Ne rien choisir', + 'collections.file.mapSkipped': '{count} entrées sont écartées', + 'collections.file.mapSkipped.one': '{count} entrée est écartée', + 'collections.file.mapUnnamed': 'Sans nom', + 'collections.file.mapSkipLine': 'une ligne, pas un lieu', + 'collections.file.mapSkipNoPoint': 'une zone ou sans position', + 'collections.file.mapSkipInvalid': 'coordonnées hors limites', 'collections.file.errorTooManyPlaces': 'Ce fichier contient plus de {count} lieux. Découpez-le et importez les parties une par une.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/fr/map.ts b/shared/src/i18n/fr/map.ts index 376ed680d..195acb596 100644 --- a/shared/src/i18n/fr/map.ts +++ b/shared/src/i18n/fr/map.ts @@ -32,6 +32,8 @@ const map: TranslationStrings = { 'L’accès à la position est bloqué. Vérifiez les réglages de l’appareil. Une app installée possède sa propre autorisation de localisation, distincte du navigateur.', 'map.location.unavailable': 'Votre position n’a pas pu être déterminée.', 'map.location.timeout': 'La localisation a pris trop de temps. Réessayez avec une vue plus dégagée du ciel.', + 'map.placeNames.show': 'Afficher les noms de lieux', + 'map.placeNames.hide': 'Masquer les noms de lieux', 'map.overview.show': 'Afficher tout le voyage', 'map.lock.lock': 'Verrouiller la vue de la carte', 'map.lock.unlock': 'Laisser la carte suivre la sélection', diff --git a/shared/src/i18n/gr/collection.ts b/shared/src/i18n/gr/collection.ts index d64d0e239..ab4fd5e74 100644 --- a/shared/src/i18n/gr/collection.ts +++ b/shared/src/i18n/gr/collection.ts @@ -70,9 +70,19 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped': '{count} ήταν ήδη στη λίστα και έμειναν ως είχαν', 'collections.importDoneSkipped.one': '{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': 'Η συλλογή μου', @@ -125,6 +135,13 @@ const collection: TranslationStrings = { 'collections.copyN': 'Αντιγραφή {count} σε ταξίδι', 'collections.copyN.one': 'Αντιγραφή σε ταξίδι', 'collections.copyToTripSearch': 'Αναζήτηση ταξιδιών', + 'collections.copyCarry.title': 'Να συμπεριληφθούν', + 'collections.copyCarry.notes': 'Σημειώσεις', + 'collections.copyCarry.notesHint': + 'Απενεργοποιημένο, οι σημειώσεις μένουν στη λίστα. Ενεργοποιημένο, όλοι στο ταξίδι μπορούν να τις διαβάσουν.', + 'collections.copyCarry.tags': 'Ετικέτες', + 'collections.copyCarry.tagsHint': + 'Μια επιλεγμένη ετικέτα γίνεται ετικέτα του ταξιδιού και είναι ορατή στους συνταξιδιώτες.', 'collections.searchLists': 'Αναζήτηση λιστών', 'collections.copyToTripConfirm': 'Αντιγραφή', 'collections.noTrips': 'Δεν υπάρχουν ταξίδια ακόμα', @@ -218,6 +235,16 @@ 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.one': '{count} εγγραφή μένει εκτός', + 'collections.file.mapUnnamed': 'Χωρίς όνομα', + 'collections.file.mapSkipLine': 'γραμμή, όχι τοποθεσία', + 'collections.file.mapSkipNoPoint': 'περιοχή ή χωρίς θέση', + 'collections.file.mapSkipInvalid': 'συντεταγμένες εκτός ορίων', 'collections.file.errorTooManyPlaces': 'Αυτό το αρχείο έχει περισσότερα από {count} μέρη. Χωρίστε το και εισαγάγετε τα κομμάτια ένα ένα.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/gr/map.ts b/shared/src/i18n/gr/map.ts index 20fe21cb5..17b6fd33e 100644 --- a/shared/src/i18n/gr/map.ts +++ b/shared/src/i18n/gr/map.ts @@ -31,6 +31,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': 'Ο χάρτης να ακολουθεί την επιλογή', diff --git a/shared/src/i18n/he/collection.ts b/shared/src/i18n/he/collection.ts index 86367c446..c0a912100 100644 --- a/shared/src/i18n/he/collection.ts +++ b/shared/src/i18n/he/collection.ts @@ -82,9 +82,17 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped.one': 'אחד כבר היה ברשימה ונשאר כמו שהיה', 'collections.importDoneSkipped.two': 'שניים כבר היו ברשימה ונשארו כמו שהיו', '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': 'האוסף שלי', @@ -132,6 +140,12 @@ const collection: TranslationStrings = { 'collections.copyN.one': 'העתקה לטיול', 'collections.copyN.two': 'העתקת שניים לטיול', 'collections.copyToTripSearch': 'חיפוש טיולים', + 'collections.copyCarry.title': 'מה לקחת איתכם', + 'collections.copyCarry.notes': 'הערות', + 'collections.copyCarry.notesHint': + 'כשהאפשרות כבויה, ההערות נשארות ברשימה. כשהיא דולקת, כל משתתפי הטיול יכולים לקרוא אותן.', + 'collections.copyCarry.tags': 'תגיות', + 'collections.copyCarry.tagsHint': 'תגית שנבחרה הופכת לתגית של הטיול ונראית לכל המטיילים.', 'collections.searchLists': 'חיפוש רשימות', 'collections.copyToTripConfirm': 'העתקה', 'collections.noTrips': 'עדיין אין טיולים', @@ -227,6 +241,17 @@ const collection: TranslationStrings = { 'collections.file.gpxTrack.two': 'בקובץ הזה יש גם שתי נקודות מסלול. מסלולים לא מיובאים, רק נקודות ציון.', '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.one': 'פריט אחד הושמט', + 'collections.file.mapSkipped.two': 'שני פריטים הושמטו', + 'collections.file.mapUnnamed': 'ללא שם', + 'collections.file.mapSkipLine': 'קו, לא מקום', + 'collections.file.mapSkipNoPoint': 'שטח או ללא מיקום', + 'collections.file.mapSkipInvalid': 'קואורדינטות מחוץ לטווח', 'collections.file.errorTooManyPlaces': 'בקובץ יש יותר מ-{count} מקומות. פצלו אותו וייבאו את החלקים אחד אחד.', 'collections.file.errorTooManyPlaces.one': 'בקובץ הזה יש יותר ממקום אחד. פצלו אותו וייבאו את החלקים אחד אחד.', 'collections.file.errorTooManyPlaces.two': 'בקובץ הזה יש יותר משני מקומות. פצלו אותו וייבאו את החלקים אחד אחד.', diff --git a/shared/src/i18n/he/map.ts b/shared/src/i18n/he/map.ts index 2ab83377a..931f62cdb 100644 --- a/shared/src/i18n/he/map.ts +++ b/shared/src/i18n/he/map.ts @@ -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': 'לתת למפה לעקוב אחרי הבחירה', diff --git a/shared/src/i18n/hu/collection.ts b/shared/src/i18n/hu/collection.ts index 5957a5040..03d860c90 100644 --- a/shared/src/i18n/hu/collection.ts +++ b/shared/src/i18n/hu/collection.ts @@ -70,9 +70,18 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped': '{count} már a listán volt, és változatlan maradt', 'collections.importDoneSkipped.one': '{count} már a listán volt, és változatlan maradt', 'collections.importDoneClean': 'Most már mind itt van: {name}', - 'collections.sort.default': 'Alapértelmezett', + 'collections.sort.default': 'Saját sorrend', + 'collections.reorderBlocked': 'Töröld a keresést és a szűrőket, hogy a helyeket a saját sorrendedbe húzhasd.', + 'collections.reorderHandle': '{name} áthelyezése, vagy használd a nyílbillentyűket', 'collections.sort.nameAsc': 'Név (A–Z)', 'collections.coordinates': 'Koordináták', + 'collections.findPosition': 'Pozíció keresése', + 'collections.findPositionPlaceholder': 'Hely keresése a térképen', + 'collections.findPositionHint': + 'Ennek a helynek még nincsenek koordinátái, ezért nem jelenik meg a térképen. Keresd meg lent, és válaszd ki a megfelelő találatot.', + 'collections.findPositionPicked': 'Pozíció kiválasztva. Mentés után a hely megjelenik a térképen.', + 'collections.addNoPositionHint': + 'A fenti keresésből kiválasztott találat nélkül ennek a helynek nem lesznek koordinátái, és nem jelenik meg a térképen.', 'collections.showList': 'Lista megjelenítése', 'collections.expandMap': 'Térkép nagyítása', 'collections.hero.mine': 'Saját gyűjtemény', @@ -126,6 +135,12 @@ const collection: TranslationStrings = { 'collections.copyN': '{count} másolása utazásba', 'collections.copyN.one': 'Másolás utazásba', 'collections.copyToTripSearch': 'Utazások keresése', + 'collections.copyCarry.title': 'Mit vigyek magammal', + 'collections.copyCarry.notes': 'Jegyzetek', + 'collections.copyCarry.notesHint': + 'Kikapcsolva a jegyzetek a listában maradnak, bekapcsolva az utazás minden résztvevője olvashatja őket.', + 'collections.copyCarry.tags': 'Címkék', + 'collections.copyCarry.tagsHint': 'A kiválasztott címke az utazás címkéje lesz, és az útitársak is látják.', 'collections.searchLists': 'Listák keresése', 'collections.copyToTripConfirm': 'Másolás', 'collections.noTrips': 'Még nincsenek utazások', @@ -217,6 +232,16 @@ const collection: TranslationStrings = { 'A fájlban {count} nyomvonalpont is van. A nyomvonalakat nem importáljuk, csak az útpontokat.', 'collections.file.gpxEmpty': 'Ebben a GPX-fájlban nincsenek útpontok, így nincs mit importálni.', 'collections.file.errorNotGpx': 'Ez nem GPX-fájl.', + 'collections.file.errorNotMap': 'Ez a fájl nem olyan KML- vagy KMZ-térkép, amelyet a TREK be tud olvasni.', + 'collections.file.mapPicked': '{picked} / {total} kiválasztva', + 'collections.file.mapAll': 'Összes kiválasztása', + 'collections.file.mapNone': 'Kijelölés törlése', + 'collections.file.mapSkipped': '{count} bejegyzés kimarad', + 'collections.file.mapSkipped.one': '{count} bejegyzés kimarad', + 'collections.file.mapUnnamed': 'Névtelen', + 'collections.file.mapSkipLine': 'vonal, nem hely', + 'collections.file.mapSkipNoPoint': 'terület vagy pozíció nélkül', + 'collections.file.mapSkipInvalid': 'a koordináták a tartományon kívül esnek', 'collections.file.errorTooManyPlaces': 'Ebben a fájlban több mint {count} hely van. Oszd fel, és importáld a részeket egyenként.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/hu/map.ts b/shared/src/i18n/hu/map.ts index fb95b9757..1f8c9574e 100644 --- a/shared/src/i18n/hu/map.ts +++ b/shared/src/i18n/hu/map.ts @@ -30,6 +30,8 @@ const map: TranslationStrings = { 'A helyhozzáférés le van tiltva. Ellenőrizd a készülék beállításait; a telepített alkalmazásnak saját helyengedélye van, a böngészőtől függetlenül.', 'map.location.unavailable': 'A tartózkodási helyed nem határozható meg.', 'map.location.timeout': 'A helymeghatározás túl sokáig tartott. Próbáld újra szabad ég alatt.', + 'map.placeNames.show': 'Helynevek megjelenítése', + 'map.placeNames.hide': 'Helynevek elrejtése', 'map.overview.show': 'Teljes utazás megjelenítése', 'map.lock.lock': 'Térképnézet zárolása', 'map.lock.unlock': 'A térkép kövesse a kijelölést', diff --git a/shared/src/i18n/id/collection.ts b/shared/src/i18n/id/collection.ts index 3d2a99bfa..3287ea95b 100644 --- a/shared/src/i18n/id/collection.ts +++ b/shared/src/i18n/id/collection.ts @@ -58,9 +58,18 @@ const collection: TranslationStrings = { 'collections.importDone': '{count} tempat ditambahkan', 'collections.importDoneSkipped': '{count} sudah ada di daftar dan dibiarkan apa adanya', 'collections.importDoneClean': 'Semuanya kini ada di {name}', - 'collections.sort.default': 'Bawaan', + 'collections.sort.default': 'Urutan sendiri', + 'collections.reorderBlocked': 'Hapus pencarian dan filter untuk menyeret tempat ke urutanmu sendiri.', + 'collections.reorderHandle': 'Pindahkan {name}, atau gunakan tombol panah', 'collections.sort.nameAsc': 'Nama (A–Z)', 'collections.coordinates': 'Koordinat', + 'collections.findPosition': 'Temukan posisi', + 'collections.findPositionPlaceholder': 'Cari tempat ini di peta', + 'collections.findPositionHint': + 'Tempat ini belum punya koordinat, jadi belum muncul di peta. Cari di bawah dan pilih hasil yang tepat.', + 'collections.findPositionPicked': 'Posisi dipilih. Simpan untuk menampilkan tempat di peta.', + 'collections.addNoPositionHint': + 'Tanpa memilih hasil dari pencarian di atas, tempat ini tidak punya koordinat dan tidak akan muncul di peta.', 'collections.showList': 'Tampilkan daftar', 'collections.expandMap': 'Perbesar peta', 'collections.hero.mine': 'Koleksi saya', @@ -111,6 +120,12 @@ const collection: TranslationStrings = { 'collections.copyToTripTitle': 'Salin ke perjalanan', 'collections.copyN': 'Salin {count} ke perjalanan', 'collections.copyToTripSearch': 'Cari perjalanan', + 'collections.copyCarry.title': 'Ikut dibawa', + 'collections.copyCarry.notes': 'Catatan', + 'collections.copyCarry.notesHint': + 'Jika nonaktif, catatan tetap di daftar. Jika aktif, semua orang di perjalanan bisa membacanya.', + 'collections.copyCarry.tags': 'Tag', + 'collections.copyCarry.tagsHint': 'Tag yang dipilih menjadi tag perjalanan dan dibagikan ke para pelancongnya.', 'collections.searchLists': 'Cari daftar', 'collections.copyToTripConfirm': 'Salin', 'collections.noTrips': 'Belum ada perjalanan', @@ -189,6 +204,15 @@ const collection: TranslationStrings = { 'collections.file.gpxTrack': 'Berkas ini juga berisi {count} titik jejak. Jejak tidak diimpor, hanya titik lokasi.', 'collections.file.gpxEmpty': 'Berkas GPX ini tidak berisi titik lokasi, jadi tidak ada yang diimpor.', 'collections.file.errorNotGpx': 'Ini bukan berkas GPX.', + 'collections.file.errorNotMap': 'Berkas ini bukan peta KML atau KMZ yang bisa dibaca TREK.', + 'collections.file.mapPicked': '{picked} dari {total} dipilih', + 'collections.file.mapAll': 'Pilih semua', + 'collections.file.mapNone': 'Jangan pilih apa pun', + 'collections.file.mapSkipped': '{count} entri tidak disertakan', + 'collections.file.mapUnnamed': 'Tanpa nama', + 'collections.file.mapSkipLine': 'sebuah garis, bukan tempat', + 'collections.file.mapSkipNoPoint': 'sebuah area atau tanpa posisi', + 'collections.file.mapSkipInvalid': 'koordinat di luar jangkauan', 'collections.file.errorTooManyPlaces': 'Berkas ini berisi lebih dari {count} tempat. Pecah menjadi beberapa bagian dan impor satu per satu.', diff --git a/shared/src/i18n/id/map.ts b/shared/src/i18n/id/map.ts index 500dd0ab8..8304d573f 100644 --- a/shared/src/i18n/id/map.ts +++ b/shared/src/i18n/id/map.ts @@ -31,6 +31,8 @@ const map: TranslationStrings = { 'map.location.unavailable': 'Lokasi Anda tidak dapat ditentukan.', 'map.location.timeout': 'Penentuan lokasi terlalu lama. Coba lagi di tempat dengan pandangan langit yang lebih terbuka.', + 'map.placeNames.show': 'Tampilkan nama tempat', + 'map.placeNames.hide': 'Sembunyikan nama tempat', 'map.overview.show': 'Tampilkan seluruh perjalanan', 'map.lock.lock': 'Kunci tampilan peta', 'map.lock.unlock': 'Biarkan peta mengikuti pilihan', diff --git a/shared/src/i18n/it/collection.ts b/shared/src/i18n/it/collection.ts index 68cb586cb..d88dcee82 100644 --- a/shared/src/i18n/it/collection.ts +++ b/shared/src/i18n/it/collection.ts @@ -70,9 +70,18 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped': '{count} erano già in lista e sono rimasti com’erano', 'collections.importDoneSkipped.one': '{count} era già in lista ed è rimasto com’era', 'collections.importDoneClean': 'Ora sono tutti in {name}', - 'collections.sort.default': 'Predefinito', + 'collections.sort.default': 'Ordine personale', + 'collections.reorderBlocked': 'Cancella la ricerca e i filtri per trascinare i luoghi nel tuo ordine.', + 'collections.reorderHandle': 'Sposta {name}, oppure usa i tasti freccia', 'collections.sort.nameAsc': 'Nome (A–Z)', 'collections.coordinates': 'Coordinate', + 'collections.findPosition': 'Trova la posizione', + 'collections.findPositionPlaceholder': 'Cerca questo luogo sulla mappa', + 'collections.findPositionHint': + 'Questo luogo non ha ancora coordinate, quindi non compare sulla mappa. Cercalo qui sotto e scegli il risultato giusto.', + 'collections.findPositionPicked': 'Posizione scelta. Salva per mettere il luogo sulla mappa.', + 'collections.addNoPositionHint': + 'Senza un risultato scelto dalla ricerca qui sopra, questo luogo non avrà coordinate e non comparirà sulla mappa.', 'collections.showList': 'Mostra elenco', 'collections.expandMap': 'Espandi mappa', 'collections.hero.mine': 'La mia raccolta', @@ -125,6 +134,12 @@ const collection: TranslationStrings = { 'collections.copyN': 'Copia {count} nel viaggio', 'collections.copyN.one': 'Copia nel viaggio', 'collections.copyToTripSearch': 'Cerca viaggi', + 'collections.copyCarry.title': 'Da portare con sé', + 'collections.copyCarry.notes': 'Note', + 'collections.copyCarry.notesHint': + 'Disattivato, le note restano nell’elenco. Attivato, tutti i partecipanti al viaggio possono leggerle.', + 'collections.copyCarry.tags': 'Tag', + 'collections.copyCarry.tagsHint': 'Un tag scelto diventa un tag del viaggio, condiviso con i suoi viaggiatori.', 'collections.searchLists': 'Cerca elenchi', 'collections.copyToTripConfirm': 'Copia', 'collections.noTrips': 'Ancora nessun viaggio', @@ -218,6 +233,16 @@ const collection: TranslationStrings = { 'Questo file contiene anche {count} punto di traccia. Le tracce non vengono importate, solo i punti di passaggio.', 'collections.file.gpxEmpty': 'Questo file GPX non contiene punti di passaggio, quindi non c’è niente da importare.', 'collections.file.errorNotGpx': 'Questo non è un file GPX.', + 'collections.file.errorNotMap': 'Questo file non è una mappa KML o KMZ che TREK può leggere.', + 'collections.file.mapPicked': '{picked} di {total} scelti', + 'collections.file.mapAll': 'Scegli tutti', + 'collections.file.mapNone': 'Non sceglierne nessuno', + 'collections.file.mapSkipped': '{count} voci restano fuori', + 'collections.file.mapSkipped.one': '{count} voce resta fuori', + 'collections.file.mapUnnamed': 'Senza nome', + 'collections.file.mapSkipLine': 'una linea, non un luogo', + 'collections.file.mapSkipNoPoint': 'un’area o senza posizione', + 'collections.file.mapSkipInvalid': 'coordinate fuori intervallo', 'collections.file.errorTooManyPlaces': 'Questo file contiene più di {count} luoghi. Dividilo e importa le parti una alla volta.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/it/map.ts b/shared/src/i18n/it/map.ts index d4da4b2be..8a01dfcd3 100644 --- a/shared/src/i18n/it/map.ts +++ b/shared/src/i18n/it/map.ts @@ -31,6 +31,8 @@ const map: TranslationStrings = { 'L’accesso alla posizione è bloccato. Controlla le impostazioni del dispositivo; un’app installata ha un proprio permesso di localizzazione, separato dal browser.', 'map.location.unavailable': 'Impossibile determinare la tua posizione.', 'map.location.timeout': 'La localizzazione ha richiesto troppo tempo. Riprova con una visuale più libera del cielo.', + 'map.placeNames.show': 'Mostra i nomi dei luoghi', + 'map.placeNames.hide': 'Nascondi i nomi dei luoghi', 'map.overview.show': 'Mostra tutto il viaggio', 'map.lock.lock': 'Blocca la vista della mappa', 'map.lock.unlock': 'Lascia che la mappa segua la selezione', diff --git a/shared/src/i18n/ja/collection.ts b/shared/src/i18n/ja/collection.ts index bf3d0eef5..b8d6598db 100644 --- a/shared/src/i18n/ja/collection.ts +++ b/shared/src/i18n/ja/collection.ts @@ -58,9 +58,17 @@ const collection: TranslationStrings = { 'collections.importDone': '{count}件の場所を追加しました', 'collections.importDoneSkipped': '{count}件はすでにリストにあり、そのままにしました', 'collections.importDoneClean': 'すべて{name}に入りました', - 'collections.sort.default': 'デフォルト', + 'collections.sort.default': '自分の順序', + 'collections.reorderBlocked': '検索とフィルターを解除すると、場所をドラッグして自分の順序に並べ替えられます。', + 'collections.reorderHandle': '{name} を移動します。矢印キーも使えます', 'collections.sort.nameAsc': '名前順(A–Z)', 'collections.coordinates': '座標', + 'collections.findPosition': '位置を探す', + 'collections.findPositionPlaceholder': 'この場所を地図で検索', + 'collections.findPositionHint': + 'この場所にはまだ座標がないため、地図に表示されません。下で検索して、正しい候補を選んでください。', + 'collections.findPositionPicked': '位置を選びました。保存すると、場所が地図に表示されます。', + 'collections.addNoPositionHint': '上の検索から候補を選ばない場合、この場所には座標が付かず、地図に表示されません。', 'collections.showList': 'リストを表示', 'collections.expandMap': '地図を拡大', 'collections.hero.mine': 'マイコレクション', @@ -110,6 +118,12 @@ const collection: TranslationStrings = { 'collections.copyToTripTitle': '旅行にコピー', 'collections.copyN': '{count}件を旅行にコピー', 'collections.copyToTripSearch': '旅行を検索', + 'collections.copyCarry.title': '一緒に持っていく', + 'collections.copyCarry.notes': 'メモ', + 'collections.copyCarry.notesHint': + 'オフにすると、メモはリストに残ります。オンにすると、旅行のメンバー全員が読めます。', + 'collections.copyCarry.tags': 'タグ', + 'collections.copyCarry.tagsHint': '選んだタグは旅行のタグになり、同行者と共有されます。', 'collections.searchLists': 'リストを検索', 'collections.copyToTripConfirm': 'コピー', 'collections.noTrips': 'まだ旅行がありません', @@ -187,6 +201,15 @@ const collection: TranslationStrings = { 'このファイルにはトラックポイントも {count} 件あります。トラックはインポートされず、ウェイポイントのみが対象です。', 'collections.file.gpxEmpty': 'この GPX ファイルにはウェイポイントがないため、インポートするものがありません。', 'collections.file.errorNotGpx': 'これは GPX ファイルではありません。', + 'collections.file.errorNotMap': 'このファイルは、TREK が読み込める KML または KMZ の地図ではありません。', + 'collections.file.mapPicked': '{total} 件中 {picked} 件を選択', + 'collections.file.mapAll': 'すべて選択', + 'collections.file.mapNone': '選択を解除', + 'collections.file.mapSkipped': '{count} 件は除外されます', + 'collections.file.mapUnnamed': '名称なし', + 'collections.file.mapSkipLine': '線であり、場所ではありません', + 'collections.file.mapSkipNoPoint': 'エリア、または位置なし', + 'collections.file.mapSkipInvalid': '座標が範囲外', 'collections.file.errorTooManyPlaces': 'このファイルには {count} 件を超える場所があります。分割して、1 つずつインポートしてください。', diff --git a/shared/src/i18n/ja/map.ts b/shared/src/i18n/ja/map.ts index 8ddc63bc7..a9ba3b030 100644 --- a/shared/src/i18n/ja/map.ts +++ b/shared/src/i18n/ja/map.ts @@ -31,6 +31,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': '選択に合わせて地図を移動', diff --git a/shared/src/i18n/ko/collection.ts b/shared/src/i18n/ko/collection.ts index 8e90de9c3..82aa2c594 100644 --- a/shared/src/i18n/ko/collection.ts +++ b/shared/src/i18n/ko/collection.ts @@ -58,9 +58,18 @@ const collection: TranslationStrings = { 'collections.importDone': '장소 {count}개를 추가했습니다', 'collections.importDoneSkipped': '{count}개는 이미 목록에 있어 그대로 두었습니다', 'collections.importDoneClean': '이제 모두 {name}에 있습니다', - 'collections.sort.default': '기본', + 'collections.sort.default': '내 순서', + 'collections.reorderBlocked': '검색과 필터를 지우면 장소를 끌어서 내 순서로 정렬할 수 있습니다.', + 'collections.reorderHandle': '{name} 이동, 방향키로도 이동할 수 있습니다', 'collections.sort.nameAsc': '이름순 (A–Z)', 'collections.coordinates': '좌표', + 'collections.findPosition': '위치 찾기', + 'collections.findPositionPlaceholder': '지도에서 이 장소 검색', + 'collections.findPositionHint': + '이 장소에는 아직 좌표가 없어 지도에 표시되지 않습니다. 아래에서 검색해 알맞은 결과를 선택하세요.', + 'collections.findPositionPicked': '위치를 선택했습니다. 저장하면 장소가 지도에 표시됩니다.', + 'collections.addNoPositionHint': + '위 검색에서 결과를 선택하지 않으면 이 장소에는 좌표가 없어 지도에 표시되지 않습니다.', 'collections.showList': '목록 표시', 'collections.expandMap': '지도 확대', 'collections.hero.mine': '내 컬렉션', @@ -110,6 +119,11 @@ const collection: TranslationStrings = { 'collections.copyToTripTitle': '여행에 복사', 'collections.copyN': '{count}개를 여행에 복사', 'collections.copyToTripSearch': '여행 검색', + 'collections.copyCarry.title': '함께 가져가기', + 'collections.copyCarry.notes': '메모', + 'collections.copyCarry.notesHint': '끄면 메모는 목록에 남습니다. 켜면 여행의 모든 구성원이 읽을 수 있습니다.', + 'collections.copyCarry.tags': '태그', + 'collections.copyCarry.tagsHint': '선택한 태그는 여행의 태그가 되어 동행자와 공유됩니다.', 'collections.searchLists': '목록 검색', 'collections.copyToTripConfirm': '복사', 'collections.noTrips': '아직 여행이 없습니다', @@ -186,6 +200,15 @@ const collection: TranslationStrings = { '이 파일에는 트랙 포인트 {count}개도 있습니다. 트랙은 가져오지 않고 웨이포인트만 가져옵니다.', 'collections.file.gpxEmpty': '이 GPX 파일에는 웨이포인트가 없어 가져올 것이 없습니다.', 'collections.file.errorNotGpx': 'GPX 파일이 아닙니다.', + 'collections.file.errorNotMap': '이 파일은 TREK이 읽을 수 있는 KML 또는 KMZ 지도가 아닙니다.', + 'collections.file.mapPicked': '{total}개 중 {picked}개 선택됨', + 'collections.file.mapAll': '모두 선택', + 'collections.file.mapNone': '선택 안 함', + 'collections.file.mapSkipped': '{count}개 항목은 제외됩니다', + 'collections.file.mapUnnamed': '이름 없음', + 'collections.file.mapSkipLine': '선이며 장소가 아님', + 'collections.file.mapSkipNoPoint': '영역이거나 위치 없음', + 'collections.file.mapSkipInvalid': '좌표가 범위를 벗어남', 'collections.file.errorTooManyPlaces': '이 파일에는 장소가 {count}개보다 많습니다. 나눠서 하나씩 가져오세요.', 'collections.share.title': '목록 공유', diff --git a/shared/src/i18n/ko/map.ts b/shared/src/i18n/ko/map.ts index c3423c4ae..25fa76568 100644 --- a/shared/src/i18n/ko/map.ts +++ b/shared/src/i18n/ko/map.ts @@ -31,6 +31,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': '선택 항목에 따라 지도 이동', diff --git a/shared/src/i18n/nl/collection.ts b/shared/src/i18n/nl/collection.ts index af2a4f929..bdcbccf1a 100644 --- a/shared/src/i18n/nl/collection.ts +++ b/shared/src/i18n/nl/collection.ts @@ -70,9 +70,18 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped': '{count} stonden er al op en zijn ongewijzigd gebleven', 'collections.importDoneSkipped.one': '{count} stond er al op en is ongewijzigd gebleven', 'collections.importDoneClean': 'Ze staan nu allemaal in {name}', - 'collections.sort.default': 'Standaard', + 'collections.sort.default': 'Eigen volgorde', + 'collections.reorderBlocked': 'Wis de zoekopdracht en de filters om plaatsen in je eigen volgorde te slepen.', + 'collections.reorderHandle': '{name} verplaatsen, of gebruik de pijltjestoetsen', 'collections.sort.nameAsc': 'Naam (A–Z)', 'collections.coordinates': 'Coördinaten', + 'collections.findPosition': 'Positie zoeken', + 'collections.findPositionPlaceholder': 'Zoek deze plaats op de kaart', + 'collections.findPositionHint': + 'Deze plaats heeft nog geen coördinaten en staat daarom niet op de kaart. Zoek hem hieronder en kies het juiste resultaat.', + 'collections.findPositionPicked': 'Positie gekozen. Sla op om de plaats op de kaart te zetten.', + 'collections.addNoPositionHint': + 'Zonder een gekozen resultaat uit de zoekopdracht hierboven krijgt deze plaats geen coördinaten en staat hij niet op de kaart.', 'collections.showList': 'Lijst tonen', 'collections.expandMap': 'Kaart vergroten', 'collections.hero.mine': 'Mijn collectie', @@ -125,6 +134,12 @@ const collection: TranslationStrings = { 'collections.copyN': '{count} naar reis kopiëren', 'collections.copyN.one': 'Naar reis kopiëren', 'collections.copyToTripSearch': 'Reizen zoeken', + 'collections.copyCarry.title': 'Meenemen', + 'collections.copyCarry.notes': 'Notities', + 'collections.copyCarry.notesHint': + 'Uitgeschakeld blijven de notities in de lijst. Ingeschakeld kan iedereen in de reis ze lezen.', + 'collections.copyCarry.tags': 'Tags', // same-as-en + 'collections.copyCarry.tagsHint': 'Een gekozen tag wordt een tag van de reis, gedeeld met de reizigers.', 'collections.searchLists': 'Lijsten zoeken', 'collections.copyToTripConfirm': 'Kopiëren', 'collections.noTrips': 'Nog geen reizen', @@ -218,6 +233,16 @@ const collection: TranslationStrings = { 'Dit bestand bevat ook {count} trackpunt. Tracks worden niet geïmporteerd, alleen waypoints.', 'collections.file.gpxEmpty': 'Dit GPX-bestand bevat geen waypoints, dus er valt niets te importeren.', 'collections.file.errorNotGpx': 'Dit is geen GPX-bestand.', + 'collections.file.errorNotMap': 'Dit bestand is geen KML- of KMZ-kaart die TREK kan lezen.', + 'collections.file.mapPicked': '{picked} van {total} gekozen', + 'collections.file.mapAll': 'Alles kiezen', + 'collections.file.mapNone': 'Niets kiezen', + 'collections.file.mapSkipped': '{count} items worden overgeslagen', + 'collections.file.mapSkipped.one': '{count} item wordt overgeslagen', + 'collections.file.mapUnnamed': 'Zonder naam', + 'collections.file.mapSkipLine': 'een lijn, geen plaats', + 'collections.file.mapSkipNoPoint': 'een vlak of zonder positie', + 'collections.file.mapSkipInvalid': 'coördinaten buiten bereik', 'collections.file.errorTooManyPlaces': 'Dit bestand bevat meer dan {count} plekken. Splits het op en importeer de delen een voor een.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/nl/map.ts b/shared/src/i18n/nl/map.ts index 922e5865e..5840664cb 100644 --- a/shared/src/i18n/nl/map.ts +++ b/shared/src/i18n/nl/map.ts @@ -32,6 +32,8 @@ const map: TranslationStrings = { 'Locatietoegang is geblokkeerd. Controleer de apparaatinstellingen; een geïnstalleerde app heeft een eigen locatiemachtiging, los van de browser.', 'map.location.unavailable': 'Je locatie kon niet worden bepaald.', 'map.location.timeout': 'Het bepalen van je locatie duurde te lang. Probeer het opnieuw met vrij zicht op de lucht.', + 'map.placeNames.show': 'Plaatsnamen tonen', + 'map.placeNames.hide': 'Plaatsnamen verbergen', 'map.overview.show': 'Hele reis tonen', 'map.lock.lock': 'Kaartweergave vergrendelen', 'map.lock.unlock': 'Kaart de selectie laten volgen', diff --git a/shared/src/i18n/pl/collection.ts b/shared/src/i18n/pl/collection.ts index 26bac1326..9110fbc87 100644 --- a/shared/src/i18n/pl/collection.ts +++ b/shared/src/i18n/pl/collection.ts @@ -94,9 +94,18 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped.few': '{count} miejsca były już na liście i zostały bez zmian', 'collections.importDoneSkipped.many': '{count} miejsc było już na liście i zostało bez zmian', 'collections.importDoneClean': 'Teraz wszystkie są w {name}', - 'collections.sort.default': 'Domyślnie', + 'collections.sort.default': 'Własna kolejność', + 'collections.reorderBlocked': 'Wyczyść wyszukiwanie i filtry, aby przeciągać miejsca do własnej kolejności.', + 'collections.reorderHandle': 'Przenieś {name} lub użyj klawiszy strzałek', 'collections.sort.nameAsc': 'Nazwa (A–Z)', 'collections.coordinates': 'Współrzędne', + 'collections.findPosition': 'Znajdź pozycję', + 'collections.findPositionPlaceholder': 'Wyszukaj to miejsce na mapie', + 'collections.findPositionHint': + 'To miejsce nie ma jeszcze współrzędnych, więc nie ma go na mapie. Wyszukaj je poniżej i wybierz właściwy wynik.', + 'collections.findPositionPicked': 'Pozycja wybrana. Zapisz, aby umieścić miejsce na mapie.', + 'collections.addNoPositionHint': + 'Bez wybrania wyniku z wyszukiwania powyżej to miejsce nie dostanie współrzędnych i nie pojawi się na mapie.', 'collections.showList': 'Pokaż listę', 'collections.expandMap': 'Powiększ mapę', 'collections.hero.mine': 'Moja kolekcja', @@ -153,6 +162,12 @@ const collection: TranslationStrings = { 'collections.copyN.few': 'Kopiuj {count} do podróży', 'collections.copyN.many': 'Kopiuj {count} do podróży', 'collections.copyToTripSearch': 'Szukaj podróży', + 'collections.copyCarry.title': 'Zabierz ze sobą', + 'collections.copyCarry.notes': 'Notatki', + 'collections.copyCarry.notesHint': + 'Po wyłączeniu notatki zostają na liście. Po włączeniu mogą je czytać wszyscy w podróży.', + 'collections.copyCarry.tags': 'Tagi', + 'collections.copyCarry.tagsHint': 'Wybrany tag staje się tagiem podróży i jest widoczny dla współpodróżnych.', 'collections.searchLists': 'Szukaj list', 'collections.copyToTripConfirm': 'Kopiuj', 'collections.noTrips': 'Brak podróży', @@ -271,6 +286,18 @@ const collection: TranslationStrings = { 'Plik zawiera też {count} punktów śladu. Ślady nie są importowane, tylko punkty trasy.', 'collections.file.gpxEmpty': 'Ten plik GPX nie zawiera punktów trasy, więc nie ma czego importować.', 'collections.file.errorNotGpx': 'To nie jest plik GPX.', + 'collections.file.errorNotMap': 'Ten plik nie jest mapą KML ani KMZ, którą TREK potrafi odczytać.', + 'collections.file.mapPicked': 'Wybrano {picked} z {total}', + 'collections.file.mapAll': 'Wybierz wszystko', + 'collections.file.mapNone': 'Nie wybieraj nic', + 'collections.file.mapSkipped': '{count} wpisów zostanie pominiętych', + 'collections.file.mapSkipped.one': '{count} wpis zostanie pominięty', + 'collections.file.mapSkipped.few': '{count} wpisy zostaną pominięte', + 'collections.file.mapSkipped.many': '{count} wpisów zostanie pominiętych', + 'collections.file.mapUnnamed': 'Bez nazwy', + 'collections.file.mapSkipLine': 'linia, nie miejsce', + 'collections.file.mapSkipNoPoint': 'obszar lub brak pozycji', + 'collections.file.mapSkipInvalid': 'współrzędne poza zakresem', 'collections.file.errorTooManyPlaces': 'Ten plik zawiera więcej niż {count} miejsca. Podziel go i importuj części po kolei.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/pl/map.ts b/shared/src/i18n/pl/map.ts index 4d440b174..26be7e1f5 100644 --- a/shared/src/i18n/pl/map.ts +++ b/shared/src/i18n/pl/map.ts @@ -31,6 +31,8 @@ const map: TranslationStrings = { 'Dostęp do lokalizacji jest zablokowany. Sprawdź ustawienia urządzenia; zainstalowana aplikacja ma własne uprawnienie do lokalizacji, niezależne od przeglądarki.', 'map.location.unavailable': 'Nie udało się ustalić Twojej lokalizacji.', 'map.location.timeout': 'Ustalanie lokalizacji trwało zbyt długo. Spróbuj ponownie przy lepszej widoczności nieba.', + 'map.placeNames.show': 'Pokaż nazwy miejsc', + 'map.placeNames.hide': 'Ukryj nazwy miejsc', 'map.overview.show': 'Pokaż całą podróż', 'map.lock.lock': 'Zablokuj widok mapy', 'map.lock.unlock': 'Pozwól mapie podążać za zaznaczeniem', diff --git a/shared/src/i18n/ru/collection.ts b/shared/src/i18n/ru/collection.ts index a9d0575aa..fc45ba818 100644 --- a/shared/src/i18n/ru/collection.ts +++ b/shared/src/i18n/ru/collection.ts @@ -94,9 +94,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': 'Моя коллекция', @@ -152,6 +161,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': 'Пока нет поездок', @@ -271,6 +286,18 @@ 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.one': '{count} запись будет пропущена', + '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.one': diff --git a/shared/src/i18n/ru/map.ts b/shared/src/i18n/ru/map.ts index 213f6e23a..4a4b6cd13 100644 --- a/shared/src/i18n/ru/map.ts +++ b/shared/src/i18n/ru/map.ts @@ -32,6 +32,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': 'Карта следует за выбором', diff --git a/shared/src/i18n/sk/collection.ts b/shared/src/i18n/sk/collection.ts index cc6d40939..a510ef5e5 100644 --- a/shared/src/i18n/sk/collection.ts +++ b/shared/src/i18n/sk/collection.ts @@ -82,9 +82,18 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped.one': '{count} miesto už na zozname bolo a zostalo bez zmeny', 'collections.importDoneSkipped.few': '{count} miesta už na zozname boli a zostali bez zmeny', 'collections.importDoneClean': 'Teraz sú všetky v {name}', - 'collections.sort.default': 'Predvolené', + 'collections.sort.default': 'Vlastné poradie', + 'collections.reorderBlocked': 'Vymažte hľadanie a filtre, aby ste mohli miesta presúvať do vlastného poradia.', + 'collections.reorderHandle': 'Presunúť {name} alebo použiť klávesy so šípkami', 'collections.sort.nameAsc': 'Názov (A–Z)', 'collections.coordinates': 'Súradnice', + 'collections.findPosition': 'Nájsť polohu', + 'collections.findPositionPlaceholder': 'Vyhľadať toto miesto na mape', + 'collections.findPositionHint': + 'Toto miesto zatiaľ nemá súradnice, a preto nie je na mape. Vyhľadajte ho nižšie a vyberte správny výsledok.', + 'collections.findPositionPicked': 'Poloha vybraná. Po uložení sa miesto zobrazí na mape.', + 'collections.addNoPositionHint': + 'Bez výberu výsledku z vyhľadávania vyššie nebude mať toto miesto súradnice a na mape sa nezobrazí.', 'collections.showList': 'Zobraziť zoznam', 'collections.expandMap': 'Zväčšiť mapu', 'collections.hero.mine': 'Moja zbierka', @@ -139,6 +148,12 @@ const collection: TranslationStrings = { 'collections.copyN.one': 'Kopírovať do cesty', 'collections.copyN.few': 'Kopírovať {count} do cesty', 'collections.copyToTripSearch': 'Hľadať cesty', + 'collections.copyCarry.title': 'Vziať so sebou', + 'collections.copyCarry.notes': 'Poznámky', + 'collections.copyCarry.notesHint': + 'Keď je vypnuté, poznámky zostanú v zozname. Keď je zapnuté, môže ich čítať každý v ceste.', + 'collections.copyCarry.tags': 'Štítky', + 'collections.copyCarry.tagsHint': 'Vybraný štítok sa stane štítkom cesty a uvidia ho všetci spolucestujúci.', 'collections.searchLists': 'Hľadať zoznamy', 'collections.copyToTripConfirm': 'Kopírovať', 'collections.noTrips': 'Zatiaľ žiadne cesty', @@ -241,6 +256,17 @@ const collection: TranslationStrings = { 'collections.file.gpxTrack.few': 'Tento súbor má aj {count} body stopy. Stopy sa neimportujú, len trasové body.', 'collections.file.gpxEmpty': 'Tento súbor GPX nemá žiadne trasové body, takže nie je čo importovať.', 'collections.file.errorNotGpx': 'Toto nie je súbor GPX.', + 'collections.file.errorNotMap': 'Tento súbor nie je mapa KML ani KMZ, ktorú by TREK vedel prečítať.', + 'collections.file.mapPicked': 'Vybrané: {picked} z {total}', + 'collections.file.mapAll': 'Vybrať všetko', + 'collections.file.mapNone': 'Nevybrať nič', + 'collections.file.mapSkipped': '{count} položiek sa vynechá', + 'collections.file.mapSkipped.one': '{count} položka sa vynechá', + 'collections.file.mapSkipped.few': '{count} položky sa vynechajú', + 'collections.file.mapUnnamed': 'Bez názvu', + 'collections.file.mapSkipLine': 'čiara, nie miesto', + 'collections.file.mapSkipNoPoint': 'plocha alebo bez polohy', + 'collections.file.mapSkipInvalid': 'súradnice mimo rozsahu', 'collections.file.errorTooManyPlaces': 'Tento súbor má viac než {count} miest. Rozdeľte ho a importujte časti po jednej.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/sk/map.ts b/shared/src/i18n/sk/map.ts index dd23a32b9..68272b85f 100644 --- a/shared/src/i18n/sk/map.ts +++ b/shared/src/i18n/sk/map.ts @@ -30,6 +30,8 @@ const map: TranslationStrings = { 'Prístup k polohe je zablokovaný. Skontrolujte nastavenia zariadenia; nainštalovaná aplikácia má vlastné oprávnenie na polohu, nezávislé od prehliadača.', 'map.location.unavailable': 'Vašu polohu sa nepodarilo zistiť.', 'map.location.timeout': 'Zisťovanie polohy trvalo príliš dlho. Skúste to znova s voľným výhľadom na oblohu.', + 'map.placeNames.show': 'Zobraziť názvy miest', + 'map.placeNames.hide': 'Skryť názvy miest', 'map.overview.show': 'Zobraziť celú cestu', 'map.lock.lock': 'Uzamknúť zobrazenie mapy', 'map.lock.unlock': 'Nechať mapu sledovať výber', diff --git a/shared/src/i18n/sv/collection.ts b/shared/src/i18n/sv/collection.ts index a4df72123..19be2b98c 100644 --- a/shared/src/i18n/sv/collection.ts +++ b/shared/src/i18n/sv/collection.ts @@ -70,9 +70,18 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped': '{count} fanns redan i listan och lämnades som de var', 'collections.importDoneSkipped.one': '{count} fanns redan i listan och lämnades som den var', 'collections.importDoneClean': 'Nu finns de alla i {name}', - 'collections.sort.default': 'Standard', + 'collections.sort.default': 'Egen ordning', + 'collections.reorderBlocked': 'Rensa sökningen och filtren för att dra platser till din egen ordning.', + 'collections.reorderHandle': 'Flytta {name}, eller använd piltangenterna', 'collections.sort.nameAsc': 'Namn (A–Ö)', 'collections.coordinates': 'Koordinater', + 'collections.findPosition': 'Hitta positionen', + 'collections.findPositionPlaceholder': 'Sök efter den här platsen på kartan', + 'collections.findPositionHint': + 'Den här platsen har inga koordinater än och syns därför inte på kartan. Sök efter den nedan och välj rätt träff.', + 'collections.findPositionPicked': 'Position vald. Spara för att lägga platsen på kartan.', + 'collections.addNoPositionHint': + 'Utan en vald träff från sökningen ovan får den här platsen inga koordinater och syns inte på kartan.', 'collections.showList': 'Visa lista', 'collections.expandMap': 'Förstora karta', 'collections.hero.mine': 'Min samling', @@ -124,6 +133,12 @@ const collection: TranslationStrings = { 'collections.copyN': 'Kopiera {count} till resa', 'collections.copyN.one': 'Kopiera till resa', 'collections.copyToTripSearch': 'Sök resor', + 'collections.copyCarry.title': 'Ta med', + 'collections.copyCarry.notes': 'Anteckningar', + 'collections.copyCarry.notesHint': + 'Avstängt ligger anteckningarna kvar i listan. Påslaget kan alla i resan läsa dem.', + 'collections.copyCarry.tags': 'Taggar', + 'collections.copyCarry.tagsHint': 'En vald tagg blir en tagg för resan och delas med resenärerna.', 'collections.searchLists': 'Sök listor', 'collections.copyToTripConfirm': 'Kopiera', 'collections.noTrips': 'Inga resor ännu', @@ -215,6 +230,16 @@ const collection: TranslationStrings = { 'collections.file.gpxTrack.one': 'Filen innehåller också {count} spårpunkt. Spår importeras inte, bara vägpunkter.', 'collections.file.gpxEmpty': 'Den här GPX-filen har inga vägpunkter, så det finns inget att importera.', 'collections.file.errorNotGpx': 'Det här är ingen GPX-fil.', + 'collections.file.errorNotMap': 'Den här filen är ingen KML- eller KMZ-karta som TREK kan läsa.', + 'collections.file.mapPicked': '{picked} av {total} valda', + 'collections.file.mapAll': 'Välj alla', + 'collections.file.mapNone': 'Välj ingen', + 'collections.file.mapSkipped': '{count} poster lämnas utanför', + 'collections.file.mapSkipped.one': '{count} post lämnas utanför', + 'collections.file.mapUnnamed': 'Namnlös', + 'collections.file.mapSkipLine': 'en linje, ingen plats', + 'collections.file.mapSkipNoPoint': 'ett område eller utan position', + 'collections.file.mapSkipInvalid': 'koordinater utanför giltigt intervall', 'collections.file.errorTooManyPlaces': 'Filen har fler än {count} platser. Dela upp den och importera delarna en i taget.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/sv/map.ts b/shared/src/i18n/sv/map.ts index af95a7306..aebedf289 100644 --- a/shared/src/i18n/sv/map.ts +++ b/shared/src/i18n/sv/map.ts @@ -30,6 +30,8 @@ const map: TranslationStrings = { 'Platsåtkomst är blockerad. Kontrollera enhetens inställningar; en installerad app har ett eget platstillstånd, skilt från webbläsaren.', 'map.location.unavailable': 'Din plats kunde inte fastställas.', 'map.location.timeout': 'Platsbestämningen tog för lång tid. Försök igen med friare sikt mot himlen.', + 'map.placeNames.show': 'Visa platsnamn', + 'map.placeNames.hide': 'Dölj platsnamn', 'map.overview.show': 'Visa hela resan', 'map.lock.lock': 'Lås kartvyn', 'map.lock.unlock': 'Låt kartan följa markeringen', diff --git a/shared/src/i18n/th/collection.ts b/shared/src/i18n/th/collection.ts index a952b3031..a1ee5ffd9 100644 --- a/shared/src/i18n/th/collection.ts +++ b/shared/src/i18n/th/collection.ts @@ -58,9 +58,16 @@ const collection: TranslationStrings = { 'collections.importDone': 'เพิ่มสถานที่ {count} แห่งแล้ว', 'collections.importDoneSkipped': 'มี {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': 'คอลเลกชันของฉัน', @@ -110,6 +117,11 @@ const collection: TranslationStrings = { 'collections.copyToTripTitle': 'คัดลอกไปที่การเดินทาง', 'collections.copyN': 'คัดลอก {count} ไปยังการเดินทาง', 'collections.copyToTripSearch': 'ค้นหาการเดินทาง', + 'collections.copyCarry.title': 'นำไปด้วย', + 'collections.copyCarry.notes': 'บันทึก', + 'collections.copyCarry.notesHint': 'เมื่อปิด บันทึกจะอยู่ในรายการเท่านั้น เมื่อเปิด ทุกคนในการเดินทางจะอ่านได้', + 'collections.copyCarry.tags': 'แท็ก', + 'collections.copyCarry.tagsHint': 'แท็กที่เลือกจะกลายเป็นแท็กของการเดินทางและแชร์ให้ผู้ร่วมเดินทาง', 'collections.searchLists': 'ค้นหารายการ', 'collections.copyToTripConfirm': 'คัดลอก', 'collections.noTrips': 'ยังไม่มีการเดินทาง', @@ -227,6 +239,15 @@ const collection: TranslationStrings = { 'collections.file.gpxTrack': 'ไฟล์นี้ยังมีจุดแทร็ก {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.mapUnnamed': 'ไม่มีชื่อ', + 'collections.file.mapSkipLine': 'เป็นเส้น ไม่ใช่สถานที่', + 'collections.file.mapSkipNoPoint': 'เป็นพื้นที่หรือไม่มีตำแหน่ง', + 'collections.file.mapSkipInvalid': 'พิกัดอยู่นอกช่วง', 'collections.file.errorTooManyPlaces': 'ไฟล์นี้มีสถานที่มากกว่า {count} แห่ง โปรดแยกไฟล์แล้วนำเข้าทีละส่วน', }; diff --git a/shared/src/i18n/th/map.ts b/shared/src/i18n/th/map.ts index 1edcc57da..8e75cb5d8 100644 --- a/shared/src/i18n/th/map.ts +++ b/shared/src/i18n/th/map.ts @@ -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': 'ให้แผนที่ติดตามรายการที่เลือก', diff --git a/shared/src/i18n/tr/collection.ts b/shared/src/i18n/tr/collection.ts index 5cad3570d..8819d73d6 100644 --- a/shared/src/i18n/tr/collection.ts +++ b/shared/src/i18n/tr/collection.ts @@ -70,9 +70,18 @@ const collection: TranslationStrings = { 'collections.importDoneSkipped': '{count} yer zaten listedeydi ve olduğu gibi bırakıldı', 'collections.importDoneSkipped.one': '{count} yer zaten listedeydi ve olduğu gibi bırakıldı', 'collections.importDoneClean': 'Artık hepsi {name} listesinde', - 'collections.sort.default': 'Varsayılan', + 'collections.sort.default': 'Kendi sıram', + 'collections.reorderBlocked': 'Yerleri kendi sıranıza sürüklemek için aramayı ve filtreleri temizleyin.', + 'collections.reorderHandle': '{name} yerini taşıyın veya ok tuşlarını kullanın', 'collections.sort.nameAsc': 'Ad (A–Z)', 'collections.coordinates': 'Koordinatlar', + 'collections.findPosition': 'Konumu bul', + 'collections.findPositionPlaceholder': 'Bu yeri haritada ara', + 'collections.findPositionHint': + 'Bu yerin henüz koordinatı yok, bu yüzden haritada görünmüyor. Aşağıda arayın ve doğru sonucu seçin.', + 'collections.findPositionPicked': 'Konum seçildi. Yeri haritaya koymak için kaydedin.', + 'collections.addNoPositionHint': + 'Yukarıdaki aramadan bir sonuç seçmezseniz bu yerin koordinatı olmaz ve haritada görünmez.', 'collections.showList': 'Listeyi göster', 'collections.expandMap': 'Haritayı genişlet', 'collections.hero.mine': 'Koleksiyonum', @@ -125,6 +134,11 @@ const collection: TranslationStrings = { 'collections.copyN': '{count} öğeyi geziye kopyala', 'collections.copyN.one': 'Geziye kopyala', 'collections.copyToTripSearch': 'Gezi ara', + 'collections.copyCarry.title': 'Birlikte götür', + 'collections.copyCarry.notes': 'Notlar', + 'collections.copyCarry.notesHint': 'Kapalıyken notlar listede kalır. Açıkken gezideki herkes okuyabilir.', + 'collections.copyCarry.tags': 'Etiketler', + 'collections.copyCarry.tagsHint': 'Seçilen etiket gezinin etiketi olur ve yol arkadaşlarıyla paylaşılır.', 'collections.searchLists': 'Listelerde ara', 'collections.copyToTripConfirm': 'Kopyala', 'collections.noTrips': 'Henüz gezi yok', @@ -216,6 +230,16 @@ const collection: TranslationStrings = { 'Bu dosyada ayrıca {count} iz noktası var. İzler içe aktarılmaz, yalnızca yol noktaları.', 'collections.file.gpxEmpty': 'Bu GPX dosyasında yol noktası yok, bu yüzden içe aktarılacak bir şey yok.', 'collections.file.errorNotGpx': 'Bu bir GPX dosyası değil.', + 'collections.file.errorNotMap': 'Bu dosya, TREK’in okuyabileceği bir KML veya KMZ haritası değil.', + 'collections.file.mapPicked': '{total} içinden {picked} seçildi', + 'collections.file.mapAll': 'Tümünü seç', + 'collections.file.mapNone': 'Hiçbirini seçme', + 'collections.file.mapSkipped': '{count} kayıt dışarıda bırakılıyor', + 'collections.file.mapSkipped.one': '{count} kayıt dışarıda bırakılıyor', + 'collections.file.mapUnnamed': 'Adsız', + 'collections.file.mapSkipLine': 'bir çizgi, yer değil', + 'collections.file.mapSkipNoPoint': 'bir alan veya konumsuz', + 'collections.file.mapSkipInvalid': 'koordinatlar aralık dışında', 'collections.file.errorTooManyPlaces': 'Bu dosyada {count} yerden fazlası var. Dosyayı bölüp parçaları tek tek içe aktar.', 'collections.file.errorTooManyPlaces.one': diff --git a/shared/src/i18n/tr/map.ts b/shared/src/i18n/tr/map.ts index 296b4d8ec..bece92017 100644 --- a/shared/src/i18n/tr/map.ts +++ b/shared/src/i18n/tr/map.ts @@ -30,6 +30,8 @@ const map: TranslationStrings = { 'Konum erişimi engellendi. Cihaz ayarlarını kontrol edin; yüklü bir uygulamanın tarayıcıdan ayrı kendi konum izni vardır.', 'map.location.unavailable': 'Konumunuz belirlenemedi.', 'map.location.timeout': 'Konum belirleme çok uzun sürdü. Gökyüzünü daha iyi gören bir yerde tekrar deneyin.', + 'map.placeNames.show': 'Yer adlarını göster', + 'map.placeNames.hide': 'Yer adlarını gizle', 'map.overview.show': 'Tüm geziyi göster', 'map.lock.lock': 'Harita görünümünü kilitle', 'map.lock.unlock': 'Harita seçimi takip etsin', diff --git a/shared/src/i18n/uk/collection.ts b/shared/src/i18n/uk/collection.ts index 6817c4ce2..978eaccea 100644 --- a/shared/src/i18n/uk/collection.ts +++ b/shared/src/i18n/uk/collection.ts @@ -94,9 +94,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': 'Моя колекція', @@ -152,6 +161,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': 'Поки немає подорожей', @@ -268,6 +283,18 @@ const collection: TranslationStrings = { 'collections.file.gpxTrack.many': 'У файлі також є {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.one': 'Буде пропущено {count} запис', + '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.one': diff --git a/shared/src/i18n/uk/map.ts b/shared/src/i18n/uk/map.ts index 738271737..a0c5d97a5 100644 --- a/shared/src/i18n/uk/map.ts +++ b/shared/src/i18n/uk/map.ts @@ -31,6 +31,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': 'Дозволити карті стежити за вибором', diff --git a/shared/src/i18n/vi/collection.ts b/shared/src/i18n/vi/collection.ts index 48d38c3ca..ea9db5f2e 100644 --- a/shared/src/i18n/vi/collection.ts +++ b/shared/src/i18n/vi/collection.ts @@ -58,9 +58,18 @@ const collection: TranslationStrings = { 'collections.importDone': 'Đã thêm {count} địa điểm', 'collections.importDoneSkipped': '{count} địa điểm đã có sẵn trong danh sách và được giữ nguyên', 'collections.importDoneClean': 'Giờ tất cả đều nằm trong {name}', - 'collections.sort.default': 'Mặc định', + 'collections.sort.default': 'Thứ tự riêng', + 'collections.reorderBlocked': 'Xóa tìm kiếm và bộ lọc để kéo các địa điểm theo thứ tự riêng của bạn.', + 'collections.reorderHandle': 'Di chuyển {name}, hoặc dùng phím mũi tên', 'collections.sort.nameAsc': 'Tên (A–Z)', 'collections.coordinates': 'Tọa độ', + 'collections.findPosition': 'Tìm vị trí', + 'collections.findPositionPlaceholder': 'Tìm địa điểm này trên bản đồ', + 'collections.findPositionHint': + 'Địa điểm này chưa có tọa độ nên chưa hiện trên bản đồ. Hãy tìm bên dưới và chọn kết quả đúng.', + 'collections.findPositionPicked': 'Đã chọn vị trí. Lưu để đưa địa điểm lên bản đồ.', + 'collections.addNoPositionHint': + 'Nếu không chọn một kết quả từ ô tìm kiếm phía trên, địa điểm này sẽ không có tọa độ và không hiện trên bản đồ.', 'collections.showList': 'Hiện danh sách', 'collections.expandMap': 'Mở rộng bản đồ', 'collections.hero.mine': 'Bộ sưu tập của tôi', @@ -111,6 +120,13 @@ const collection: TranslationStrings = { 'collections.copyToTripTitle': 'Sao chép vào chuyến đi', 'collections.copyN': 'Sao chép {count} vào chuyến đi', 'collections.copyToTripSearch': 'Tìm chuyến đi', + 'collections.copyCarry.title': 'Mang theo', + 'collections.copyCarry.notes': 'Ghi chú', + 'collections.copyCarry.notesHint': + 'Khi tắt, ghi chú vẫn ở lại trong danh sách. Khi bật, mọi người trong chuyến đi đều đọc được.', + 'collections.copyCarry.tags': 'Thẻ', + 'collections.copyCarry.tagsHint': + 'Thẻ đã chọn sẽ trở thành thẻ của chuyến đi và được chia sẻ với những người đi cùng.', 'collections.searchLists': 'Tìm danh sách', 'collections.copyToTripConfirm': 'Sao chép', 'collections.noTrips': 'Chưa có chuyến đi nào', @@ -188,6 +204,15 @@ const collection: TranslationStrings = { 'Tệp này còn có {count} điểm thuộc vết đường đi. Vết đường đi không được nhập, chỉ nhập các điểm tham chiếu.', 'collections.file.gpxEmpty': 'Tệp GPX này không có điểm tham chiếu nào, nên không có gì để nhập.', 'collections.file.errorNotGpx': 'Đây không phải tệp GPX.', + 'collections.file.errorNotMap': 'Tệp này không phải bản đồ KML hoặc KMZ mà TREK đọc được.', + 'collections.file.mapPicked': 'Đã chọn {picked} trên {total}', + 'collections.file.mapAll': 'Chọn tất cả', + 'collections.file.mapNone': 'Bỏ chọn tất cả', + 'collections.file.mapSkipped': '{count} mục bị bỏ qua', + 'collections.file.mapUnnamed': 'Chưa đặt tên', + 'collections.file.mapSkipLine': 'một đường, không phải địa điểm', + 'collections.file.mapSkipNoPoint': 'một vùng hoặc không có vị trí', + 'collections.file.mapSkipInvalid': 'tọa độ nằm ngoài phạm vi', 'collections.file.errorTooManyPlaces': 'Tệp này có hơn {count} địa điểm. Hãy chia nhỏ và nhập từng phần một.', 'collections.share.title': 'Chia sẻ danh sách', diff --git a/shared/src/i18n/vi/map.ts b/shared/src/i18n/vi/map.ts index fcc728755..42ec11251 100644 --- a/shared/src/i18n/vi/map.ts +++ b/shared/src/i18n/vi/map.ts @@ -33,6 +33,8 @@ const map: TranslationStrings = { 'map.location.unavailable': 'Không thể xác định vị trí của bạn.', 'map.location.timeout': 'Việc xác định vị trí mất quá nhiều thời gian. Hãy thử lại ở nơi nhìn thấy bầu trời thoáng hơn.', + 'map.placeNames.show': 'Hiện tên địa điểm', + 'map.placeNames.hide': 'Ẩn tên địa điểm', 'map.overview.show': 'Hiện toàn bộ chuyến đi', 'map.lock.lock': 'Khóa góc nhìn bản đồ', 'map.lock.unlock': 'Để bản đồ đi theo mục đang chọn', diff --git a/shared/src/i18n/zh-TW/collection.ts b/shared/src/i18n/zh-TW/collection.ts index e6e0a3108..f6706108f 100644 --- a/shared/src/i18n/zh-TW/collection.ts +++ b/shared/src/i18n/zh-TW/collection.ts @@ -58,9 +58,16 @@ const collection: TranslationStrings = { 'collections.importDone': '已新增 {count} 個地點', 'collections.importDoneSkipped': '{count} 個已在清單中,保持原樣', 'collections.importDoneClean': '現在它們都在{name}裡', - 'collections.sort.default': '預設', + 'collections.sort.default': '自訂順序', + 'collections.reorderBlocked': '清除搜尋和篩選後,就可以把地點拖成你自己的順序。', + 'collections.reorderHandle': '移動{name},也可以使用方向鍵', 'collections.sort.nameAsc': '名稱 (A–Z)', 'collections.coordinates': '座標', + 'collections.findPosition': '尋找位置', + 'collections.findPositionPlaceholder': '在地圖上搜尋這個地點', + 'collections.findPositionHint': '這個地點還沒有座標,所以不會顯示在地圖上。請在下方搜尋並選擇正確的結果。', + 'collections.findPositionPicked': '已選定位置。儲存後,地點會顯示在地圖上。', + 'collections.addNoPositionHint': '如果不從上方搜尋結果中選擇,這個地點就沒有座標,也不會顯示在地圖上。', 'collections.showList': '顯示清單', 'collections.expandMap': '展開地圖', 'collections.hero.mine': '我的收藏', @@ -110,6 +117,11 @@ const collection: TranslationStrings = { 'collections.copyToTripTitle': '複製到行程', 'collections.copyN': '將 {count} 個複製到行程', 'collections.copyToTripSearch': '搜尋行程', + 'collections.copyCarry.title': '一併帶上', + 'collections.copyCarry.notes': '備註', + 'collections.copyCarry.notesHint': '關閉時,備註仍留在清單裡;開啟後,行程中的所有人都能看到。', + 'collections.copyCarry.tags': '標籤', + 'collections.copyCarry.tagsHint': '選取的標籤會成為行程的標籤,並與同行者共享。', 'collections.searchLists': '搜尋清單', 'collections.copyToTripConfirm': '複製', 'collections.noTrips': '尚無行程', @@ -184,6 +196,15 @@ const collection: TranslationStrings = { 'collections.file.gpxTrack': '這個檔案還包含 {count} 個軌跡點。軌跡不會匯入,只匯入航點。', 'collections.file.gpxEmpty': '這個 GPX 檔案沒有航點,沒有可匯入的內容。', 'collections.file.errorNotGpx': '這不是 GPX 檔案。', + 'collections.file.errorNotMap': '這個檔案不是 TREK 能讀取的 KML 或 KMZ 地圖。', + 'collections.file.mapPicked': '已選 {picked} / {total}', + 'collections.file.mapAll': '全選', + 'collections.file.mapNone': '全不選', + 'collections.file.mapSkipped': '{count} 個項目將被略過', + 'collections.file.mapUnnamed': '未命名', + 'collections.file.mapSkipLine': '這是一條線,不是地點', + 'collections.file.mapSkipNoPoint': '這是一個區域,或沒有位置', + 'collections.file.mapSkipInvalid': '座標超出範圍', 'collections.file.errorTooManyPlaces': '這個檔案包含超過 {count} 個地點。請分割後逐一匯入。', 'collections.share.title': '分享清單', diff --git a/shared/src/i18n/zh-TW/map.ts b/shared/src/i18n/zh-TW/map.ts index 6244f8d34..47ca8afba 100644 --- a/shared/src/i18n/zh-TW/map.ts +++ b/shared/src/i18n/zh-TW/map.ts @@ -29,6 +29,8 @@ const map: TranslationStrings = { 'map.location.denied': '定位權限已被封鎖。請檢查裝置設定,已安裝的應用程式擁有與瀏覽器分開的定位權限。', 'map.location.unavailable': '無法判斷你的位置。', 'map.location.timeout': '定位花費的時間過長。請在能看到天空的開闊位置重試。', + 'map.placeNames.show': '顯示地名', + 'map.placeNames.hide': '隱藏地名', 'map.overview.show': '顯示整趟行程', 'map.lock.lock': '鎖定地圖視角', 'map.lock.unlock': '讓地圖跟隨所選項目', diff --git a/shared/src/i18n/zh/collection.ts b/shared/src/i18n/zh/collection.ts index acc181668..98bedb38a 100644 --- a/shared/src/i18n/zh/collection.ts +++ b/shared/src/i18n/zh/collection.ts @@ -58,9 +58,16 @@ const collection: TranslationStrings = { 'collections.importDone': '已添加 {count} 个地点', 'collections.importDoneSkipped': '{count} 个已在列表中,保持原样', 'collections.importDoneClean': '现在它们都在{name}里', - 'collections.sort.default': '默认', + 'collections.sort.default': '自定义顺序', + 'collections.reorderBlocked': '清除搜索和筛选后,就可以把地点拖成你自己的顺序。', + 'collections.reorderHandle': '移动{name},也可以使用方向键', 'collections.sort.nameAsc': '名称 (A–Z)', 'collections.coordinates': '坐标', + 'collections.findPosition': '查找位置', + 'collections.findPositionPlaceholder': '在地图上搜索这个地点', + 'collections.findPositionHint': '这个地点还没有坐标,所以不会显示在地图上。请在下方搜索并选择正确的结果。', + 'collections.findPositionPicked': '已选定位置。保存后,地点会显示在地图上。', + 'collections.addNoPositionHint': '如果不从上方搜索结果中选择,这个地点就没有坐标,也不会显示在地图上。', 'collections.showList': '显示列表', 'collections.expandMap': '展开地图', 'collections.hero.mine': '我的收藏', @@ -110,6 +117,11 @@ const collection: TranslationStrings = { 'collections.copyToTripTitle': '复制到行程', 'collections.copyN': '将 {count} 个复制到行程', 'collections.copyToTripSearch': '搜索行程', + 'collections.copyCarry.title': '一并带上', + 'collections.copyCarry.notes': '备注', + 'collections.copyCarry.notesHint': '关闭时,备注仍留在清单里;开启后,行程中的所有人都能看到。', + 'collections.copyCarry.tags': '标签', + 'collections.copyCarry.tagsHint': '选中的标签会成为行程的标签,并与同行者共享。', 'collections.searchLists': '搜索清单', 'collections.copyToTripConfirm': '复制', 'collections.noTrips': '还没有行程', @@ -184,6 +196,15 @@ const collection: TranslationStrings = { 'collections.file.gpxTrack': '该文件还包含 {count} 个轨迹点。轨迹不会导入,只导入航点。', 'collections.file.gpxEmpty': '该 GPX 文件中没有航点,没有可导入的内容。', 'collections.file.errorNotGpx': '这不是 GPX 文件。', + 'collections.file.errorNotMap': '这个文件不是 TREK 能读取的 KML 或 KMZ 地图。', + 'collections.file.mapPicked': '已选 {picked} / {total}', + 'collections.file.mapAll': '全选', + 'collections.file.mapNone': '全不选', + 'collections.file.mapSkipped': '{count} 个条目将被略过', + 'collections.file.mapUnnamed': '未命名', + 'collections.file.mapSkipLine': '这是一条线,不是地点', + 'collections.file.mapSkipNoPoint': '这是一个区域,或没有位置', + 'collections.file.mapSkipInvalid': '坐标超出范围', 'collections.file.errorTooManyPlaces': '该文件包含超过 {count} 个地点。请拆分后逐个导入。', 'collections.share.title': '共享列表', diff --git a/shared/src/i18n/zh/map.ts b/shared/src/i18n/zh/map.ts index 10594f471..4ad60814b 100644 --- a/shared/src/i18n/zh/map.ts +++ b/shared/src/i18n/zh/map.ts @@ -29,6 +29,8 @@ const map: TranslationStrings = { 'map.location.denied': '定位权限已被阻止。请检查设备设置,已安装的应用拥有与浏览器分开的定位权限。', 'map.location.unavailable': '无法确定你的位置。', 'map.location.timeout': '定位耗时过长。请在能看到天空的开阔位置重试。', + 'map.placeNames.show': '显示地名', + 'map.placeNames.hide': '隐藏地名', 'map.overview.show': '显示整个行程', 'map.lock.lock': '锁定地图视图', 'map.lock.unlock': '让地图跟随所选内容',