mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
feat(places): notes, visits, tours, history, tags and location in the place sheet, saved lists on the trip map
Both the desktop sheet and the phone sheet of All places show the place's location as a badge, its notes per list, its visits from trips (hidden without any), linked tours and bookings, its change history and the reader's own tags with a tag filter. A trip map can show the places of linked lists and add one to the trip. All places reloads after a list is added or removed.
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import type {
|
||||
PlaceActivitiesResponse,
|
||||
PlaceActivityCandidatesResponse,
|
||||
PlaceLibraryActivitiesResponse,
|
||||
PlacesLibraryKind,
|
||||
TripPlaceActivityLinkRequest,
|
||||
} from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
const tripBase = (tripId: number, placeId: number) => `/trips/${tripId}/places/${placeId}/activities`;
|
||||
const savedBase = (collectionPlaceId: number) => `/addons/collections/places/${collectionPlaceId}/activities`;
|
||||
|
||||
/**
|
||||
* PLC-18: the bookings and tours a place is about. A trip place links bookings
|
||||
* and tours of its trip, a saved place tours kept in its list; an entry of All
|
||||
* places reads them over every origin it has. Unlinking takes only the link off.
|
||||
*/
|
||||
export const placeActivitiesApi = {
|
||||
tripPlace: (tripId: number, placeId: number, signal?: AbortSignal): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.get(tripBase(tripId, placeId), { signal }).then((r) => r.data),
|
||||
tripCandidates: (tripId: number, placeId: number, signal?: AbortSignal): Promise<PlaceActivityCandidatesResponse> =>
|
||||
apiClient.get(`${tripBase(tripId, placeId)}/candidates`, { signal }).then((r) => r.data),
|
||||
linkTrip: (tripId: number, placeId: number, body: TripPlaceActivityLinkRequest): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.post(tripBase(tripId, placeId), body).then((r) => r.data),
|
||||
unlinkTripBooking: (tripId: number, placeId: number, reservationId: number): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.delete(`${tripBase(tripId, placeId)}/reservations/${reservationId}`).then((r) => r.data),
|
||||
unlinkTripTour: (tripId: number, placeId: number, tourId: number): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.delete(`${tripBase(tripId, placeId)}/tours/${tourId}`).then((r) => r.data),
|
||||
|
||||
savedPlace: (collectionPlaceId: number, signal?: AbortSignal): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.get(savedBase(collectionPlaceId), { signal }).then((r) => r.data),
|
||||
savedCandidates: (collectionPlaceId: number, signal?: AbortSignal): Promise<PlaceActivityCandidatesResponse> =>
|
||||
apiClient.get(`${savedBase(collectionPlaceId)}/candidates`, { signal }).then((r) => r.data),
|
||||
linkSaved: (collectionPlaceId: number, collectionTourId: number): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.post(savedBase(collectionPlaceId), { collection_tour_id: collectionTourId }).then((r) => r.data),
|
||||
unlinkSaved: (collectionPlaceId: number, collectionTourId: number): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.delete(`${savedBase(collectionPlaceId)}/tours/${collectionTourId}`).then((r) => r.data),
|
||||
|
||||
libraryEntry: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlaceLibraryActivitiesResponse> =>
|
||||
apiClient.get(`/addons/collections/library/places/${kind}/${id}/activities`, { signal }).then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { PlaceHistoryPageResponse, PlaceHistoryQueryInput, PlacesLibraryKind } from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
const base = '/addons/collections/library/places';
|
||||
|
||||
/** PLC-14: what changed in the details of an entry of All places, opened from a trip place or a saved place. */
|
||||
export const placeHistoryApi = {
|
||||
history: (
|
||||
kind: PlacesLibraryKind,
|
||||
id: number,
|
||||
query: PlaceHistoryQueryInput = {},
|
||||
signal?: AbortSignal
|
||||
): Promise<PlaceHistoryPageResponse> =>
|
||||
apiClient.get(`${base}/${kind}/${id}/history`, { params: query, signal }).then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import type {
|
||||
CreateTagRequest,
|
||||
PlacesLibraryBulkTagsRequest,
|
||||
PlacesLibraryBulkTagsResponse,
|
||||
PlacesLibraryEntryTagsRequest,
|
||||
PlacesLibraryEntryTagsResponse,
|
||||
Tag,
|
||||
TagListResponse,
|
||||
UpdateTagRequest,
|
||||
} from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
const base = '/addons/collections/library/places/tags';
|
||||
|
||||
/**
|
||||
* PLC-21: the user's personal tags (the ones /tags keeps) and which entries
|
||||
* of All places carry them. Everything here is the user's own and private.
|
||||
*/
|
||||
export const placeTagsApi = {
|
||||
list: (): Promise<TagListResponse> => apiClient.get('/tags').then((r) => r.data),
|
||||
create: (body: CreateTagRequest): Promise<{ tag: Tag }> =>
|
||||
apiClient.post('/tags', body satisfies CreateTagRequest).then((r) => r.data),
|
||||
update: (id: number, body: UpdateTagRequest): Promise<{ tag: Tag }> =>
|
||||
apiClient.put(`/tags/${id}`, body satisfies UpdateTagRequest).then((r) => r.data),
|
||||
remove: (id: number): Promise<{ success: boolean }> => apiClient.delete(`/tags/${id}`).then((r) => r.data),
|
||||
/** The entry carries exactly these tags from now on. */
|
||||
setForEntry: (body: PlacesLibraryEntryTagsRequest): Promise<PlacesLibraryEntryTagsResponse> =>
|
||||
apiClient.put(base, body satisfies PlacesLibraryEntryTagsRequest).then((r) => r.data),
|
||||
/** Puts tags on several entries and takes others off them. */
|
||||
bulk: (body: PlacesLibraryBulkTagsRequest): Promise<PlacesLibraryBulkTagsResponse> =>
|
||||
apiClient.post(`${base}/bulk`, body satisfies PlacesLibraryBulkTagsRequest).then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import type {
|
||||
PlaceMediaResponse,
|
||||
PlacesLibraryKind,
|
||||
PlaceVisitsForPlaceResponse,
|
||||
PlaceVisitsListQuery,
|
||||
PlaceVisitsListResponse,
|
||||
PlaceVisitTripVisitedResponse,
|
||||
} from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
/**
|
||||
* D7/PLC-10, PLC-19, PLC-20, PLC-23: the visits the server reads from the
|
||||
* trips (nothing to write: a visit comes from the trip's plan), the trip
|
||||
* places visited, and the photos and files of an entry of All places.
|
||||
*/
|
||||
export const placeVisitsApi = {
|
||||
list: (query: PlaceVisitsListQuery = {}, signal?: AbortSignal): Promise<PlaceVisitsListResponse> =>
|
||||
apiClient.get('/place-visits', { params: query, signal }).then((r) => r.data),
|
||||
forPlace: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlaceVisitsForPlaceResponse> =>
|
||||
apiClient.get('/place-visits/place', { params: { kind, id }, signal }).then((r) => r.data),
|
||||
tripVisited: (tripId: number, signal?: AbortSignal): Promise<PlaceVisitTripVisitedResponse> =>
|
||||
apiClient.get(`/trips/${tripId}/place-visits/mine`, { signal }).then((r) => r.data),
|
||||
media: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlaceMediaResponse> =>
|
||||
apiClient.get(`/addons/collections/library/places/${kind}/${id}/media`, { signal }).then((r) => r.data),
|
||||
};
|
||||
@@ -8,10 +8,18 @@ import apiClient from './client';
|
||||
|
||||
const base = '/addons/collections/library/places';
|
||||
|
||||
/** The query as the server reads it: a tag filter (PLC-21) as its ids joined by commas, not `tag_ids[]=`. */
|
||||
function queryParams(query: PlacesLibraryQueryInput): Record<string, unknown> {
|
||||
const { tag_ids: tagIds, ...rest } = query;
|
||||
if (tagIds === undefined) return rest;
|
||||
const joined = Array.isArray(tagIds) ? tagIds.join(',') : tagIds;
|
||||
return joined === '' ? rest : { ...rest, tag_ids: joined };
|
||||
}
|
||||
|
||||
/** PLC-07/PLC-08 "All places": one page of entries, and one entry by the trip place or saved place it was opened from. */
|
||||
export const placesLibraryApi = {
|
||||
list: (query: PlacesLibraryQueryInput = {}, signal?: AbortSignal): Promise<PlacesLibraryPageResponse> =>
|
||||
apiClient.get(base, { params: query, signal }).then((r) => r.data),
|
||||
apiClient.get(base, { params: queryParams(query), signal }).then((r) => r.data),
|
||||
detail: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlacesLibraryDetailResponse> =>
|
||||
apiClient.get(`${base}/${kind}/${id}`, { signal }).then((r) => r.data),
|
||||
};
|
||||
|
||||
@@ -53,6 +53,9 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
|
||||
// Linked lists (PLC-15/PLC-16): store/tripCollectionsStore (watchTripCollections) reads the
|
||||
// trip's linked lists and map layer again; content-free because each member's answer differs.
|
||||
'tripCollections:changed',
|
||||
// Place activities (PLC-18): store/placeActivitiesStore (watchPlaceActivities) reads the
|
||||
// bookings and tours of the held trip place, and the All places entries it is an origin of, again.
|
||||
'placeActivities:changed',
|
||||
// components/Roadtrip/useDayBoundaries reloads the shared boundaries.
|
||||
'roadtripBoundary:changed',
|
||||
// In-app notifications: hooks/useInAppNotificationListener, which also keeps
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Check, Shapes } from 'lucide-react';
|
||||
import React, { createElement, useEffect, useRef, useState } from 'react';
|
||||
import type { Category, TranslationFn } from '../../types';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
|
||||
interface CategoryTileMenuProps {
|
||||
categories: Category[];
|
||||
@@ -52,23 +53,24 @@ export default function CategoryTileMenu({
|
||||
|
||||
return (
|
||||
<div className="relative flex-none" ref={ref}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className={`grid place-items-center rounded-[14px] shadow-sm transition-transform hover:scale-[1.03] ${tone ? '' : 'bg-surface-card text-content-muted'}`}
|
||||
// The category's own colour, the one data-driven value of the tile.
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
...(tone ? { background: `color-mix(in srgb, ${tone} 16%, var(--bg-card))`, color: tone } : {}),
|
||||
}}
|
||||
>
|
||||
{createElement(Icon, { size: Math.round(size * 0.43), strokeWidth: 1.9 })}
|
||||
</button>
|
||||
<Tooltip label={label} disabled={open}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
aria-label={label}
|
||||
className={`grid place-items-center rounded-[14px] shadow-sm transition-transform hover:scale-[1.03] ${tone ? '' : 'bg-surface-card text-content-muted'}`}
|
||||
// The category's own colour, the one data-driven value of the tile.
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
...(tone ? { background: `color-mix(in srgb, ${tone} 16%, var(--bg-card))`, color: tone } : {}),
|
||||
}}
|
||||
>
|
||||
{createElement(Icon, { size: Math.round(size * 0.43), strokeWidth: 1.9 })}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{open && (
|
||||
<div
|
||||
role="listbox"
|
||||
|
||||
@@ -126,7 +126,6 @@ export default function CollectionExportMenu({ onExport, exporting, t }: Collect
|
||||
aria-expanded={open}
|
||||
aria-controls={open ? menuId : undefined}
|
||||
aria-label={t('collections.file.export')}
|
||||
title={t('collections.file.exportTitle')}
|
||||
className="col-glass-btn"
|
||||
>
|
||||
{exporting ? <Loader2 size={15} className="animate-spin" /> : <Download size={15} />}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Layers, Tag, CheckSquare, Star, Plus, ArrowDownUp, DownloadCloud } from
|
||||
import type { StatusFilter, CollectionSortMode } from '../../store/collectionStore'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import { getCategoryIcon } from '../shared/categoryIcons'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { STATUS_META, STATUS_ORDER } from '../../pages/collections/collectionsModel'
|
||||
import type { CategoryOption, LabelOption } from '../../pages/collections/collectionsModel'
|
||||
import CollectionLabelFilter from './CollectionLabelFilter'
|
||||
@@ -87,9 +88,11 @@ export default function CollectionFilterBar({
|
||||
return (
|
||||
<div className="col-filterbar">
|
||||
{canAddPlace && (
|
||||
<button type="button" onClick={onAddPlace} className="col-filter-btn col-filter-add" aria-label={t('collections.addPlace')} title={t('collections.addPlace')}>
|
||||
<Plus size={15} />
|
||||
</button>
|
||||
<Tooltip label={t('collections.addPlace')}>
|
||||
<button type="button" onClick={onAddPlace} className="col-filter-btn col-filter-add" aria-label={t('collections.addPlace')}>
|
||||
<Plus size={15} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
<FilterDropdown current={statusFilter} options={statusOpts} onSelect={k => onStatusFilter(k as StatusFilter)} lead={<Layers size={13} />} />
|
||||
{categoryOptions.length > 0 && (
|
||||
@@ -98,27 +101,29 @@ export default function CollectionFilterBar({
|
||||
<FilterDropdown current={ratingFilter} options={ratingOpts} onSelect={k => onRatingFilter(k as number | 'all')} lead={<Star size={13} />} />
|
||||
<FilterDropdown current={sortMode} options={sortOpts} onSelect={k => onSortMode(k as CollectionSortMode)} lead={<ArrowDownUp size={13} />} />
|
||||
{showSelect && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleSelect}
|
||||
className={`col-filter-btn col-filter-icon col-filter-select${selectMode ? ' on' : ''}`}
|
||||
aria-pressed={selectMode}
|
||||
aria-label={t('collections.select')}
|
||||
title={t('collections.select')}
|
||||
>
|
||||
<CheckSquare size={15} />
|
||||
</button>
|
||||
<Tooltip label={t('collections.select')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleSelect}
|
||||
className={`col-filter-btn col-filter-icon col-filter-select${selectMode ? ' on' : ''}`}
|
||||
aria-pressed={selectMode}
|
||||
aria-label={t('collections.select')}
|
||||
>
|
||||
<CheckSquare size={15} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{canImport && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onImport}
|
||||
className="col-filter-btn col-filter-icon"
|
||||
aria-label={t('collections.importFromTrip')}
|
||||
title={t('collections.importFromTrip')}
|
||||
>
|
||||
<DownloadCloud size={15} />
|
||||
</button>
|
||||
<Tooltip label={t('collections.importFromTrip')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onImport}
|
||||
className="col-filter-btn col-filter-icon"
|
||||
aria-label={t('collections.importFromTrip')}
|
||||
>
|
||||
<DownloadCloud size={15} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{showLabels && (labelOptions.length > 0 || canManageLabels) && (
|
||||
<CollectionLabelFilter
|
||||
|
||||
@@ -95,7 +95,7 @@ export default function CollectionHero({
|
||||
<h1 className="col-hero-title">{title}</h1>
|
||||
<div className="col-hero-actions">
|
||||
{canEdit && (
|
||||
<button type="button" onClick={onEdit} aria-label={t('common.edit')} title={t('common.edit')} className="col-glass-btn">
|
||||
<button type="button" onClick={onEdit} aria-label={t('common.edit')} className="col-glass-btn">
|
||||
<Pencil size={15} />
|
||||
<span className="txt">{t('common.edit')}</span>
|
||||
</button>
|
||||
@@ -106,7 +106,6 @@ export default function CollectionHero({
|
||||
type="button"
|
||||
onClick={onShare}
|
||||
aria-label={isOwner ? t('collections.share.button') : t('collections.shared')}
|
||||
title={isOwner ? t('collections.share.button') : t('collections.shared')}
|
||||
className={`col-glass-btn${isOwner && shareMemberCount > 0 ? ' has-count' : ''}`}
|
||||
>
|
||||
{isOwner ? <Share2 size={15} /> : <Users size={15} />}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { Check, ChevronDown, Plus, Settings2, Tags } from 'lucide-react'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import type { LabelOption } from '../../pages/collections/collectionsModel'
|
||||
import type { TranslationFn } from '../../types'
|
||||
|
||||
@@ -108,9 +109,11 @@ export default function CollectionLabelFilter({
|
||||
const toggle = (id: number) => onLabelFilter(labelFilter.includes(id) ? labelFilter.filter(x => x !== id) : [...labelFilter, id])
|
||||
const manageLabel = labelOptions.length ? t('collections.labels.manage') : t('collections.labels.add')
|
||||
const manage = canManageLabels && onManageLabels && (
|
||||
<button type="button" className="col-filter-addlabel" onClick={onManageLabels} title={manageLabel} aria-label={manageLabel}>
|
||||
{labelOptions.length ? <Settings2 size={13} /> : <Plus size={13} />}
|
||||
</button>
|
||||
<Tooltip label={manageLabel}>
|
||||
<button type="button" className="col-filter-addlabel" onClick={onManageLabels} aria-label={manageLabel}>
|
||||
{labelOptions.length ? <Settings2 size={13} /> : <Plus size={13} />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
|
||||
const tray = (
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React from 'react'
|
||||
import { PanelLeftClose, PanelLeftOpen, Search } from 'lucide-react'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import type { CollectionPlace } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import CollectionMap from './CollectionMap'
|
||||
@@ -60,15 +61,16 @@ export default function CollectionMapPanel({
|
||||
{overlay && (
|
||||
<div className="col-map-topbar">
|
||||
<div className="col-map-group">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleView}
|
||||
className="col-map-btn"
|
||||
aria-label={view === 'map' ? t('collections.showList') : t('collections.expandMap')}
|
||||
title={view === 'map' ? t('collections.showList') : t('collections.expandMap')}
|
||||
>
|
||||
{view === 'map' ? <PanelLeftOpen size={17} /> : <PanelLeftClose size={17} />}
|
||||
</button>
|
||||
<Tooltip label={view === 'map' ? t('collections.showList') : t('collections.expandMap')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleView}
|
||||
className="col-map-btn"
|
||||
aria-label={view === 'map' ? t('collections.showList') : t('collections.expandMap')}
|
||||
>
|
||||
{view === 'map' ? <PanelLeftOpen size={17} /> : <PanelLeftClose size={17} />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{showLabels && (
|
||||
<CollectionLabelFilter
|
||||
variant="map"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useRef, useState } from 'react'
|
||||
import PlaceLocationBadge from './PlaceLocationBadge'
|
||||
import { dockStyle, type DockRect } from './detailDock'
|
||||
import Markdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
@@ -141,20 +142,16 @@ export default function CollectionPlaceDetail({
|
||||
{categories.length > 0 && <CategoryTileMenu categories={categories} value={categoryId} onChange={setCategoryId} size={40} t={t} />}
|
||||
<input value={name} onChange={e => setName(e.target.value)} className="col-detail-name-input min-w-0 flex-1" autoFocus aria-label={t('common.name')} />
|
||||
</div>
|
||||
) : <h2 className="col-detail-name">{place.name}</h2>}
|
||||
) : (
|
||||
<>
|
||||
<h2 className="col-detail-name">{place.name}</h2>
|
||||
<PlaceLocationBadge address={place.address} lat={place.lat} lng={place.lng} t={t} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-detail-body">
|
||||
{/* Meta (view only) */}
|
||||
{!editing && place.address && (
|
||||
<div className="col-detail-meta">
|
||||
{place.address && <span className="col-detail-addr"><MapPin size={12} /> {place.address}</span>}
|
||||
{/* Same picker as inside a trip (#1455). A saved place is somewhere
|
||||
you intend to go, and until now the only way to get directions
|
||||
was to add it to a trip first. */}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Status — live for editors, read-only for viewers */}
|
||||
<StatusSegment status={place.status} onSet={canEdit ? onSetStatus : () => {}} t={t} />
|
||||
|
||||
@@ -10,6 +10,8 @@ interface CopyCarryPanelProps {
|
||||
onIncludeNotes: (on: boolean) => void;
|
||||
tagIds: number[];
|
||||
onToggleTag: (id: number) => void;
|
||||
personalTagIds?: number[];
|
||||
onTogglePersonalTag?: (id: number) => void;
|
||||
/** The phone sheet wears the mobile tokens, the desktop dialog the app's. */
|
||||
variant: 'dialog' | 'sheet';
|
||||
t: TranslationFn;
|
||||
@@ -34,6 +36,53 @@ const LOOK = {
|
||||
},
|
||||
} as const;
|
||||
|
||||
type Look = (typeof LOOK)[keyof typeof LOOK];
|
||||
|
||||
/** One group of tags to take along, each a chip in its own colour that turns on when picked. */
|
||||
function TagChoice({
|
||||
title,
|
||||
hint,
|
||||
tags,
|
||||
picked,
|
||||
onToggle,
|
||||
look,
|
||||
}: {
|
||||
title: string;
|
||||
hint: string;
|
||||
tags: { id: number; name: string; color?: string | null }[];
|
||||
picked: number[];
|
||||
onToggle: (id: number) => void;
|
||||
look: Look;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-start gap-3">
|
||||
<Tag size={15} className={`mt-0.5 flex-none ${look.hint}`} aria-hidden="true" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className={`text-body font-semibold ${look.label}`}>{title}</div>
|
||||
<div className={`text-caption ${look.hint}`}>{hint}</div>
|
||||
<div className="mt-2 flex flex-wrap gap-1.5" role="group" aria-label={title}>
|
||||
{tags.map((tag) => {
|
||||
const on = picked.includes(tag.id);
|
||||
return (
|
||||
<button
|
||||
key={tag.id}
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
onClick={() => onToggle(tag.id)}
|
||||
className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-caption font-semibold ${on ? look.chipOn : look.chipOff}`}
|
||||
>
|
||||
{/* The tag's own colour, the one data-driven value here. */}
|
||||
<span className="h-2 w-2 flex-none rounded-full" style={{ background: tag.color || 'var(--accent)' }} />
|
||||
{tag.name}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -45,6 +94,8 @@ export default function CopyCarryPanel({
|
||||
onIncludeNotes,
|
||||
tagIds,
|
||||
onToggleTag,
|
||||
personalTagIds,
|
||||
onTogglePersonalTag,
|
||||
variant,
|
||||
t,
|
||||
}: CopyCarryPanelProps): React.ReactElement {
|
||||
@@ -67,34 +118,24 @@ export default function CopyCarryPanel({
|
||||
</div>
|
||||
)}
|
||||
{options.tags.length > 0 && (
|
||||
<div className="flex items-start gap-3">
|
||||
<Tag size={15} className={`mt-0.5 flex-none ${look.hint}`} aria-hidden="true" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className={`text-body font-semibold ${look.label}`}>{t('collections.copyCarry.tags')}</div>
|
||||
<div className={`text-caption ${look.hint}`}>{t('collections.copyCarry.tagsHint')}</div>
|
||||
<div className="mt-2 flex flex-wrap gap-1.5" role="group" aria-label={t('collections.copyCarry.tags')}>
|
||||
{options.tags.map((tag) => {
|
||||
const on = tagIds.includes(tag.id);
|
||||
return (
|
||||
<button
|
||||
key={tag.id}
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
onClick={() => onToggleTag(tag.id)}
|
||||
className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-caption font-semibold ${on ? look.chipOn : look.chipOff}`}
|
||||
>
|
||||
{/* The tag's own colour, the one data-driven value here. */}
|
||||
<span
|
||||
className="h-2 w-2 flex-none rounded-full"
|
||||
style={{ background: tag.color || 'var(--accent)' }}
|
||||
/>
|
||||
{tag.name}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<TagChoice
|
||||
title={t('collections.copyCarry.tags')}
|
||||
hint={t('collections.copyCarry.tagsHint')}
|
||||
tags={options.tags}
|
||||
picked={tagIds}
|
||||
onToggle={onToggleTag}
|
||||
look={look}
|
||||
/>
|
||||
)}
|
||||
{!!options.personalTags?.length && onTogglePersonalTag && (
|
||||
<TagChoice
|
||||
title={t('collections.copyCarry.personalTags')}
|
||||
hint={t('collections.copyCarry.personalTagsHint')}
|
||||
tags={options.personalTags}
|
||||
picked={personalTagIds ?? []}
|
||||
onToggle={onTogglePersonalTag}
|
||||
look={look}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -26,7 +26,7 @@ interface CopyToTripModalProps {
|
||||
*/
|
||||
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, offersCarry, includeNotes, setIncludeNotes, tagIds, toggleTag } =
|
||||
const { loading, search, setSearch, filtered, busyTripId, dateRange, handleCopy, offersCarry, includeNotes, setIncludeNotes, tagIds, toggleTag, personalTagIds, togglePersonalTag } =
|
||||
useTripCopyPicker({ open: isOpen, onCopy, onClose, t, emptySelection: placeIds.length === 0, carryOptions })
|
||||
|
||||
if (!isOpen) return null
|
||||
@@ -66,7 +66,7 @@ export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, car
|
||||
/>
|
||||
</div>
|
||||
{offersCarry && carryOptions && (
|
||||
<CopyCarryPanel options={carryOptions} includeNotes={includeNotes} onIncludeNotes={setIncludeNotes} tagIds={tagIds} onToggleTag={toggleTag} variant="dialog" t={t} />
|
||||
<CopyCarryPanel options={carryOptions} includeNotes={includeNotes} onIncludeNotes={setIncludeNotes} tagIds={tagIds} onToggleTag={toggleTag} personalTagIds={personalTagIds} onTogglePersonalTag={togglePersonalTag} variant="dialog" t={t} />
|
||||
)}
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-8 text-content-faint">
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { PlacesLibraryTag } from '@trek/shared';
|
||||
import React from 'react';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
|
||||
/**
|
||||
* The reader's own tags on a row of All places (PLC-21): one dot per tag in its
|
||||
* colour behind the name, the names in the tooltip, so the row keeps its two lines.
|
||||
*/
|
||||
export default function EntryTagDots({ tags }: { tags: PlacesLibraryTag[] | undefined }): React.ReactElement | null {
|
||||
if (!tags?.length) return null;
|
||||
return (
|
||||
<Tooltip label={tags.map((tag) => tag.name).join(', ')}>
|
||||
<span
|
||||
className="inline-flex flex-none items-center gap-0.5"
|
||||
role="img"
|
||||
aria-label={tags.map((tag) => tag.name).join(', ')}
|
||||
>
|
||||
{tags.slice(0, 4).map((tag) => (
|
||||
// The tag's own colour, the one data-driven value of the dot.
|
||||
<span key={tag.id} className="h-2 w-2 rounded-full" style={{ background: tag.color || 'var(--accent)' }} />
|
||||
))}
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import type { PlacesLibraryDetailResponse, Tag as TagRow } from '@trek/shared';
|
||||
import { Check, Pencil, Plus, Tag, Trash2, X } from 'lucide-react';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import ConfirmDialog from '../shared/ConfirmDialog';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { useEntryTags } from './useEntryTags';
|
||||
|
||||
type EntryTags = ReturnType<typeof useEntryTags>;
|
||||
|
||||
/** A tag's colour as a dot, the one data-driven value of the chip. */
|
||||
function Dot({ color }: { color: string | null | undefined }) {
|
||||
return <span className="h-2 w-2 flex-none rounded-full" style={{ background: color || 'var(--accent)' }} />;
|
||||
}
|
||||
|
||||
const ROW = 'flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-start text-body hover:bg-surface-secondary';
|
||||
const ICON_BTN =
|
||||
'grid h-6 w-6 flex-none place-items-center rounded-md text-content-muted hover:bg-surface-tertiary hover:text-content';
|
||||
|
||||
/** One tag in the picker: ticked when the place carries it, renamed or deleted in place. */
|
||||
function TagRowItem({ tag, on, tags, t }: { tag: TagRow; on: boolean; tags: EntryTags; t: TranslationFn }) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [name, setName] = useState(String(tag.name));
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
if (editing) {
|
||||
return (
|
||||
<form
|
||||
className="flex items-center gap-1.5 px-1 py-1"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void tags.rename(tag.id, name);
|
||||
setEditing(false);
|
||||
}}
|
||||
>
|
||||
<input
|
||||
autoFocus
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
aria-label={t('placeTags.rename')}
|
||||
className="min-w-0 flex-1 rounded-md border border-edge bg-surface-input px-2 py-1 text-body text-content outline-none"
|
||||
/>
|
||||
<button type="submit" aria-label={t('common.save')} className={ICON_BTN}>
|
||||
<Check size={13} />
|
||||
</button>
|
||||
<button type="button" onClick={() => setEditing(false)} aria-label={t('common.cancel')} className={ICON_BTN}>
|
||||
<X size={13} />
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="group flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
role="menuitemcheckbox"
|
||||
aria-checked={on}
|
||||
onClick={() => void tags.toggle(tag.id)}
|
||||
className={ROW}
|
||||
>
|
||||
<Dot color={tag.color} />
|
||||
<span className="min-w-0 flex-1 truncate text-content">{tag.name}</span>
|
||||
{on && <Check size={14} className="flex-none text-accent" />}
|
||||
</button>
|
||||
<Tooltip label={t('placeTags.rename')}>
|
||||
<button type="button" onClick={() => setEditing(true)} aria-label={t('placeTags.rename')} className={ICON_BTN}>
|
||||
<Pencil size={12} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('placeTags.delete')}>
|
||||
<button type="button" onClick={() => setConfirm(true)} aria-label={t('placeTags.delete')} className={ICON_BTN}>
|
||||
<Trash2 size={12} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<ConfirmDialog
|
||||
isOpen={confirm}
|
||||
onClose={() => setConfirm(false)}
|
||||
onConfirm={() => void tags.destroy(tag.id)}
|
||||
title={t('placeTags.deleteTitle', { name: String(tag.name) })}
|
||||
message={t('placeTags.deleteMessage')}
|
||||
confirmLabel={t('placeTags.delete')}
|
||||
danger
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The reader's own tags on a place of All places in the desktop sheet (PLC-21):
|
||||
* the ones it carries as chips, and a picker to tick others, make a new one from
|
||||
* the search, rename or delete a tag. Only the reader sees them.
|
||||
*/
|
||||
export default function EntryTagsSection({
|
||||
data,
|
||||
onChanged,
|
||||
t,
|
||||
}: {
|
||||
data: PlacesLibraryDetailResponse | null;
|
||||
onChanged: () => void;
|
||||
t: TranslationFn;
|
||||
}): React.ReactElement {
|
||||
const tags = useEntryTags({ entry: data?.entry ?? null, onChanged, t });
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDown = (e: PointerEvent) => {
|
||||
// A dialog over the picker (delete) is outside it but belongs to it.
|
||||
if (
|
||||
ref.current &&
|
||||
!ref.current.contains(e.target as Node) &&
|
||||
!(e.target as Element).closest?.('[role="dialog"]')
|
||||
) {
|
||||
setOpen(false);
|
||||
}
|
||||
};
|
||||
document.addEventListener('pointerdown', onDown);
|
||||
return () => document.removeEventListener('pointerdown', onDown);
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<section className="col-detail-field">
|
||||
<div ref={ref} className="relative flex items-center gap-2">
|
||||
<span className="col-detail-label">
|
||||
<Tag size={12} /> {t('placeTags.title')}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-expanded={open}
|
||||
className="col-detail-action ms-auto"
|
||||
>
|
||||
<Plus size={13} /> {t('placeTags.add')}
|
||||
</button>
|
||||
{open && (
|
||||
<div
|
||||
role="menu"
|
||||
aria-label={t('placeTags.title')}
|
||||
className="absolute end-0 top-[calc(100%+6px)] z-30 w-[280px] rounded-xl border border-edge-faint bg-surface-card p-1.5 shadow-lg"
|
||||
>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (tags.canCreate) void tags.createAndAdd();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
autoFocus
|
||||
value={tags.query}
|
||||
onChange={(e) => tags.setQuery(e.target.value)}
|
||||
placeholder={t('placeTags.search')}
|
||||
aria-label={t('placeTags.search')}
|
||||
className="mb-1 w-full rounded-lg border border-edge bg-surface-input px-2.5 py-1.5 text-body text-content outline-none placeholder:text-content-faint"
|
||||
/>
|
||||
</form>
|
||||
<div className="max-h-[240px] overflow-y-auto">
|
||||
{tags.matches.map((tag) => (
|
||||
<TagRowItem key={tag.id} tag={tag} on={tags.assignedIds.includes(tag.id)} tags={tags} t={t} />
|
||||
))}
|
||||
{tags.matches.length === 0 && !tags.canCreate && (
|
||||
<p className="m-0 px-2 py-2 text-caption text-content-faint">{t('placeTags.none')}</p>
|
||||
)}
|
||||
</div>
|
||||
{tags.canCreate && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void tags.createAndAdd()}
|
||||
disabled={tags.busy}
|
||||
className={`${ROW} mt-1`}
|
||||
>
|
||||
<Plus size={14} className="flex-none text-content-muted" />
|
||||
<span className="min-w-0 flex-1 truncate text-content">
|
||||
{t('placeTags.create', { name: tags.query.trim() })}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{tags.assigned.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{tags.assigned.map((tag) => (
|
||||
<span key={tag.id} className="col-origin-chip">
|
||||
<Dot color={tag.color} />
|
||||
{tag.name}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void tags.toggle(tag.id)}
|
||||
aria-label={t('placeTags.removeFrom', { name: tag.name })}
|
||||
className="-me-1 grid h-4 w-4 place-items-center rounded-full text-content-faint hover:text-content"
|
||||
>
|
||||
<X size={11} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="col-origin-sub m-0">{t('placeTags.private')}</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -49,7 +49,6 @@ export default function FilterDropdown({
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
title={cur.label}
|
||||
>
|
||||
{cur.icon ?? lead}
|
||||
<span className="col-filter-lbl">{cur.label}</span>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { CollectionStatus, PlacesLibraryCounts, PlacesLibrarySort } from '@trek/shared';
|
||||
import type { CollectionStatus, PlacesLibraryCounts, PlacesLibrarySort, Tag as TagRow } from '@trek/shared';
|
||||
import { ArrowDownUp, Bookmark, CopyCheck, Globe2, Layers, Luggage, Tag } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { Category, TranslationFn } from '../../types';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
import { STATUS_META, STATUS_ORDER } from './collectionStatus';
|
||||
import FilterDropdown, { type FilterOption } from './FilterDropdown';
|
||||
import TagFilterDropdown from './TagFilterDropdown';
|
||||
import type { LibraryKindFilter } from './usePlacesLibrary';
|
||||
|
||||
interface LibraryFilterBarProps {
|
||||
@@ -22,6 +23,10 @@ interface LibraryFilterBarProps {
|
||||
duplicates?: number;
|
||||
duplicatesMore?: boolean;
|
||||
onDuplicates?: () => void;
|
||||
/** The reader's own tags (PLC-21) and the ones the list is narrowed to. */
|
||||
tags?: readonly TagRow[];
|
||||
tagIds?: readonly number[];
|
||||
onToggleTag?: (id: number) => void;
|
||||
t: TranslationFn;
|
||||
}
|
||||
|
||||
@@ -44,6 +49,9 @@ export default function LibraryFilterBar({
|
||||
duplicates = 0,
|
||||
duplicatesMore = false,
|
||||
onDuplicates,
|
||||
tags = [],
|
||||
tagIds = [],
|
||||
onToggleTag,
|
||||
t,
|
||||
}: LibraryFilterBarProps): React.ReactElement {
|
||||
const kindOpts: FilterOption[] = [
|
||||
@@ -95,6 +103,7 @@ export default function LibraryFilterBar({
|
||||
lead={<Tag size={13} />}
|
||||
/>
|
||||
)}
|
||||
{onToggleTag && <TagFilterDropdown tags={tags} picked={tagIds} onToggle={onToggleTag} t={t} />}
|
||||
<FilterDropdown
|
||||
current={sort}
|
||||
options={sortOpts}
|
||||
@@ -102,12 +111,7 @@ export default function LibraryFilterBar({
|
||||
lead={<ArrowDownUp size={13} />}
|
||||
/>
|
||||
{duplicates > 0 && onDuplicates && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDuplicates}
|
||||
className="col-filter-btn ms-auto"
|
||||
title={t('collections.duplicates.title')}
|
||||
>
|
||||
<button type="button" onClick={onDuplicates} className="col-filter-btn ms-auto">
|
||||
<CopyCheck size={13} />
|
||||
<span className="col-filter-lbl">
|
||||
{t('collections.duplicates.button', { count: duplicates })}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { PlacesLibraryOrigin } from '@trek/shared';
|
||||
import { Bookmark, Luggage } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { originName } from './originName';
|
||||
|
||||
/** How many origins a row names before it counts the rest. */
|
||||
@@ -28,11 +29,6 @@ export default function LibraryOrigins({
|
||||
<span
|
||||
key={origin.kind === 'trip' ? `t${origin.place_id}` : `l${origin.collection_place_id}`}
|
||||
className="col-origin-pill"
|
||||
title={
|
||||
origin.kind === 'trip'
|
||||
? t('collections.library.fromTrip', { name: originName(origin) })
|
||||
: t('collections.library.fromList', { name: originName(origin) })
|
||||
}
|
||||
>
|
||||
<Icon size={12} className="flex-none" aria-hidden="true" />
|
||||
<span>{originName(origin)}</span>
|
||||
@@ -40,7 +36,9 @@ export default function LibraryOrigins({
|
||||
);
|
||||
})}
|
||||
{rest > 0 && (
|
||||
<span className="col-origin-pill more">{t('collections.library.moreOrigins', { count: rest })}</span>
|
||||
<Tooltip label={ordered.slice(SHOWN).map(originName).join(', ')}>
|
||||
<span className="col-origin-pill more">{t('collections.library.moreOrigins', { count: rest })}</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -7,10 +7,7 @@ import {
|
||||
Hotel,
|
||||
Loader2,
|
||||
Luggage,
|
||||
MapPin,
|
||||
MapPinOff,
|
||||
Navigation,
|
||||
NotebookPen,
|
||||
Star,
|
||||
Ticket,
|
||||
X,
|
||||
@@ -21,7 +18,9 @@ import { entityGradient } from '../../utils/gradients';
|
||||
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
import { NavigationMenu } from '../shared/NavigationMenu';
|
||||
import { STATUS_META } from './collectionStatus';
|
||||
import { dockStyle, type DockRect } from './detailDock';
|
||||
import EntryTagsSection from './EntryTagsSection';
|
||||
import { tripLine } from './libraryDates';
|
||||
import {
|
||||
originPairs,
|
||||
@@ -32,8 +31,15 @@ import {
|
||||
type TripOrigin,
|
||||
type TripPair,
|
||||
} from './libraryPairs';
|
||||
import { listIcon } from './listIcons';
|
||||
import { originName } from './originName';
|
||||
import OriginNotesSection from './OriginNotesSection';
|
||||
import PlaceActivitiesSection from './PlaceActivitiesSection';
|
||||
import PlaceHistorySection from './PlaceHistorySection';
|
||||
import PlaceLocationBadge from './PlaceLocationBadge';
|
||||
import PlaceMediaSection from './PlaceMediaSection';
|
||||
import StatusBadge from './StatusBadge';
|
||||
import VisitsSection from './VisitsSection';
|
||||
|
||||
interface LibraryPlaceDetailProps {
|
||||
data: PlacesLibraryDetailResponse | null;
|
||||
@@ -50,21 +56,11 @@ interface LibraryPlaceDetailProps {
|
||||
onSaveToList: (origin: TripOrigin, detail: TripDetail) => void;
|
||||
/** Copies a saved place into a trip (the list's own copy flow). */
|
||||
onCopyToTrip: (collectionPlaceId: number) => void;
|
||||
/** A note was saved: read the place again. */
|
||||
onNotesSaved: () => void;
|
||||
t: TranslationFn;
|
||||
}
|
||||
|
||||
function Notes({ text, t }: { text: string | null; t: TranslationFn }) {
|
||||
if (!text?.trim()) return null;
|
||||
return (
|
||||
<span className="col-origin-notes">
|
||||
<span className="col-detail-label">
|
||||
<NotebookPen size={11} /> {t('collections.notes')}
|
||||
</span>
|
||||
<span className="txt">{text}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function TripCard({
|
||||
origin,
|
||||
detail,
|
||||
@@ -91,7 +87,11 @@ function TripCard({
|
||||
>
|
||||
<span className="col-origin-head">
|
||||
<span className="col-origin-ico">
|
||||
<Luggage size={15} />
|
||||
{origin.trip_cover ? (
|
||||
<img src={origin.trip_cover} alt="" className="col-origin-cover" />
|
||||
) : (
|
||||
<Luggage size={15} />
|
||||
)}
|
||||
</span>
|
||||
<span className="col-origin-title">
|
||||
<span className="nm">{originName(origin)}</span>
|
||||
@@ -117,7 +117,6 @@ function TripCard({
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<Notes text={detail.notes} t={t} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -126,12 +125,15 @@ function ListCard({
|
||||
origin,
|
||||
detail,
|
||||
entryName,
|
||||
compact,
|
||||
onOpen,
|
||||
t,
|
||||
}: {
|
||||
origin: ListOrigin;
|
||||
detail: ListDetail;
|
||||
entryName: string;
|
||||
/** Beside the trips: the status under the name. */
|
||||
compact: boolean;
|
||||
onOpen: () => void;
|
||||
t: TranslationFn;
|
||||
}) {
|
||||
@@ -144,13 +146,26 @@ function ListCard({
|
||||
aria-label={`${t('collections.library.openList')}: ${originName(origin)}`}
|
||||
>
|
||||
<span className="col-origin-head">
|
||||
<span className="col-origin-ico">
|
||||
<Bookmark size={15} />
|
||||
<span
|
||||
className="col-origin-ico col-origin-ico-list"
|
||||
style={{ ['--list' as string]: origin.collection_color || 'var(--accent)' }}
|
||||
>
|
||||
{createElement(listIcon(origin.collection_icon), { size: 15 })}
|
||||
</span>
|
||||
<span className="col-origin-title">
|
||||
<span className="nm">{originName(origin)}</span>
|
||||
{compact && (
|
||||
<span className="sub inline-flex items-center gap-1">
|
||||
{createElement(STATUS_META[origin.status].icon, {
|
||||
size: 12,
|
||||
strokeWidth: 2.4,
|
||||
style: { color: STATUS_META[origin.status].color },
|
||||
})}
|
||||
{t(STATUS_META[origin.status].labelKey)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<StatusBadge status={origin.status} t={t} />
|
||||
{!compact && <StatusBadge status={origin.status} t={t} />}
|
||||
<ChevronRight size={16} className="col-origin-chev" />
|
||||
</span>
|
||||
{extras && (
|
||||
@@ -178,7 +193,6 @@ function ListCard({
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<Notes text={detail.notes} t={t} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -219,34 +233,17 @@ function DetailCover({
|
||||
{entry && (
|
||||
<div className="col-detail-head">
|
||||
<h2 className="col-detail-name">{entry.name}</h2>
|
||||
<PlaceLocationBadge address={entry.address} lat={entry.lat} lng={entry.lng} t={t} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Where the place is, or that it has no position yet. */
|
||||
function DetailMeta({ entry, t }: { entry: Entry; t: TranslationFn }) {
|
||||
const unplaced = entry.lat == null || entry.lng == null;
|
||||
if (!entry.address && !unplaced) return null;
|
||||
return (
|
||||
<div className="col-detail-meta">
|
||||
{entry.address && (
|
||||
<span className="col-detail-addr">
|
||||
<MapPin size={13} /> {entry.address}
|
||||
</span>
|
||||
)}
|
||||
{unplaced && (
|
||||
<span className="col-detail-addr">
|
||||
<MapPinOff size={13} className="text-warning" /> {t('places.noCoordinates')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The body: where it is, its description, then every trip and every list it sits in. */
|
||||
function DetailBody({
|
||||
data,
|
||||
onNotesSaved,
|
||||
entry,
|
||||
trips,
|
||||
lists,
|
||||
@@ -256,6 +253,8 @@ function DetailBody({
|
||||
onOpenList,
|
||||
t,
|
||||
}: {
|
||||
data: PlacesLibraryDetailResponse | null;
|
||||
onNotesSaved: () => void;
|
||||
entry: Entry;
|
||||
trips: TripPair[];
|
||||
lists: ListPair[];
|
||||
@@ -265,45 +264,55 @@ function DetailBody({
|
||||
onOpenList: (collectionId: number, collectionPlaceId: number) => void;
|
||||
t: TranslationFn;
|
||||
}) {
|
||||
const paired = trips.length > 0 && lists.length > 0;
|
||||
return (
|
||||
<>
|
||||
<DetailMeta entry={entry} t={t} />
|
||||
{description && <div className="col-detail-md whitespace-pre-wrap">{description}</div>}
|
||||
{trips.length > 0 && (
|
||||
<section className="col-detail-field">
|
||||
<div className="col-detail-label">
|
||||
<Luggage size={12} /> {t('collections.library.inTrips')}
|
||||
</div>
|
||||
{trips.map(({ origin, detail }) => (
|
||||
<TripCard
|
||||
key={origin.place_id}
|
||||
origin={origin}
|
||||
detail={detail}
|
||||
entryName={entry.name}
|
||||
language={language}
|
||||
onOpen={() => onOpenTrip(origin.trip_id, origin.place_id)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{lists.length > 0 && (
|
||||
<section className="col-detail-field">
|
||||
<div className="col-detail-label">
|
||||
<Bookmark size={12} /> {t('collections.library.inLists')}
|
||||
</div>
|
||||
{lists.map(({ origin, detail }) => (
|
||||
<ListCard
|
||||
key={origin.collection_place_id}
|
||||
origin={origin}
|
||||
detail={detail}
|
||||
entryName={entry.name}
|
||||
onOpen={() => onOpenList(origin.collection_id, origin.collection_place_id)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{/* Trips and lists side by side when the place is in both, so neither is pushed below the fold. */}
|
||||
<div className={paired ? 'col-origin-pair' : 'contents'}>
|
||||
{trips.length > 0 && (
|
||||
<section className="col-detail-field">
|
||||
<div className="col-detail-label">
|
||||
<Luggage size={12} /> {t('collections.library.inTrips')}
|
||||
</div>
|
||||
{trips.map(({ origin, detail }) => (
|
||||
<TripCard
|
||||
key={origin.place_id}
|
||||
origin={origin}
|
||||
detail={detail}
|
||||
entryName={entry.name}
|
||||
language={language}
|
||||
onOpen={() => onOpenTrip(origin.trip_id, origin.place_id)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{lists.length > 0 && (
|
||||
<section className="col-detail-field">
|
||||
<div className="col-detail-label">
|
||||
<Bookmark size={12} /> {t('collections.library.inLists')}
|
||||
</div>
|
||||
{lists.map(({ origin, detail }) => (
|
||||
<ListCard
|
||||
key={origin.collection_place_id}
|
||||
origin={origin}
|
||||
detail={detail}
|
||||
entryName={entry.name}
|
||||
compact={paired}
|
||||
onOpen={() => onOpenList(origin.collection_id, origin.collection_place_id)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
<EntryTagsSection data={data} onChanged={onNotesSaved} t={t} />
|
||||
<OriginNotesSection data={data} onSaved={onNotesSaved} t={t} />
|
||||
<PlaceMediaSection entry={entry} t={t} />
|
||||
<VisitsSection entry={entry} language={language} t={t} />
|
||||
<PlaceActivitiesSection entry={entry} language={language} t={t} />
|
||||
<PlaceHistorySection entry={entry} language={language} t={t} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -375,6 +384,7 @@ export default function LibraryPlaceDetail({
|
||||
onOpenTrip,
|
||||
onSaveToList,
|
||||
onCopyToTrip,
|
||||
onNotesSaved,
|
||||
t,
|
||||
}: LibraryPlaceDetailProps): React.ReactElement {
|
||||
const entry = data?.entry ?? null;
|
||||
@@ -396,6 +406,8 @@ export default function LibraryPlaceDetail({
|
||||
)}
|
||||
{entry && (
|
||||
<DetailBody
|
||||
data={data}
|
||||
onNotesSaved={onNotesSaved}
|
||||
entry={entry}
|
||||
trips={trips}
|
||||
lists={lists}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { PlacesLibraryDetailResponse } from '@trek/shared';
|
||||
import { Bookmark, Luggage, NotebookPen, Pencil, Plus } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { TEXTAREA } from '../shared/dialogParts';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { useOriginNotes } from './useOriginNotes';
|
||||
|
||||
/**
|
||||
* The notes of a place of All places in the desktop sheet (PLC-17): each trip's
|
||||
* and each list's own, with where it comes from, apart from the description.
|
||||
* The reader edits a note in place where that trip or list lets them.
|
||||
*/
|
||||
export default function OriginNotesSection({
|
||||
data,
|
||||
onSaved,
|
||||
t,
|
||||
}: {
|
||||
data: PlacesLibraryDetailResponse | null;
|
||||
onSaved: () => void;
|
||||
t: TranslationFn;
|
||||
}): React.ReactElement | null {
|
||||
const n = useOriginNotes({ data, onSaved, t });
|
||||
if (n.notes.length === 0 && n.targets.length === 0) return null;
|
||||
return (
|
||||
<section className="col-detail-field">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="col-detail-label">
|
||||
<NotebookPen size={12} /> {t('collections.notes')}
|
||||
</span>
|
||||
{n.targets.length > 0 && (
|
||||
<button type="button" onClick={n.add} className="col-detail-action ms-auto">
|
||||
<Plus size={13} /> {t('placeNotes.add')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{n.choosing && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{n.targets.map((target) => (
|
||||
<button key={target.key} type="button" onClick={() => n.edit(target)} className="col-origin-chip">
|
||||
{target.kind === 'trip' ? <Luggage size={11} /> : <Bookmark size={11} />} {target.source}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{n.notes.map((note) => (
|
||||
<div key={note.key} className="col-origin-notes">
|
||||
<span className="flex items-center gap-1.5 text-caption font-semibold text-content-faint">
|
||||
{note.kind === 'trip' ? <Luggage size={11} /> : <Bookmark size={11} />}
|
||||
<span className="min-w-0 flex-1 truncate">{note.source}</span>
|
||||
{note.canEdit && n.editing !== note.key && (
|
||||
<Tooltip label={t('placeNotes.edit')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => n.edit(note)}
|
||||
aria-label={t('placeNotes.edit')}
|
||||
className="grid h-6 w-6 place-items-center rounded-md text-content-muted hover:bg-surface-secondary hover:text-content"
|
||||
>
|
||||
<Pencil size={12} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</span>
|
||||
{n.editing === note.key ? (
|
||||
<>
|
||||
<textarea
|
||||
rows={4}
|
||||
autoFocus
|
||||
className={TEXTAREA}
|
||||
value={n.draft}
|
||||
onChange={(e) => n.setDraft(e.target.value)}
|
||||
aria-label={t('placeNotes.fieldLabel', { source: note.source })}
|
||||
/>
|
||||
<span className="flex justify-end gap-2">
|
||||
<button type="button" onClick={n.cancel} className="col-detail-action">
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button type="button" onClick={() => void n.save()} disabled={n.busy} className="col-detail-btn">
|
||||
{t('common.save')}
|
||||
</button>
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span dir="auto" className="txt">
|
||||
{note.text}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { PlaceActivity, PlacesLibraryEntry } from '@trek/shared';
|
||||
import { Link2, Plus, Route, Ticket, X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { activityLine } from './placeExtrasText';
|
||||
import { activityHref, usePlaceActivities } from './usePlaceActivities';
|
||||
|
||||
const ICON_BTN =
|
||||
'grid h-7 w-7 flex-none place-items-center rounded-lg text-content-muted hover:bg-surface-secondary hover:text-content disabled:opacity-50';
|
||||
|
||||
function ActivityIcon({ type }: { type: PlaceActivity['type'] }) {
|
||||
return type === 'booking' ? <Ticket size={16} /> : <Route size={16} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tours and bookings of a place of All places in the desktop sheet (PLC-18):
|
||||
* each one opens where it lives, a said link can be taken off again, and "+ Link"
|
||||
* offers the bookings and tours of the trips and lists the reader may link in.
|
||||
* Not there at all while there is nothing linked and nothing to link.
|
||||
*/
|
||||
export default function PlaceActivitiesSection({
|
||||
entry,
|
||||
language,
|
||||
t,
|
||||
}: {
|
||||
entry: PlacesLibraryEntry;
|
||||
language: string;
|
||||
t: TranslationFn;
|
||||
}): React.ReactElement | null {
|
||||
const navigate = useNavigate();
|
||||
const a = usePlaceActivities({ entry, t });
|
||||
if (a.activities.length === 0 && !a.canLink) return null;
|
||||
return (
|
||||
<section className="col-detail-field">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="col-detail-label">
|
||||
<Ticket size={12} /> {t('placeActivities.title')}
|
||||
</span>
|
||||
{a.canLink && !a.picking && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void a.openPicker()}
|
||||
disabled={a.busy}
|
||||
className="col-detail-action ms-auto"
|
||||
>
|
||||
<Plus size={13} /> {t('placeActivities.link')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{a.activities.map((act) => (
|
||||
<div key={`${act.key}:${act.source.kind}`} className="col-origin">
|
||||
<span className="col-origin-head">
|
||||
<span className="col-origin-ico">
|
||||
<ActivityIcon type={act.type} />
|
||||
</span>
|
||||
<button type="button" onClick={() => navigate(activityHref(act))} className="col-origin-title text-start">
|
||||
<span className="nm">{act.title}</span>
|
||||
<span className="sub">{activityLine(act, language, t)}</span>
|
||||
</button>
|
||||
{act.can_unlink ? (
|
||||
<Tooltip label={t('placeActivities.unlink')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void a.unlink(act)}
|
||||
disabled={a.busy}
|
||||
aria-label={t('placeActivities.unlink')}
|
||||
className={ICON_BTN}
|
||||
>
|
||||
<X size={15} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span className="col-origin-tag">{t('placeActivities.atThisPlace')}</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{a.activities.length === 0 && !a.picking && <p className="col-origin-sub m-0">{t('placeActivities.none')}</p>}
|
||||
{a.picking && (
|
||||
<div className="col-origin cursor-default">
|
||||
<span className="flex items-center gap-2 text-caption font-semibold text-content-muted">
|
||||
<Link2 size={13} /> <span className="flex-1">{t('placeActivities.pickTitle')}</span>
|
||||
<button type="button" onClick={a.closePicker} aria-label={t('common.close')} className={ICON_BTN}>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</span>
|
||||
{a.picking.every((g) => g.candidates.length === 0) && (
|
||||
<span className="col-origin-sub">{t('placeActivities.nothingToLink')}</span>
|
||||
)}
|
||||
{a.picking.map((g) =>
|
||||
g.candidates.map((c) => (
|
||||
<button
|
||||
key={`${g.source.origin.kind}:${c.key}`}
|
||||
type="button"
|
||||
disabled={a.busy}
|
||||
onClick={() => void a.link(g.source, c)}
|
||||
className="flex items-center gap-2.5 rounded-lg px-1 py-1.5 text-start hover:bg-surface-secondary disabled:opacity-50"
|
||||
>
|
||||
<span className="grid h-7 w-7 flex-none place-items-center rounded-lg bg-surface-secondary text-content-muted">
|
||||
<ActivityIcon type={c.type} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-body font-semibold text-content">{c.title}</span>
|
||||
<span className="block truncate text-caption text-content-faint">{activityLine(c, language, t)}</span>
|
||||
</span>
|
||||
<Plus size={15} className="flex-none text-content-muted" />
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { PlacesLibraryEntry } from '@trek/shared';
|
||||
import { ArrowRight, Bookmark, History, Luggage } from 'lucide-react';
|
||||
import React, { useState } from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { historyLine, historyMeta } from './placeExtrasText';
|
||||
import { usePlaceHistory } from './usePlaceHistory';
|
||||
|
||||
/** How many changes show before "show all" opens the rest. */
|
||||
const FOLDED = 3;
|
||||
|
||||
/**
|
||||
* The change history of a place of All places in the desktop sheet (PLC-14):
|
||||
* which detail changed from what to what, who changed it and when, with the trip
|
||||
* or list it happened in. The newest few first, the rest on request; not there
|
||||
* at all before the first change.
|
||||
*/
|
||||
export default function PlaceHistorySection({
|
||||
entry,
|
||||
language,
|
||||
t,
|
||||
}: {
|
||||
entry: PlacesLibraryEntry;
|
||||
language: string;
|
||||
t: TranslationFn;
|
||||
}): React.ReactElement | null {
|
||||
const h = usePlaceHistory(entry);
|
||||
const [open, setOpen] = useState(false);
|
||||
if (h.entries.length === 0) return null;
|
||||
const shown = open ? h.entries : h.entries.slice(0, FOLDED);
|
||||
return (
|
||||
<section className="col-detail-field">
|
||||
<div className="col-detail-label">
|
||||
<History size={12} /> {t('placeHistory.title')}
|
||||
</div>
|
||||
<ol className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{shown.map((e) => {
|
||||
const line = historyLine(e, t);
|
||||
return (
|
||||
<li key={e.id} className="flex flex-col gap-0.5 border-s-2 border-edge-faint ps-3">
|
||||
<span className="text-body text-content">
|
||||
<strong className="font-semibold">{line.field}</strong>
|
||||
{(line.from || line.to) && (
|
||||
<span className="text-content-muted">
|
||||
{': '}
|
||||
{line.from && <span className="line-through decoration-content-faint">{line.from}</span>}
|
||||
{line.from && line.to && <ArrowRight size={11} className="mx-1 inline align-[-1px]" />}
|
||||
{line.to && <span className="text-content">{line.to}</span>}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-caption text-content-faint">
|
||||
{e.origin.kind === 'trip' ? <Luggage size={11} /> : <Bookmark size={11} />}
|
||||
{historyMeta(e, t, language)}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
{(open ? h.hasMore : h.entries.length > FOLDED || h.hasMore) && (
|
||||
<button
|
||||
type="button"
|
||||
className="col-detail-action self-start"
|
||||
disabled={h.loadingMore}
|
||||
onClick={() => {
|
||||
if (!open) setOpen(true);
|
||||
else void h.more();
|
||||
}}
|
||||
>
|
||||
{!open ? t('placeHistory.showAll') : t('placeHistory.more')}
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { MapPin, MapPinOff } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import './placeLocation.css';
|
||||
|
||||
/** A position as the badge shows it, five decimals, about a metre. */
|
||||
export function coordsText(lat: number, lng: number): string {
|
||||
return `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a place is, under its name on the cover of every place sheet: the
|
||||
* address, else the coordinates, else that it has no position yet. A place
|
||||
* without a position wears the struck-out pin in the warning colour either way.
|
||||
*/
|
||||
export default function PlaceLocationBadge({
|
||||
address,
|
||||
lat,
|
||||
lng,
|
||||
t,
|
||||
}: {
|
||||
address: string | null | undefined;
|
||||
lat: number | null | undefined;
|
||||
lng: number | null | undefined;
|
||||
t: TranslationFn;
|
||||
}): React.ReactElement {
|
||||
const placed = lat != null && lng != null;
|
||||
const text = address?.trim() || (placed ? coordsText(lat, lng) : t('places.noCoordinates'));
|
||||
return (
|
||||
<span className={placed ? 'place-loc-badge' : 'place-loc-badge unplaced'}>
|
||||
{placed ? <MapPin size={12} /> : <MapPinOff size={12} aria-label={t('places.noCoordinates')} />}
|
||||
<span dir="auto">{text}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { PlacesLibraryEntry } from '@trek/shared';
|
||||
import { FileText, Images } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import PhotoLightbox from '../Journey/PhotoLightbox';
|
||||
import { usePlaceMedia } from './usePlaceMedia';
|
||||
|
||||
/** How many pictures the strip shows before it counts the rest on the last one. */
|
||||
const SHOWN = 8;
|
||||
|
||||
/**
|
||||
* The pictures and the trip files of a place of All places (PLC-19, PLC-20), in
|
||||
* the desktop sheet: a strip of pictures that opens the lightbox, and the files
|
||||
* a trip attached to the place, each naming where it comes from.
|
||||
*/
|
||||
export default function PlaceMediaSection({
|
||||
entry,
|
||||
t,
|
||||
}: {
|
||||
entry: PlacesLibraryEntry;
|
||||
t: TranslationFn;
|
||||
}): React.ReactElement | null {
|
||||
const m = usePlaceMedia(entry);
|
||||
if (m.photos.length === 0 && m.files.length === 0) return null;
|
||||
const rest = m.photos.length - SHOWN;
|
||||
return (
|
||||
<>
|
||||
{m.photos.length > 0 && (
|
||||
<section className="col-detail-field">
|
||||
<div className="col-detail-label">
|
||||
<Images size={12} /> {t('places.media.photos')}
|
||||
</div>
|
||||
<div className="grid grid-cols-4 gap-1.5">
|
||||
{m.photos.slice(0, SHOWN).map((p, i) => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
onClick={() => m.setOpen(i)}
|
||||
className="relative aspect-square overflow-hidden rounded-lg bg-surface-secondary"
|
||||
aria-label={p.caption}
|
||||
>
|
||||
<img src={p.thumbSrc} alt="" loading="lazy" className="h-full w-full object-cover" />
|
||||
{i === SHOWN - 1 && rest > 0 && (
|
||||
<>
|
||||
<span className="absolute inset-0 bg-surface-card opacity-75" />
|
||||
<span className="absolute inset-0 grid place-items-center text-body font-bold text-content">
|
||||
+{rest}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{m.files.length > 0 && (
|
||||
<section className="col-detail-field">
|
||||
<div className="col-detail-label">
|
||||
<FileText size={12} /> {t('places.media.files')}
|
||||
</div>
|
||||
{m.files.map((f) => (
|
||||
<a key={f.file_id} href={f.url} target="_blank" rel="noreferrer" className="col-origin">
|
||||
<span className="col-origin-head">
|
||||
<span className="col-origin-ico">
|
||||
<FileText size={16} />
|
||||
</span>
|
||||
<span className="col-origin-title">
|
||||
<span className="nm">{f.original_name}</span>
|
||||
<span className="sub">{f.trip_title}</span>
|
||||
</span>
|
||||
</span>
|
||||
</a>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{m.open !== null && (
|
||||
<PhotoLightbox
|
||||
photos={m.photos.map((p) => ({
|
||||
id: p.id,
|
||||
src: p.src,
|
||||
thumbSrc: p.thumbSrc,
|
||||
caption: p.caption,
|
||||
provider: p.provider,
|
||||
mediaType: p.mediaType,
|
||||
}))}
|
||||
startIndex={m.open}
|
||||
onClose={m.close}
|
||||
label={entry.name}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -11,14 +11,17 @@ import PlaceAvatar from '../shared/PlaceAvatar';
|
||||
import CategoryBadge from './CategoryBadge';
|
||||
import CollectionMapPanel from './CollectionMapPanel';
|
||||
import CopyToTripModal from './CopyToTripModal';
|
||||
import { detailDock } from './detailDock';
|
||||
import DuplicatesDialog from './DuplicatesDialog';
|
||||
import EntryTagDots from './EntryTagDots';
|
||||
import LibraryFilterBar from './LibraryFilterBar';
|
||||
import LibraryOrigins from './LibraryOrigins';
|
||||
import { libraryCarryOptions, saveDraftOf } from './libraryPairs';
|
||||
import LibraryPlaceDetail from './LibraryPlaceDetail';
|
||||
import { detailDock } from './detailDock';
|
||||
import { saveDraftOf } from './libraryPairs';
|
||||
import { usePersonalTags } from './useEntryTags';
|
||||
import { usePlaceDuplicates } from './usePlaceDuplicates';
|
||||
import { usePlacesLibrary } from './usePlacesLibrary';
|
||||
import VisitedMark from './VisitedMark';
|
||||
|
||||
interface PlacesLibraryViewProps {
|
||||
categories: Category[];
|
||||
@@ -139,6 +142,8 @@ function LibraryRows({
|
||||
<div className="t">
|
||||
{entry.category?.name && <CategoryBadge category={entry.category} />}
|
||||
<span className="nm">{entry.name}</span>
|
||||
<VisitedMark count={entry.visit_count} t={t} />
|
||||
<EntryTagDots tags={entry.tags} />
|
||||
</div>
|
||||
{entry.address && (
|
||||
<div className="s">
|
||||
@@ -184,6 +189,7 @@ export default function PlacesLibraryView({
|
||||
t,
|
||||
}: PlacesLibraryViewProps): React.ReactElement {
|
||||
const lib = usePlacesLibrary({ active: true, t });
|
||||
const personalTags = usePersonalTags();
|
||||
const dup = usePlaceDuplicates({ active: true, onChanged: lib.reload, t });
|
||||
const [showDup, setShowDup] = useState(false);
|
||||
const openSave = useSaveToCollectionStore((s) => s.open);
|
||||
@@ -210,6 +216,9 @@ export default function PlacesLibraryView({
|
||||
duplicates={dup.pairs.length}
|
||||
duplicatesMore={dup.hasMore}
|
||||
onDuplicates={() => setShowDup(true)}
|
||||
tags={personalTags}
|
||||
tagIds={lib.tagIds}
|
||||
onToggleTag={lib.toggleTag}
|
||||
t={t}
|
||||
/>
|
||||
);
|
||||
@@ -279,6 +288,7 @@ export default function PlacesLibraryView({
|
||||
<LibraryPlaceDetail
|
||||
data={lib.detail}
|
||||
loading={lib.detailLoading}
|
||||
onNotesSaved={lib.reload}
|
||||
cover={lib.cover}
|
||||
language={language}
|
||||
anchorRect={anchor}
|
||||
@@ -308,10 +318,16 @@ export default function PlacesLibraryView({
|
||||
|
||||
{copyId != null && (
|
||||
<CopyToTripModal
|
||||
carryOptions={libraryCarryOptions(lib.detail, copyId)}
|
||||
isOpen
|
||||
placeIds={[copyId]}
|
||||
onClose={() => setCopyId(null)}
|
||||
onCopy={(tripId, carry) => copyToTrip(tripId, [copyId], undefined, carry)}
|
||||
onCopy={(tripId, carry) =>
|
||||
copyToTrip(tripId, [copyId], undefined, carry).then((res) => {
|
||||
lib.reload();
|
||||
return res;
|
||||
})
|
||||
}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React from 'react'
|
||||
import type { CollectionStatus } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { STATUS_META, nextStatus } from './collectionStatus'
|
||||
|
||||
interface StatusBadgeProps {
|
||||
@@ -48,7 +49,15 @@ export default function StatusBadge({ status, onChange, showLabel = true, size =
|
||||
const className = `inline-flex items-center gap-1.5 rounded-full text-[11px] leading-none border backdrop-blur-md ${showLabel ? 'px-2.5 py-1' : 'p-1.5'} ${skin}`
|
||||
|
||||
if (!interactive) {
|
||||
return <span className={className} title={label}>{content}</span>
|
||||
// Without its word the badge is only an icon: name it and say it on hover.
|
||||
if (!showLabel) {
|
||||
return (
|
||||
<Tooltip label={label}>
|
||||
<span className={className} role="img" aria-label={label}>{content}</span>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
return <span className={className}>{content}</span>
|
||||
}
|
||||
|
||||
// Rendered as a role=button span (not a native <button type="button">) on purpose: inside
|
||||
@@ -56,16 +65,17 @@ export default function StatusBadge({ status, onChange, showLabel = true, size =
|
||||
// pill's background/border/padding, and the pill also has to sit inside the
|
||||
// grid card's own clickable element without nesting one button in another.
|
||||
return (
|
||||
<Tooltip label={`${label}, ${t('collections.status.cycleHint')}`}>
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={cycle}
|
||||
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') cycle(e) }}
|
||||
title={`${label} — ${t('collections.status.cycleHint')}`}
|
||||
aria-label={label}
|
||||
className={`${className} transition-transform hover:scale-110 active:scale-95 cursor-pointer select-none`}
|
||||
>
|
||||
{content}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { Tag as TagRow } from '@trek/shared';
|
||||
import { Check, ChevronDown, Tag } from 'lucide-react';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
|
||||
/**
|
||||
* The tag filter of All places (PLC-21), shaped like the dropdowns beside it but
|
||||
* with several picks at once: a place shows when it carries any of them. Not drawn
|
||||
* while the reader has no tags.
|
||||
*/
|
||||
export default function TagFilterDropdown({
|
||||
tags,
|
||||
picked,
|
||||
onToggle,
|
||||
t,
|
||||
}: {
|
||||
tags: readonly TagRow[];
|
||||
picked: readonly number[];
|
||||
onToggle: (id: number) => void;
|
||||
t: TranslationFn;
|
||||
}): React.ReactElement | null {
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDoc = (e: MouseEvent) => {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') setOpen(false);
|
||||
};
|
||||
document.addEventListener('mousedown', onDoc);
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', onDoc);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
if (tags.length === 0) return null;
|
||||
const label =
|
||||
picked.length === 0
|
||||
? t('placeTags.filterAll')
|
||||
: picked.length === 1
|
||||
? String(tags.find((tag) => tag.id === picked[0])?.name ?? '')
|
||||
: t('placeTags.filterCount', { count: picked.length });
|
||||
return (
|
||||
<div className="col-filter" ref={ref}>
|
||||
<button
|
||||
type="button"
|
||||
className={['col-filter-btn', open && 'open', picked.length === 0 && 'is-default'].filter(Boolean).join(' ')}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
aria-label={`${t('placeTags.title')}: ${label}`}
|
||||
>
|
||||
<Tag size={13} />
|
||||
<span className="col-filter-lbl">{label}</span>
|
||||
<ChevronDown size={14} className="col-filter-chev" />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="col-filter-pop" role="listbox" aria-multiselectable="true">
|
||||
{tags.map((tag) => {
|
||||
const on = picked.includes(tag.id);
|
||||
return (
|
||||
<button
|
||||
key={tag.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={on}
|
||||
className={['col-filter-opt', on && 'on'].filter(Boolean).join(' ')}
|
||||
onClick={() => onToggle(tag.id)}
|
||||
>
|
||||
{/* The tag's own colour, the one data-driven value of the row. */}
|
||||
<span className="col-filter-dot" style={{ background: tag.color || 'var(--accent)' }} />
|
||||
<span className="col-filter-lbl">{tag.name}</span>
|
||||
{on && <Check size={13} className="col-filter-check" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { ArrowUpRight, Bookmark, Eye, EyeOff, Link2, X } from 'lucide-react';
|
||||
import React, { createElement, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { placesPath } from '../../utils/placesRoutes';
|
||||
import { MapTogglePill } from '../Map/MapTogglePill';
|
||||
import ConfirmDialog from '../shared/ConfirmDialog';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { listIcon } from './listIcons';
|
||||
import type { useTripLists } from './useTripLists';
|
||||
|
||||
type TripLists = ReturnType<typeof useTripLists>;
|
||||
|
||||
/** A list's symbol in its colour, as the rail and the place cards draw it. */
|
||||
function ListTile({ color, icon }: { color?: string | null; icon?: string | null }) {
|
||||
const tone = color || 'var(--accent)';
|
||||
return (
|
||||
<span
|
||||
className="grid h-7 w-7 flex-none place-items-center rounded-lg"
|
||||
// The list's own colour, the one data-driven value of the tile.
|
||||
style={{ background: `color-mix(in srgb, ${tone} 16%, var(--bg-card))`, color: tone }}
|
||||
>
|
||||
{createElement(listIcon(icon), { size: 14 })}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const ICON_BTN =
|
||||
'grid h-7 w-7 flex-none place-items-center rounded-lg text-content-muted hover:bg-surface-secondary hover:text-content disabled:opacity-50';
|
||||
|
||||
/**
|
||||
* The trip map's one way in to the lists a trip draws on (PLC-15, PLC-16): a round
|
||||
* control beside the other map toggles that opens a card with the linked lists,
|
||||
* each shown on the map or not, opened in Places or unlinked, and the reader's
|
||||
* other lists to link. A pin of a shown list asks before it joins the trip.
|
||||
* Nothing is drawn for a reader with no linked list and no right to link one.
|
||||
*/
|
||||
export function TripListsPill({ lists, t }: { lists: TripLists; t: TranslationFn }): React.ReactElement | null {
|
||||
const navigate = useNavigate();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [picking, setPicking] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDown = (e: PointerEvent) => {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') setOpen(false);
|
||||
};
|
||||
document.addEventListener('pointerdown', onDown);
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', onDown);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
if (lists.links.length === 0 && !lists.canLink) return null;
|
||||
|
||||
return (
|
||||
<div ref={ref} className="relative" style={{ pointerEvents: 'auto' }}>
|
||||
<MapTogglePill
|
||||
active={lists.visible.length > 0}
|
||||
onToggle={() => {
|
||||
setOpen((o) => !o);
|
||||
setPicking(false);
|
||||
}}
|
||||
label={t('tripLists.title')}
|
||||
badge={lists.visible.length}
|
||||
opensDialog
|
||||
testId="trip-lists-pill"
|
||||
icon={<Bookmark size={17} strokeWidth={2} />}
|
||||
/>
|
||||
{open && (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-label={t('tripLists.title')}
|
||||
className="absolute bottom-[calc(100%+8px)] end-0 z-30 w-[300px] rounded-2xl border border-edge-faint bg-surface-card p-2 shadow-lg"
|
||||
>
|
||||
<div className="px-2 pb-1.5 pt-1 text-caption font-semibold text-content-muted">{t('tripLists.title')}</div>
|
||||
{lists.links.length === 0 && (
|
||||
<p className="m-0 px-2 pb-2 text-caption text-content-faint">{t('tripLists.none')}</p>
|
||||
)}
|
||||
{lists.links.map((l) => {
|
||||
const on = lists.visible.includes(l.collection_id);
|
||||
const look = lists.lookOf.get(l.collection_id);
|
||||
return (
|
||||
<div
|
||||
key={l.collection_id}
|
||||
className="flex items-center gap-2 rounded-xl px-1.5 py-1.5 hover:bg-surface-secondary"
|
||||
>
|
||||
<ListTile color={look?.color ?? l.color} icon={look?.icon} />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-body font-semibold text-content">{l.name}</span>
|
||||
<span className="block text-caption text-content-faint">
|
||||
{t('tripLists.places', { count: l.place_count })}
|
||||
</span>
|
||||
</span>
|
||||
<Tooltip label={t(on ? 'tripLists.hide' : 'tripLists.show')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => lists.toggle(l.collection_id)}
|
||||
aria-pressed={on}
|
||||
aria-label={t(on ? 'tripLists.hide' : 'tripLists.show')}
|
||||
className={on ? `${ICON_BTN} text-accent` : ICON_BTN}
|
||||
>
|
||||
{on ? <Eye size={15} /> : <EyeOff size={15} />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('tripLists.open')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate(placesPath(l.collection_id))}
|
||||
aria-label={t('tripLists.open')}
|
||||
className={ICON_BTN}
|
||||
>
|
||||
<ArrowUpRight size={15} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{lists.canLink && (
|
||||
<Tooltip label={t('tripLists.unlink')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void lists.unlink(l.collection_id)}
|
||||
disabled={lists.busy}
|
||||
aria-label={t('tripLists.unlink')}
|
||||
className={ICON_BTN}
|
||||
>
|
||||
<X size={15} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{lists.canLink && !picking && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
lists.loadLinkable();
|
||||
setPicking(true);
|
||||
}}
|
||||
className="mt-1 flex w-full items-center gap-2 rounded-xl px-2 py-2 text-start text-body font-semibold text-content-muted hover:bg-surface-secondary hover:text-content"
|
||||
>
|
||||
<Link2 size={15} /> {t('tripLists.link')}
|
||||
</button>
|
||||
)}
|
||||
{picking && (
|
||||
<div className="mt-1 border-t border-edge-faint pt-1">
|
||||
{lists.linkable.length === 0 && (
|
||||
<p className="m-0 px-2 py-2 text-caption text-content-faint">{t('tripLists.nothingToLink')}</p>
|
||||
)}
|
||||
<div className="max-h-[220px] overflow-y-auto">
|
||||
{lists.linkable.map((c) => (
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
disabled={lists.busy}
|
||||
onClick={() => {
|
||||
void lists.link(c.id);
|
||||
setPicking(false);
|
||||
}}
|
||||
className="flex w-full items-center gap-2 rounded-xl px-1.5 py-1.5 text-start hover:bg-surface-secondary disabled:opacity-50"
|
||||
>
|
||||
<ListTile color={c.color} icon={c.icon} />
|
||||
<span className="min-w-0 flex-1 truncate text-body text-content">{c.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<ConfirmDialog
|
||||
isOpen={lists.pending !== null}
|
||||
onClose={lists.cancelPending}
|
||||
onConfirm={() => void lists.addPending()}
|
||||
title={t('tripLists.addTitle')}
|
||||
message={t('tripLists.addMessage', { name: lists.pending?.name ?? '' })}
|
||||
confirmLabel={t('tripLists.add')}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { CalendarCheck } from 'lucide-react';
|
||||
import React, { useMemo } from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { BOX } from '../Planner/bookings/bookingParts';
|
||||
import { visitDate } from './libraryDates';
|
||||
import { tripPlaceEntry, usePlaceVisits } from './usePlaceVisits';
|
||||
|
||||
/**
|
||||
* A trip place's visits in the planner: how often and when last the reader was
|
||||
* there, from this and every other trip it was planned in on a day that has
|
||||
* passed. Not shown before the first visit.
|
||||
*/
|
||||
export default function TripPlaceVisits({
|
||||
trip,
|
||||
place,
|
||||
language,
|
||||
t,
|
||||
}: {
|
||||
trip: { id: number; title: string; start_date?: string | null; end_date?: string | null };
|
||||
place: { id: number; name: string; address?: string | null; lat?: number | null; lng?: number | null };
|
||||
language: string;
|
||||
t: TranslationFn;
|
||||
}): React.ReactElement | null {
|
||||
const entry = useMemo(() => tripPlaceEntry(trip, place), [trip, place]);
|
||||
const v = usePlaceVisits({ entry });
|
||||
const last = visitDate(v.lastVisit, null, language);
|
||||
if (v.count === 0 || !last) return null;
|
||||
return (
|
||||
<div className={`${BOX} flex flex-none items-center gap-2.5 px-3 py-2`}>
|
||||
<CalendarCheck size={15} className="flex-none text-success" />
|
||||
<span className="min-w-0 flex-1 truncate text-body text-content-secondary">
|
||||
{t('visits.summary', { count: v.count, date: last })}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { CircleCheck } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
|
||||
/**
|
||||
* That the reader has been to a place, behind its name in All places (PLC-10):
|
||||
* a green tick, with the number of visits once there are more than one.
|
||||
*/
|
||||
export default function VisitedMark({
|
||||
count,
|
||||
t,
|
||||
}: {
|
||||
count: number | undefined;
|
||||
t: TranslationFn;
|
||||
}): React.ReactElement | null {
|
||||
if (!count) return null;
|
||||
const label = t('visits.visitedTimes', { count });
|
||||
return (
|
||||
<Tooltip label={label}>
|
||||
<span
|
||||
className="inline-flex flex-none items-center gap-0.5 text-caption font-bold text-success"
|
||||
role="img"
|
||||
aria-label={label}
|
||||
>
|
||||
<CircleCheck size={13} strokeWidth={2.4} />
|
||||
{count > 1 && <span>{count}</span>}
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { PlacesLibraryEntry, PlaceVisit } from '@trek/shared';
|
||||
import { CalendarCheck } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { Avatar } from '../Planner/TravelerPicker';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { visitDate } from './libraryDates';
|
||||
import { usePlaceVisits } from './usePlaceVisits';
|
||||
|
||||
/** One visit as a card like the trips and lists above it: the day, the trip and who was there. */
|
||||
function VisitCard({ visit, language }: { visit: PlaceVisit; language: string }) {
|
||||
const names = visit.participants.map((p) => p.username).join(', ');
|
||||
return (
|
||||
<div className="col-origin cursor-default">
|
||||
<span className="col-origin-head">
|
||||
<span className="col-origin-ico">
|
||||
<CalendarCheck size={16} />
|
||||
</span>
|
||||
<span className="col-origin-title">
|
||||
<span className="nm">{visitDate(visit.visited_on, visit.visited_time, language)}</span>
|
||||
<span className="sub">{visit.trip.title}</span>
|
||||
</span>
|
||||
{visit.participants.length > 1 && (
|
||||
<Tooltip label={names}>
|
||||
<span className="flex flex-none">
|
||||
{visit.participants.slice(0, 4).map((p, i) => (
|
||||
<span key={p.id} className={i ? '-ms-1.5 flex rounded-full ring-2 ring-surface-secondary' : 'flex'}>
|
||||
<Avatar userId={p.id} username={p.username} avatarUrl={p.avatar_url} size={20} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* When the reader was at a place of All places (PLC-10): every past day of a
|
||||
* trip it was planned on, newest first. Nothing to enter; without visits the
|
||||
* section is not there at all.
|
||||
*/
|
||||
export default function VisitsSection({
|
||||
entry,
|
||||
language,
|
||||
t,
|
||||
}: {
|
||||
entry: PlacesLibraryEntry;
|
||||
language: string;
|
||||
t: TranslationFn;
|
||||
}): React.ReactElement | null {
|
||||
const v = usePlaceVisits({ entry });
|
||||
const last = visitDate(v.lastVisit, null, language);
|
||||
if (v.count === 0 || !last) return null;
|
||||
return (
|
||||
<section className="col-detail-field">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="col-detail-label">
|
||||
<CalendarCheck size={12} /> {t('visits.title')}
|
||||
</span>
|
||||
<span className="col-origin-sub ms-auto">{t('visits.summary', { count: v.count, date: last })}</span>
|
||||
</div>
|
||||
{v.visits.map((visit) => (
|
||||
<VisitCard key={`${visit.trip.id}:${visit.day_id}:${visit.place_id}`} visit={visit} language={language} />
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -54,3 +54,15 @@ export function tripLine(
|
||||
? `${first} ${t('collections.library.moreOrigins', { count: detail.days.length - 1 })}`
|
||||
: first;
|
||||
}
|
||||
|
||||
/** When a visit was, with its year, since a history reaches back over years: "Wed, 2 Dec 2026, 14:30". */
|
||||
export function visitDate(
|
||||
date: string | null | undefined,
|
||||
time: string | null | undefined,
|
||||
language: string
|
||||
): string | null {
|
||||
const d = asDate(date);
|
||||
if (!d) return null;
|
||||
const day = new Intl.DateTimeFormat(language, { ...SHORT, weekday: 'short', year: 'numeric' }).format(d);
|
||||
return time ? `${day}, ${time}` : day;
|
||||
}
|
||||
|
||||
@@ -44,3 +44,18 @@ export function saveDraftOf(origin: TripOrigin, detail: TripDetail, categoryId:
|
||||
phone: info.phone,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What a saved place of an entry may take along into a trip: its notes in the
|
||||
* list, the list's labels on it, and the reader's own tags on the entry (PLC-21).
|
||||
* Nothing of it goes unless picked in the copy dialog.
|
||||
*/
|
||||
export function libraryCarryOptions(data: PlacesLibraryDetailResponse | null, collectionPlaceId: number | null) {
|
||||
if (!data || collectionPlaceId == null) return undefined;
|
||||
const pair = originPairs(data).lists.find((p) => p.origin.collection_place_id === collectionPlaceId);
|
||||
return {
|
||||
hasNotes: !!pair?.detail.notes?.trim(),
|
||||
tags: (pair?.detail.labels ?? []).map((l) => ({ id: l.id, name: l.name, color: l.color })),
|
||||
personalTags: (data.entry.tags ?? []).map((tag) => ({ id: tag.id, name: tag.name, color: tag.color })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { PlaceActivity, PlaceActivityCandidate, PlaceHistoryEntry } from '@trek/shared';
|
||||
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { dayDate } from './libraryDates';
|
||||
|
||||
/** The words for one changed detail: which detail, and the old and the new value as the reader reads them. */
|
||||
export function historyLine(
|
||||
entry: PlaceHistoryEntry,
|
||||
t: TranslationFn
|
||||
): { field: string; from: string | null; to: string | null } {
|
||||
const field = t(`placeHistory.field.${entry.field}`);
|
||||
// A picture or the opening hours say nothing as text: only that they changed.
|
||||
if (entry.field === 'image' || entry.field === 'opening_hours') return { field, from: null, to: null };
|
||||
if (entry.field === 'status') {
|
||||
const word = (v: string | null) => (v ? t(`collections.status.${v}`) : null);
|
||||
return { field, from: word(entry.old_value), to: word(entry.new_value) };
|
||||
}
|
||||
return { field, from: entry.old_value, to: entry.new_value };
|
||||
}
|
||||
|
||||
/** Who changed it: the person, TREK itself, or someone whose account is gone. */
|
||||
export function historyEditor(entry: PlaceHistoryEntry, t: TranslationFn): string {
|
||||
if (entry.automatic) return t('placeHistory.automatic');
|
||||
return entry.editor?.username ?? t('placeHistory.formerMember');
|
||||
}
|
||||
|
||||
/** When it changed, as a short date and time in the reader's language. */
|
||||
export function historyWhen(entry: PlaceHistoryEntry, language: string): string {
|
||||
if (!entry.changed_at) return '';
|
||||
const d = new Date(`${entry.changed_at.replace(' ', 'T')}${entry.changed_at.endsWith('Z') ? '' : 'Z'}`);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
return new Intl.DateTimeFormat(language, {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(d);
|
||||
}
|
||||
|
||||
/** The second line of a tour or booking: where it lives and when it is. */
|
||||
export function activityLine(
|
||||
activity: PlaceActivity | PlaceActivityCandidate,
|
||||
language: string,
|
||||
t: TranslationFn
|
||||
): string {
|
||||
const where = activity.origin.kind === 'trip' ? activity.origin.trip_title : activity.origin.collection_name;
|
||||
const day = activity.date ? dayDate(activity.date, language) : null;
|
||||
const when = day ?? (activity.day_number != null ? t('collections.library.day', { day: activity.day_number }) : null);
|
||||
const kind = activity.type === 'booking' ? t('placeActivities.booking') : t('placeActivities.tour');
|
||||
return [kind, where, when].filter(Boolean).join(', ');
|
||||
}
|
||||
|
||||
/** The line under a change: where, who and when, leaving out what is not known. */
|
||||
export function historyMeta(entry: PlaceHistoryEntry, t: TranslationFn, language: string): string {
|
||||
const where = entry.origin.kind === 'trip' ? entry.origin.trip_title : entry.origin.collection_name;
|
||||
return [where, historyEditor(entry, t), historyWhen(entry, language)].filter(Boolean).join(', ');
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/* Where a place is, as a glass pill under its name on the sheet's cover photo. */
|
||||
.place-loc-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
max-width: 100%;
|
||||
margin-top: 6px;
|
||||
padding: 3px 10px;
|
||||
border-radius: 999px;
|
||||
background: rgba(0, 0, 0, 0.38);
|
||||
-webkit-backdrop-filter: blur(8px);
|
||||
backdrop-filter: blur(8px);
|
||||
color: rgba(255, 255, 255, 0.94);
|
||||
font-size: calc(12px * var(--fs-scale-caption, 1));
|
||||
font-weight: 500;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.place-loc-badge > span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.place-loc-badge > svg {
|
||||
flex: none;
|
||||
}
|
||||
.place-loc-badge.unplaced > svg {
|
||||
color: var(--warning);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { PlacesLibraryEntry, Tag } from '@trek/shared';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { subscribePlaceTags, usePlaceTagsStore } from '../../store/placeTagsStore';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
/** The reader's tags, read once and kept current from other tabs and devices. */
|
||||
export function usePersonalTags(): Tag[] {
|
||||
const tags = usePlaceTagsStore((s) => s.tags);
|
||||
const loaded = usePlaceTagsStore((s) => s.loaded);
|
||||
const load = usePlaceTagsStore((s) => s.load);
|
||||
useEffect(() => subscribePlaceTags(), []);
|
||||
useEffect(() => {
|
||||
if (loaded) return;
|
||||
load().catch(() => {
|
||||
// Offline: no tags to offer, which is what a filter without tags looks like.
|
||||
return undefined;
|
||||
});
|
||||
}, [loaded, load]);
|
||||
return tags;
|
||||
}
|
||||
|
||||
/** Tags whose name holds the trimmed, case-folded query; all of them for an empty one. */
|
||||
export function matchTags(tags: readonly Tag[], query: string): Tag[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
return q ? tags.filter((tag) => String(tag.name).toLowerCase().includes(q)) : [...tags];
|
||||
}
|
||||
|
||||
/**
|
||||
* The reader's own tags on one place of All places (PLC-21), for the desktop and
|
||||
* the phone sheet: which it carries, putting one on or taking it off, a new tag
|
||||
* typed into the search, and renaming or deleting a tag everywhere. Private: no
|
||||
* one else sees them, and none goes into a trip unless picked when copying.
|
||||
*/
|
||||
export function useEntryTags({
|
||||
entry,
|
||||
onChanged,
|
||||
t,
|
||||
}: {
|
||||
entry: PlacesLibraryEntry | null;
|
||||
onChanged: () => void;
|
||||
t: TranslationFn;
|
||||
}) {
|
||||
const toast = useToast();
|
||||
const all = usePersonalTags();
|
||||
const setForEntry = usePlaceTagsStore((s) => s.setForEntry);
|
||||
const create = usePlaceTagsStore((s) => s.create);
|
||||
const update = usePlaceTagsStore((s) => s.update);
|
||||
const remove = usePlaceTagsStore((s) => s.remove);
|
||||
const [query, setQuery] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const assigned = useMemo(() => entry?.tags ?? [], [entry]);
|
||||
const assignedIds = useMemo(() => assigned.map((tag) => tag.id), [assigned]);
|
||||
const matches = useMemo(() => matchTags(all, query), [all, query]);
|
||||
const trimmed = query.trim();
|
||||
const canCreate = trimmed !== '' && !all.some((tag) => String(tag.name).toLowerCase() === trimmed.toLowerCase());
|
||||
|
||||
const run = async (action: () => Promise<unknown>) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await action();
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggle = (tagId: number) =>
|
||||
run(async () => {
|
||||
if (!entry) return;
|
||||
const next = assignedIds.includes(tagId) ? assignedIds.filter((id) => id !== tagId) : [...assignedIds, tagId];
|
||||
await setForEntry(entry.key, next);
|
||||
});
|
||||
|
||||
/** The typed name as a new tag, put straight on the place. */
|
||||
const createAndAdd = () =>
|
||||
run(async () => {
|
||||
if (!entry || !trimmed) return;
|
||||
const tag = await create(trimmed);
|
||||
setQuery('');
|
||||
if (!assignedIds.includes(tag.id)) await setForEntry(entry.key, [...assignedIds, tag.id]);
|
||||
});
|
||||
|
||||
const rename = (tagId: number, name: string) => {
|
||||
const next = name.trim();
|
||||
// An emptied name keeps the old one; nothing changed, so nothing reloads.
|
||||
if (!next) return Promise.resolve();
|
||||
return run(() => update(tagId, { name: next }));
|
||||
};
|
||||
const destroy = (tagId: number) => run(() => remove(tagId));
|
||||
|
||||
return {
|
||||
all,
|
||||
assigned,
|
||||
assignedIds,
|
||||
query,
|
||||
setQuery,
|
||||
matches,
|
||||
canCreate,
|
||||
toggle,
|
||||
createAndAdd,
|
||||
rename,
|
||||
destroy,
|
||||
busy,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { PlacesLibraryDetailResponse } from '@trek/shared';
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { originPairs } from './libraryPairs';
|
||||
import { originName } from './originName';
|
||||
|
||||
/** One place's notes as one trip or one list keeps them, and whether the reader may change them. */
|
||||
export interface OriginNote {
|
||||
key: string;
|
||||
kind: 'trip' | 'list';
|
||||
/** The trip's title or the list's name. */
|
||||
source: string;
|
||||
text: string;
|
||||
canEdit: boolean;
|
||||
save: (notes: string | null) => Promise<void>;
|
||||
}
|
||||
|
||||
/** Every origin's notes, the trips first, and the empty ones only where the reader could write some. */
|
||||
export function notesOf(data: PlacesLibraryDetailResponse | null): OriginNote[] {
|
||||
const { trips, lists } = originPairs(data);
|
||||
const out: OriginNote[] = [];
|
||||
for (const { origin, detail } of trips) {
|
||||
out.push({
|
||||
key: `trip:${origin.place_id}`,
|
||||
kind: 'trip',
|
||||
source: originName(origin),
|
||||
text: detail.notes ?? '',
|
||||
canEdit: origin.can_edit,
|
||||
save: (notes) =>
|
||||
placesLibraryRepo.saveNotes({ kind: 'trip', trip_id: origin.trip_id, place_id: origin.place_id }, notes),
|
||||
});
|
||||
}
|
||||
for (const { origin, detail } of lists) {
|
||||
out.push({
|
||||
key: `list:${origin.collection_place_id}`,
|
||||
kind: 'list',
|
||||
source: originName(origin),
|
||||
text: detail.notes ?? '',
|
||||
canEdit: origin.can_edit,
|
||||
save: (notes) =>
|
||||
placesLibraryRepo.saveNotes({ kind: 'list', collection_place_id: origin.collection_place_id }, notes),
|
||||
});
|
||||
}
|
||||
return out.filter((n) => n.text.trim() || n.canEdit);
|
||||
}
|
||||
|
||||
/**
|
||||
* The notes of a place of All places (PLC-17), for the desktop and the phone
|
||||
* sheet: what each trip and each list keeps, apart from the place's description,
|
||||
* each written where it lives and only where the reader may write. Saving reads
|
||||
* the place again so the sheet shows what was stored.
|
||||
*/
|
||||
export function useOriginNotes({
|
||||
data,
|
||||
onSaved,
|
||||
t,
|
||||
}: {
|
||||
data: PlacesLibraryDetailResponse | null;
|
||||
onSaved: () => void;
|
||||
t: TranslationFn;
|
||||
}) {
|
||||
const toast = useToast();
|
||||
const all = useMemo(() => notesOf(data), [data]);
|
||||
const [editing, setEditing] = useState<string | null>(null);
|
||||
const [choosing, setChoosing] = useState(false);
|
||||
// What shows: the notes there are, and the one being written.
|
||||
const notes = all.filter((n) => n.text.trim() || n.key === editing);
|
||||
// Where a new note could go: the trips and lists the reader may write to that have none yet.
|
||||
const targets = all.filter((n) => n.canEdit && !n.text.trim() && n.key !== editing);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const edit = (note: OriginNote) => {
|
||||
setChoosing(false);
|
||||
setEditing(note.key);
|
||||
setDraft(note.text);
|
||||
};
|
||||
const cancel = () => setEditing(null);
|
||||
/** "+ Note": straight into the one place it can go, or ask where. */
|
||||
const add = () => {
|
||||
if (targets.length === 1) edit(targets[0]);
|
||||
else setChoosing((c) => !c);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
const note = all.find((n) => n.key === editing);
|
||||
if (!note || busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await note.save(draft.trim() ? draft : null);
|
||||
setEditing(null);
|
||||
onSaved();
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { notes, targets, choosing, add, editing, draft, setDraft, busy, edit, cancel, save };
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import type {
|
||||
PlaceActivity,
|
||||
PlaceActivityCandidate,
|
||||
PlaceLibraryActivitiesResponse,
|
||||
PlacesLibraryEntry,
|
||||
PlacesLibraryKind,
|
||||
} from '@trek/shared';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
import { placeActivitiesRepo } from '../../repo/placeActivitiesRepo';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { placesPath } from '../../utils/placesRoutes';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
type Source = PlaceLibraryActivitiesResponse['sources'][number];
|
||||
|
||||
/** The open entry's first origin, which the activities route reads through like the detail route. */
|
||||
function originKey(entry: PlacesLibraryEntry | null): string | null {
|
||||
const o = entry?.origins[0];
|
||||
if (!o) return null;
|
||||
return o.kind === 'trip' ? `trip:${o.place_id}` : `list:${o.collection_place_id}`;
|
||||
}
|
||||
|
||||
/** Where an activity opens: its booking or tour in the trip, or the list the tour is kept in. */
|
||||
export function activityHref(activity: Pick<PlaceActivity, 'target'>): string {
|
||||
const t = activity.target;
|
||||
if (t.kind === 'reservation') return `/trips/${t.trip_id}?booking=${t.reservation_id}`;
|
||||
if (t.kind === 'tour') return `/trips/${t.trip_id}?tour=${t.tour_id}`;
|
||||
return placesPath(t.collection_id);
|
||||
}
|
||||
|
||||
/** A source's candidates with the source they would be linked to. */
|
||||
export interface SourceCandidates {
|
||||
source: Source;
|
||||
candidates: PlaceActivityCandidate[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The tours and bookings of a place of All places (PLC-18), for the desktop and
|
||||
* the phone sheet: what is linked to it in each trip and list the reader can open
|
||||
* (said ones and the ones that already point at the place), opening one where it
|
||||
* lives, linking another of the same trip or list, and taking a link off again.
|
||||
* Who may link follows the trip's or the list's own rights.
|
||||
*/
|
||||
export function usePlaceActivities({ entry, t }: { entry: PlacesLibraryEntry | null; t: TranslationFn }) {
|
||||
const toast = useToast();
|
||||
const key = originKey(entry);
|
||||
const [data, setData] = useState<{ key: string; res: PlaceLibraryActivitiesResponse } | null>(null);
|
||||
const [seq, setSeq] = useState(0);
|
||||
const [picking, setPicking] = useState<SourceCandidates[] | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!key) return;
|
||||
const [kind, id] = key.split(':');
|
||||
const ctrl = new AbortController();
|
||||
placeActivitiesRepo
|
||||
.libraryEntry(kind as PlacesLibraryKind, Number(id), ctrl.signal)
|
||||
.then((res) => {
|
||||
if (!ctrl.signal.aborted) setData({ key, res });
|
||||
})
|
||||
// Nothing to show is what a failed read looks like too.
|
||||
.catch(() => {
|
||||
if (!ctrl.signal.aborted) setData({ key, res: { activities: [], sources: [] } });
|
||||
});
|
||||
return () => ctrl.abort();
|
||||
}, [key, seq]);
|
||||
|
||||
const current = data && data.key === key ? data.res : null;
|
||||
const linkable = (current?.sources ?? []).filter((s) => s.can_link);
|
||||
const reload = useCallback(() => setSeq((n) => n + 1), []);
|
||||
|
||||
const run = async (action: () => Promise<unknown>) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await action();
|
||||
reload();
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** Reads what could be linked, for every trip and list the reader may link in. */
|
||||
const openPicker = () =>
|
||||
run(async () => {
|
||||
const lists = await Promise.all(
|
||||
linkable.map(async (s) => {
|
||||
const res =
|
||||
s.source.kind === 'trip'
|
||||
? await placeActivitiesRepo.tripCandidates(s.source.trip_id, s.source.place_id)
|
||||
: await placeActivitiesRepo.savedCandidates(s.source.collection_place_id);
|
||||
return { source: s, candidates: res.candidates };
|
||||
})
|
||||
);
|
||||
setPicking(lists);
|
||||
});
|
||||
|
||||
const link = (source: Source, candidate: PlaceActivityCandidate) =>
|
||||
run(async () => {
|
||||
const target = candidate.target;
|
||||
if (source.source.kind === 'trip') {
|
||||
// A trip place takes the trip's bookings and tours; a list's tour never reaches it.
|
||||
if (target.kind === 'reservation') {
|
||||
await placeActivitiesRepo.linkTrip(source.source.trip_id, source.source.place_id, {
|
||||
reservation_id: target.reservation_id,
|
||||
});
|
||||
} else if (target.kind === 'tour') {
|
||||
await placeActivitiesRepo.linkTrip(source.source.trip_id, source.source.place_id, {
|
||||
tour_id: target.tour_id,
|
||||
});
|
||||
}
|
||||
} else if (target.kind === 'collection_tour') {
|
||||
await placeActivitiesRepo.linkSaved(source.source.collection_place_id, target.collection_tour_id);
|
||||
}
|
||||
setPicking(null);
|
||||
});
|
||||
|
||||
const unlink = (activity: PlaceActivity) => run(() => placeActivitiesRepo.unlink(activity));
|
||||
|
||||
return {
|
||||
activities: current?.activities ?? [],
|
||||
canLink: linkable.length > 0,
|
||||
picking,
|
||||
closePicker: () => setPicking(null),
|
||||
openPicker,
|
||||
link,
|
||||
unlink,
|
||||
busy,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { PlaceHistoryEntry, PlacesLibraryEntry, PlacesLibraryKind } from '@trek/shared';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
import { placeHistoryRepo } from '../../repo/placeHistoryRepo';
|
||||
|
||||
/** How many changes a sheet shows at first and adds with "more". */
|
||||
const PAGE = 20;
|
||||
|
||||
/** The open entry's first origin, which the history route reads through like the detail route. */
|
||||
function originKey(entry: PlacesLibraryEntry | null): string | null {
|
||||
const o = entry?.origins[0];
|
||||
if (!o) return null;
|
||||
return o.kind === 'trip' ? `trip:${o.place_id}` : `list:${o.collection_place_id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The change history of a place of All places (PLC-14), for the desktop and the
|
||||
* phone sheet: who changed which detail when, newest first, across every trip and
|
||||
* list of the place the reader can open, and more on request. Nothing is shown
|
||||
* of a trip or list the reader cannot open, not even that it changed.
|
||||
*/
|
||||
export function usePlaceHistory(entry: PlacesLibraryEntry | null) {
|
||||
const key = originKey(entry);
|
||||
const [page, setPage] = useState<{ key: string; entries: PlaceHistoryEntry[]; next: string | null } | null>(null);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!key) return;
|
||||
const [kind, id] = key.split(':');
|
||||
const ctrl = new AbortController();
|
||||
placeHistoryRepo
|
||||
.history(kind as PlacesLibraryKind, Number(id), { limit: PAGE }, ctrl.signal)
|
||||
.then((res) => {
|
||||
if (!ctrl.signal.aborted) setPage({ key, entries: res.entries, next: res.next_cursor });
|
||||
})
|
||||
// No history to show is what a failed read looks like too.
|
||||
.catch(() => {
|
||||
if (!ctrl.signal.aborted) setPage({ key, entries: [], next: null });
|
||||
});
|
||||
return () => ctrl.abort();
|
||||
}, [key]);
|
||||
|
||||
const current = page && page.key === key ? page : null;
|
||||
|
||||
const more = useCallback(async () => {
|
||||
if (!current?.next || loadingMore || !key) return;
|
||||
const [kind, id] = key.split(':');
|
||||
setLoadingMore(true);
|
||||
try {
|
||||
const res = await placeHistoryRepo.history(kind as PlacesLibraryKind, Number(id), {
|
||||
limit: PAGE,
|
||||
cursor: current.next,
|
||||
});
|
||||
setPage((prev) =>
|
||||
prev && prev.key === key ? { key, entries: [...prev.entries, ...res.entries], next: res.next_cursor } : prev
|
||||
);
|
||||
} catch {
|
||||
// The list stays as it is; another tap tries again.
|
||||
} finally {
|
||||
setLoadingMore(false);
|
||||
}
|
||||
}, [current, loadingMore, key]);
|
||||
|
||||
return {
|
||||
entries: current?.entries ?? [],
|
||||
hasMore: !!current?.next,
|
||||
loadingMore,
|
||||
more,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { PlaceMediaFile, PlaceMediaResponse, PlacesLibraryEntry, PlacesLibraryKind } from '@trek/shared';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { placeVisitsRepo } from '../../repo/placeVisitsRepo';
|
||||
|
||||
/** One picture of a place, as the strip and the lightbox show it. */
|
||||
export interface PlacePhoto {
|
||||
id: string;
|
||||
src: string;
|
||||
thumbSrc: string;
|
||||
/** Where it comes from: the trip, the list or the journey and its day. */
|
||||
caption: string;
|
||||
provider?: string;
|
||||
mediaType?: string | null;
|
||||
}
|
||||
|
||||
const journeyPhoto = (photoId: number, size: 'thumbnail' | 'original') => `/api/photos/${photoId}/${size}`;
|
||||
|
||||
/** The pictures of a place from all its origins, the place's own first, then the journeys', each once. */
|
||||
export function photosOf(media: PlaceMediaResponse | null): PlacePhoto[] {
|
||||
if (!media) return [];
|
||||
const seen = new Set<string>();
|
||||
const out: PlacePhoto[] = [];
|
||||
for (const img of media.images) {
|
||||
if (seen.has(img.image_url)) continue;
|
||||
seen.add(img.image_url);
|
||||
out.push({
|
||||
id: `img:${img.image_url}`,
|
||||
src: img.image_url,
|
||||
thumbSrc: img.image_url,
|
||||
caption: img.kind === 'trip' ? img.trip_title : img.collection_name,
|
||||
});
|
||||
}
|
||||
for (const p of media.journey_photos) {
|
||||
out.push({
|
||||
id: `jp:${p.journey_photo_id}`,
|
||||
src: journeyPhoto(p.photo_id, 'original'),
|
||||
thumbSrc: journeyPhoto(p.photo_id, 'thumbnail'),
|
||||
caption: p.caption?.trim() || p.journey_title,
|
||||
provider: p.provider,
|
||||
mediaType: p.media_type,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The open entry's origin the media are read through: its first trip place or saved place. */
|
||||
function originKey(entry: PlacesLibraryEntry | null): string | null {
|
||||
const o = entry?.origins[0];
|
||||
if (!o) return null;
|
||||
return o.kind === 'trip' ? `trip:${o.place_id}` : `list:${o.collection_place_id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pictures and trip files of a place of All places (PLC-19, PLC-20), for the
|
||||
* desktop and the phone sheet: the place's own images from its trips and lists,
|
||||
* the photos of journey entries made from it, and the files a trip attached to
|
||||
* it, each with where it comes from and only where the reader may open it.
|
||||
*/
|
||||
export function usePlaceMedia(entry: PlacesLibraryEntry | null) {
|
||||
const [media, setMedia] = useState<{ key: string; res: PlaceMediaResponse } | null>(null);
|
||||
const [open, setOpen] = useState<number | null>(null);
|
||||
const key = originKey(entry);
|
||||
|
||||
useEffect(() => {
|
||||
if (!key) return;
|
||||
const [kind, id] = key.split(':');
|
||||
const ctrl = new AbortController();
|
||||
placeVisitsRepo
|
||||
.media(kind as PlacesLibraryKind, Number(id), ctrl.signal)
|
||||
.then((res) => {
|
||||
if (!ctrl.signal.aborted) setMedia({ key, res });
|
||||
})
|
||||
// Pictures are extra: without them the sheet simply shows none.
|
||||
.catch(() => {
|
||||
if (!ctrl.signal.aborted) setMedia({ key, res: { images: [], journey_photos: [], files: [] } });
|
||||
});
|
||||
return () => ctrl.abort();
|
||||
}, [key]);
|
||||
|
||||
const current = media && media.key === key ? media.res : null;
|
||||
const photos = useMemo(() => photosOf(current), [current]);
|
||||
const files: PlaceMediaFile[] = current?.files ?? [];
|
||||
return { photos, files, open, setOpen, close: () => setOpen(null) };
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { PlaceVisitsForPlaceResponse, PlacesLibraryEntry, PlacesLibraryKind } from '@trek/shared';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { placeVisitsRepo } from '../../repo/placeVisitsRepo';
|
||||
|
||||
/** The open entry's own origin the visits are read through: its first trip place or saved place. */
|
||||
function originKey(entry: PlacesLibraryEntry | null): string | null {
|
||||
const o = entry?.origins[0];
|
||||
if (!o) return null;
|
||||
return o.kind === 'trip' ? `trip:${o.place_id}` : `list:${o.collection_place_id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A trip place as the one-origin entry the visits are read through, so the
|
||||
* planner shows the same history as All places.
|
||||
*/
|
||||
export function tripPlaceEntry(
|
||||
trip: { id: number; title: string; start_date?: string | null; end_date?: string | null },
|
||||
place: { id: number; name: string; address?: string | null; lat?: number | null; lng?: number | null }
|
||||
): PlacesLibraryEntry {
|
||||
return {
|
||||
key: `trip:${place.id}`,
|
||||
name: place.name,
|
||||
address: place.address ?? null,
|
||||
lat: place.lat ?? null,
|
||||
lng: place.lng ?? null,
|
||||
category: null,
|
||||
image_url: null,
|
||||
updated_at: null,
|
||||
origins: [
|
||||
{
|
||||
kind: 'trip',
|
||||
trip_id: trip.id,
|
||||
trip_title: trip.title,
|
||||
trip_start: trip.start_date ?? null,
|
||||
trip_end: trip.end_date ?? null,
|
||||
place_id: place.id,
|
||||
can_edit: true,
|
||||
read_only: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const NONE: PlaceVisitsForPlaceResponse = { visits: [], visit_count: 0, last_visit: null };
|
||||
|
||||
/**
|
||||
* A place's visits (PLC-10), for the sheets of All places and the planner. A
|
||||
* visit is nothing anyone enters: a place planned on a day of a trip that has
|
||||
* passed counts as visited, so this only reads what the trips say. Online only;
|
||||
* offline, or without visits, there is simply nothing to show.
|
||||
*/
|
||||
export function usePlaceVisits({ entry }: { entry: PlacesLibraryEntry | null }) {
|
||||
const [data, setData] = useState<{ key: string; res: PlaceVisitsForPlaceResponse } | null>(null);
|
||||
const key = originKey(entry);
|
||||
|
||||
useEffect(() => {
|
||||
if (!key) return;
|
||||
const [kind, id] = key.split(':');
|
||||
const ctrl = new AbortController();
|
||||
placeVisitsRepo
|
||||
.forPlace(kind as PlacesLibraryKind, Number(id), ctrl.signal)
|
||||
.then((res) => {
|
||||
if (!ctrl.signal.aborted) setData({ key, res });
|
||||
})
|
||||
// No history to show is what a failed read looks like too.
|
||||
.catch(() => {
|
||||
if (!ctrl.signal.aborted) setData({ key, res: NONE });
|
||||
});
|
||||
return () => ctrl.abort();
|
||||
}, [key]);
|
||||
|
||||
const current = data && data.key === key ? data.res : null;
|
||||
return {
|
||||
visits: current?.visits ?? [],
|
||||
count: current?.visit_count ?? 0,
|
||||
lastVisit: current?.last_visit ?? null,
|
||||
loading: key !== null && current === null,
|
||||
};
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { OnlineOnlyError } from '../../repo/onlineOnly';
|
||||
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
|
||||
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
|
||||
@@ -83,6 +84,12 @@ function useLibraryFilters() {
|
||||
const [categoryId, setCategoryId] = useState<number | 'all'>('all');
|
||||
const [sort, setSort] = useState<PlacesLibrarySort>('name');
|
||||
const [status, setStatus] = useState<CollectionStatus | 'all'>('all');
|
||||
// PLC-21: the reader's own tags, any of which an entry must carry.
|
||||
const [tagIds, setTagIds] = useState<number[]>([]);
|
||||
const toggleTag = useCallback(
|
||||
(id: number) => setTagIds((ids) => (ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id])),
|
||||
[]
|
||||
);
|
||||
|
||||
// Typing settles before it asks.
|
||||
useEffect(() => {
|
||||
@@ -96,18 +103,20 @@ function useLibraryFilters() {
|
||||
...(kind !== 'all' ? { kind } : {}),
|
||||
...(categoryId !== 'all' ? { category_id: categoryId } : {}),
|
||||
...(status !== 'all' ? { status } : {}),
|
||||
...(tagIds.length > 0 ? { tag_ids: tagIds } : {}),
|
||||
sort,
|
||||
limit: PAGE,
|
||||
}),
|
||||
[query, kind, categoryId, status, sort]
|
||||
[query, kind, categoryId, status, tagIds, sort]
|
||||
);
|
||||
const filtered = query !== '' || kind !== 'all' || categoryId !== 'all' || status !== 'all';
|
||||
const filtered = query !== '' || kind !== 'all' || categoryId !== 'all' || status !== 'all' || tagIds.length > 0;
|
||||
const resetFilters = useCallback(() => {
|
||||
setSearch('');
|
||||
setQuery('');
|
||||
setKind('all');
|
||||
setCategoryId('all');
|
||||
setStatus('all');
|
||||
setTagIds([]);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
@@ -123,6 +132,8 @@ function useLibraryFilters() {
|
||||
setSort,
|
||||
status,
|
||||
setStatus,
|
||||
tagIds,
|
||||
toggleTag,
|
||||
filtered,
|
||||
resetFilters,
|
||||
},
|
||||
@@ -283,7 +294,10 @@ function useLibraryCover(detail: PlacesLibraryDetailResponse | null): string | n
|
||||
* each of its origins keeps.
|
||||
*/
|
||||
export function usePlacesLibrary({ active, t }: { active: boolean; t: TranslationFn }) {
|
||||
const [reloadSeq, setReloadSeq] = useState(0);
|
||||
const [ownSeq, setReloadSeq] = useState(0);
|
||||
// A place saved to a list from here or anywhere else adds an origin: read again then too.
|
||||
const savedVersion = useSaveToCollectionStore((st) => st.version);
|
||||
const reloadSeq = ownSeq + savedVersion;
|
||||
const [detailError, setDetailError] = useState<{ error: string | null; offline: boolean } | null>(null);
|
||||
const pages = useLibraryPages(active, reloadSeq, t);
|
||||
const onDetailError = useCallback((err: unknown) => setDetailError(failureOf(err, t)), [t]);
|
||||
|
||||
@@ -24,12 +24,15 @@ export interface CopyResult {
|
||||
export interface CopyCarryOptions {
|
||||
hasNotes: boolean;
|
||||
tags: { id: number; name: string; color?: string | null }[];
|
||||
/** The reader's own tags on the place (PLC-21), private unless picked here. */
|
||||
personalTags?: { 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[];
|
||||
personal_tag_ids?: number[];
|
||||
}
|
||||
|
||||
export interface TripCopyPickerOptions {
|
||||
@@ -75,6 +78,9 @@ export function useTripCopyPicker({
|
||||
const [includeNotes, setIncludeNotes] = useState(false);
|
||||
const [tagIds, setTagIds] = useState<number[]>([]);
|
||||
const toggleTag = (id: number) => setTagIds((ids) => (ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id]));
|
||||
const [personalTagIds, setPersonalTagIds] = useState<number[]>([]);
|
||||
const togglePersonalTag = (id: number) =>
|
||||
setPersonalTagIds((ids) => (ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id]));
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -83,6 +89,7 @@ export function useTripCopyPicker({
|
||||
setSearch('');
|
||||
setIncludeNotes(false);
|
||||
setTagIds([]);
|
||||
setPersonalTagIds([]);
|
||||
tripsApi
|
||||
.list()
|
||||
.then((res: { trips?: TripOption[] }) => {
|
||||
@@ -117,6 +124,9 @@ export function useTripCopyPicker({
|
||||
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 ownOffered = new Set(carryOptions?.personalTags?.map((tag) => tag.id) ?? []);
|
||||
const own = personalTagIds.filter((id) => ownOffered.has(id));
|
||||
if (own.length) carry.personal_tag_ids = own;
|
||||
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 }));
|
||||
@@ -129,7 +139,8 @@ export function useTripCopyPicker({
|
||||
}
|
||||
};
|
||||
|
||||
const offersCarry = !!carryOptions && (carryOptions.hasNotes || carryOptions.tags.length > 0);
|
||||
const offersCarry =
|
||||
!!carryOptions && (carryOptions.hasNotes || carryOptions.tags.length > 0 || !!carryOptions.personalTags?.length);
|
||||
|
||||
return {
|
||||
loading,
|
||||
@@ -144,5 +155,7 @@ export function useTripCopyPicker({
|
||||
setIncludeNotes,
|
||||
tagIds,
|
||||
toggleTag,
|
||||
personalTagIds,
|
||||
togglePersonalTag,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import type { TripCollectionLayerPlace } from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { useCollectionStore } from '../../store/collectionStore';
|
||||
import { tripCollectionsEntry, useTripCollectionsStore, watchTripCollections } from '../../store/tripCollectionsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { SAVED_PLACE_POI_CATEGORY, type Poi } from '../Map/poiCategories';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
const SAVED_PREFIX = 'saved:';
|
||||
const NO_POIS: Poi[] = [];
|
||||
|
||||
/** The lists shown on a trip's map, remembered per trip on this device; the layer starts off. */
|
||||
function shownKey(tripId: number): string {
|
||||
return `trek:tripListsShown:${tripId}`;
|
||||
}
|
||||
|
||||
function readShown(tripId: number): number[] {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(shownKey(tripId));
|
||||
const parsed: unknown = raw ? JSON.parse(raw) : [];
|
||||
return Array.isArray(parsed) ? parsed.filter((n): n is number => Number.isSafeInteger(n)) : [];
|
||||
} catch {
|
||||
// Storage blocked or broken: nothing shown, which is the start anyway.
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeShown(tripId: number, ids: number[]): void {
|
||||
try {
|
||||
window.localStorage.setItem(shownKey(tripId), JSON.stringify(ids));
|
||||
} catch {
|
||||
// Storage blocked: the choice lasts until the page closes.
|
||||
}
|
||||
}
|
||||
|
||||
/** A saved place as a pin of the map's POI layer, in its list's colour and symbol. */
|
||||
export function savedPlacePoi(
|
||||
place: TripCollectionLayerPlace,
|
||||
look: { color?: string | null; icon?: string | null }
|
||||
): Poi {
|
||||
return {
|
||||
osm_id: `${SAVED_PREFIX}${place.id}`,
|
||||
name: place.name,
|
||||
lat: place.lat,
|
||||
lng: place.lng,
|
||||
category: SAVED_PLACE_POI_CATEGORY,
|
||||
poi_type: SAVED_PLACE_POI_CATEGORY,
|
||||
address: null,
|
||||
website: null,
|
||||
phone: null,
|
||||
opening_hours: null,
|
||||
cuisine: null,
|
||||
source: 'list',
|
||||
...(look.color ? { color: look.color } : {}),
|
||||
...(look.icon ? { icon: look.icon } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The saved place a pin stands for, or null for any other POI. */
|
||||
export function savedPlaceIdOf(poi: Pick<Poi, 'osm_id'>): number | null {
|
||||
if (!poi.osm_id.startsWith(SAVED_PREFIX)) return null;
|
||||
const id = Number(poi.osm_id.slice(SAVED_PREFIX.length));
|
||||
return Number.isSafeInteger(id) && id > 0 ? id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The lists a trip draws on (PLC-15) and their places on its map (PLC-16), for
|
||||
* the desktop stage and the phone's map: which lists are linked, linking and
|
||||
* unlinking one, which of them the map shows (off at first, remembered per trip
|
||||
* on this device), their places not yet in the trip as pins, and taking one of
|
||||
* them into the trip. Who may see a list is the list's own sharing; the server
|
||||
* leaves out every list the reader cannot open.
|
||||
*/
|
||||
export function useTripLists({ tripId, canEdit, t }: { tripId: number; canEdit: boolean; t: TranslationFn }) {
|
||||
const toast = useToast();
|
||||
const entry = useTripCollectionsStore((s) => tripCollectionsEntry(s, tripId));
|
||||
const load = useTripCollectionsStore((s) => s.load);
|
||||
const loadLayer = useTripCollectionsStore((s) => s.loadLayer);
|
||||
const linkList = useTripCollectionsStore((s) => s.link);
|
||||
const unlinkList = useTripCollectionsStore((s) => s.unlink);
|
||||
const lists = useCollectionStore((s) => s.collections);
|
||||
const loadLists = useCollectionStore((s) => s.loadAll);
|
||||
const copyToTrip = useCollectionStore((s) => s.copyToTrip);
|
||||
const refreshPlaces = useTripStore((s) => s.refreshPlaces);
|
||||
const [shown, setShown] = useState<number[]>(() => readShown(tripId));
|
||||
const [pending, setPending] = useState<{ id: number; name: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => watchTripCollections(), []);
|
||||
useEffect(() => {
|
||||
load(tripId).catch(() => {
|
||||
// Offline or without the addon: no lists to offer.
|
||||
return undefined;
|
||||
});
|
||||
}, [tripId, load]);
|
||||
|
||||
const links = useMemo(() => entry?.links ?? [], [entry]);
|
||||
// Only what is still linked counts as shown, so an unlinked list leaves the map too.
|
||||
const visible = useMemo(() => shown.filter((id) => links.some((l) => l.collection_id === id)), [shown, links]);
|
||||
const layer = entry?.layer ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
if (visible.length === 0 || layer !== null) return;
|
||||
loadLayer(tripId).catch((err: unknown) => toast.error(getApiErrorMessage(err, t('common.error'))));
|
||||
}, [visible.length, layer, tripId, loadLayer, toast, t]);
|
||||
|
||||
const lookOf = useMemo(() => new Map(lists.map((c) => [c.id, { color: c.color, icon: c.icon }])), [lists]);
|
||||
const pois = useMemo(() => {
|
||||
if (!layer || visible.length === 0) return NO_POIS;
|
||||
const on = new Set(visible);
|
||||
return layer
|
||||
.filter((p) => on.has(p.collection_id) && !p.in_trip)
|
||||
.map((p) =>
|
||||
savedPlacePoi(p, lookOf.get(p.collection_id) ?? links.find((l) => l.collection_id === p.collection_id) ?? {})
|
||||
);
|
||||
}, [layer, visible, lookOf, links]);
|
||||
|
||||
const toggle = useCallback(
|
||||
(collectionId: number) => {
|
||||
const next = visible.includes(collectionId)
|
||||
? visible.filter((id) => id !== collectionId)
|
||||
: [...visible, collectionId];
|
||||
setShown(next);
|
||||
writeShown(tripId, next);
|
||||
},
|
||||
[visible, tripId]
|
||||
);
|
||||
|
||||
/** A tap on a pin: a saved place asks to be taken into the trip; any other POI is not ours. */
|
||||
const claim = useCallback(
|
||||
(poi: Poi): boolean => {
|
||||
const id = savedPlaceIdOf(poi);
|
||||
if (id === null) return false;
|
||||
if (canEdit) setPending({ id, name: poi.name });
|
||||
return true;
|
||||
},
|
||||
[canEdit]
|
||||
);
|
||||
|
||||
const run = async (action: () => Promise<unknown>) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await action();
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** The pending saved place into the trip, its own notes left behind (they stay the reader's). */
|
||||
const addPending = () =>
|
||||
run(async () => {
|
||||
if (!pending) return;
|
||||
const res = await copyToTrip(tripId, [pending.id]);
|
||||
setPending(null);
|
||||
if (res.copied > 0) toast.success(t('tripLists.added', { name: pending.name }));
|
||||
else toast.info(t('tripLists.alreadyInTrip', { name: pending.name }));
|
||||
await Promise.all([refreshPlaces(tripId), loadLayer(tripId)]);
|
||||
});
|
||||
|
||||
const link = (collectionId: number) =>
|
||||
run(async () => {
|
||||
await linkList(tripId, collectionId);
|
||||
// A list linked from here is one the reader wants to see.
|
||||
const next = [...visible, collectionId];
|
||||
setShown(next);
|
||||
writeShown(tripId, next);
|
||||
});
|
||||
const unlink = (collectionId: number) => run(() => unlinkList(tripId, collectionId));
|
||||
|
||||
const linkable = useMemo(() => lists.filter((c) => !links.some((l) => l.collection_id === c.id)), [lists, links]);
|
||||
|
||||
return {
|
||||
links,
|
||||
canLink: !!entry?.canLink,
|
||||
visible,
|
||||
pois,
|
||||
toggle,
|
||||
claim,
|
||||
pending,
|
||||
cancelPending: () => setPending(null),
|
||||
addPending,
|
||||
busy,
|
||||
linkable,
|
||||
/** Reads the reader's lists the first time the picker opens. */
|
||||
loadLinkable: () => {
|
||||
if (lists.length === 0)
|
||||
loadLists().catch((err: unknown) => toast.error(getApiErrorMessage(err, t('common.error'))));
|
||||
},
|
||||
link,
|
||||
unlink,
|
||||
lookOf,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Utensils, Coffee, Wine, BedDouble, Camera, Landmark, Trees, Ticket, Fuel, Zap, ParkingSquare, Tent, Binoculars, Mountain, Warehouse, Droplet, Toilet, Sandwich, Anchor, Sailboat, Wrench, Store, BatteryCharging, Croissant, ShoppingBasket, type LucideIcon } from 'lucide-react'
|
||||
import { listIcon } from '../Collections/listIcons'
|
||||
import type { TourPoiCategory } from '@trek/shared'
|
||||
import { parsePluginPoiCategoryKey, type PluginPoiDetail } from '@trek/shared'
|
||||
// The road-trip kinds take their colour from the one place that defines it, so the
|
||||
@@ -127,6 +128,14 @@ export interface Poi {
|
||||
color?: string
|
||||
}
|
||||
|
||||
/** The category of a saved place a linked list lays over the trip map (PLC-16). */
|
||||
export const SAVED_PLACE_POI_CATEGORY = 'saved-place'
|
||||
|
||||
/** A list's colour when it is a `#rrggbb` value, the theme's accent otherwise. */
|
||||
function savedPlaceColor(color: string | undefined): string {
|
||||
return color && /^#[0-9a-fA-F]{6}$/.test(color) ? color : 'var(--accent)'
|
||||
}
|
||||
|
||||
/** What a POI pin and its hover card are drawn with. */
|
||||
export interface PoiAppearance {
|
||||
color: string
|
||||
@@ -143,6 +152,8 @@ export interface PoiAppearance {
|
||||
* category and is drawn like one.
|
||||
*/
|
||||
export function poiAppearance(poi: Pick<Poi, 'category' | 'icon' | 'color'>): PoiAppearance {
|
||||
// A saved place of a list linked to the trip (PLC-16): the list's own symbol in its colour.
|
||||
if (poi.category === SAVED_PLACE_POI_CATEGORY) return { color: savedPlaceColor(poi.color), Icon: listIcon(poi.icon) }
|
||||
const core = CATEGORY_BY_KEY.get(poi.category)
|
||||
if (core) return { color: core.color, Icon: core.Icon }
|
||||
if (parsePluginPoiCategoryKey(poi.category)) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createElement } from 'react'
|
||||
import { PLUGIN_POI_DETAILS_MAX, isPluginPoiIcon, parsePluginPoiCategoryKey, type PluginPoiDetail } from '@trek/shared'
|
||||
import { renderIconMarkup } from '../../utils/iconMarkup'
|
||||
import { poiAppearance, type Poi } from './poiCategories'
|
||||
import { poiAppearance, SAVED_PLACE_POI_CATEGORY, type Poi } from './poiCategories'
|
||||
import { pluginPoiColor } from './pluginPoiIcons'
|
||||
|
||||
/**
|
||||
@@ -32,6 +32,8 @@ export function poiPinParts(poi: PoiLook): { color: string; svg: string } {
|
||||
* icon: a pin cached before the update is never handed out after it.
|
||||
*/
|
||||
export function poiPinCacheKey(poi: PoiLook): string {
|
||||
// A saved place is drawn in its list's colour and symbol, so lists apart are pins apart.
|
||||
if (poi.category === SAVED_PLACE_POI_CATEGORY) return `${poi.category}|${poi.color ?? ''}|${poi.icon ?? ''}`
|
||||
if (!parsePluginPoiCategoryKey(poi.category)) return poi.category
|
||||
const icon = isPluginPoiIcon(poi.icon) ? poi.icon : ''
|
||||
return `${poi.category}|${pluginPoiColor(poi.color)}|${icon}`
|
||||
|
||||
@@ -42,6 +42,7 @@ import type { EndDayControlProps } from '../Roadtrip/EndDayControl'
|
||||
import VisitControls, { type RoadtripStayControl } from '../Roadtrip/VisitControls'
|
||||
import { DialogButton, DialogIconButton, DialogSection, DeleteButton, FooterSpacer, fs } from '../shared/DialogShell'
|
||||
import { BOX, Field, TypeTile, toneOf, toneTint, useOpenFile } from './bookings/bookingParts'
|
||||
import TripPlaceVisits from '../Collections/TripPlaceVisits'
|
||||
import { parseMeta } from './bookings/bookingsModel'
|
||||
import { MoreButton, SoftPill } from './planParts'
|
||||
import { InspectorHead } from './PlaceInspectorHead'
|
||||
@@ -446,6 +447,7 @@ export default function PlaceInspector({
|
||||
onFileUpload={onFileUpload} filesExpanded={filesExpanded} setFilesExpanded={setFilesExpanded}
|
||||
fileInputRef={fileInputRef} handleFileUpload={handleFileUpload} isUploading={isUploading}
|
||||
distanceUnit={distanceUnit} onUpdatePlace={onUpdatePlace} />
|
||||
{mode === 'trip' && trip && <TripPlaceVisits trip={trip} place={place} language={locale} t={t} />}
|
||||
|
||||
{/* Extra native rows from placeDetailProvider plugins (#1429). */}
|
||||
{mode === 'trip' && providerDetails.length > 0 && (
|
||||
|
||||
@@ -149,7 +149,7 @@ function CategoryChoice({ on, onClick, tile, label }: { on: boolean; onClick: ()
|
||||
function ShowDropdown(S: SidebarState) {
|
||||
const { t, filter, pickFilter, filterCounts } = S
|
||||
const [open, setOpen] = useState(false)
|
||||
const tabs = placesFilterTabs(t, S.hasTracks)
|
||||
const tabs = placesFilterTabs(t, S.hasTracks, S.hasVisited)
|
||||
const current = tabs.find(tab => tab.id === filter) ?? tabs[0]
|
||||
return (
|
||||
<FilterDropdown
|
||||
|
||||
@@ -13,7 +13,7 @@ function colorFor(userId: number) {
|
||||
return SPLIT_COLORS[(((Math.trunc(userId) - 1) % n) + n) % n]
|
||||
}
|
||||
|
||||
function Avatar({ userId, username, avatarUrl, size = 22, dim = false }: {
|
||||
export function Avatar({ userId, username, avatarUrl, size = 22, dim = false }: {
|
||||
userId: number
|
||||
username?: string
|
||||
avatarUrl?: string | null
|
||||
|
||||
@@ -8,8 +8,8 @@ import { offlineOr } from '../../utils/needsConnection';
|
||||
import { tagChoices } from '../../utils/placeTags';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
/** What the pool shows: everything, what is not on a day yet, what is, or the tracks. */
|
||||
export type PlacesFilter = 'all' | 'unplanned' | 'planned' | 'tracks';
|
||||
/** What the pool shows: everything, what is not on a day yet, what is, what the reader visited, or the tracks. */
|
||||
export type PlacesFilter = 'all' | 'unplanned' | 'planned' | 'visited' | 'tracks';
|
||||
|
||||
type Translate = ReturnType<typeof useTranslation>['t'];
|
||||
|
||||
@@ -18,13 +18,14 @@ export function poolHasTracks(places: Place[], toursEnabled: boolean | undefined
|
||||
return !toursEnabled && places.some((p) => p.route_geometry);
|
||||
}
|
||||
|
||||
/** The "show" choices; tracks only once a place has one. */
|
||||
export function placesFilterTabs(t: Translate, hasTracks: boolean) {
|
||||
/** The "show" choices; "visited" once the reader confirmed a visit at a place of the trip, tracks once a place has one. */
|
||||
export function placesFilterTabs(t: Translate, hasTracks: boolean, hasVisited = false) {
|
||||
const tabs: Array<{ id: PlacesFilter; label: string }> = [
|
||||
{ id: 'all', label: t('places.all') },
|
||||
{ id: 'unplanned', label: t('places.unplanned') },
|
||||
{ id: 'planned', label: t('places.planned') },
|
||||
];
|
||||
if (hasVisited) tabs.push({ id: 'visited', label: t('places.filterVisited') });
|
||||
if (hasTracks) tabs.push({ id: 'tracks', label: t('places.filterTracks') });
|
||||
return tabs;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { placeToSaveTarget } from '../Collections/saveTarget'
|
||||
import type { Place, Category, Day, AssignmentsMap } from '../../types'
|
||||
import { getGoogleMapsUrlForPlace } from './placeGoogleMaps'
|
||||
import { placeMatchesSearch } from '../../utils/placeSearch'
|
||||
import { useTripVisitedIds } from '../../hooks/useTripVisitedIds'
|
||||
import { matchesCategoryFilter, matchesPlacesFilter } from '../../utils/placesFilter'
|
||||
import { safeHttpUrl } from '../../utils/safeUrl'
|
||||
import { plannedPlaceIds, plannedPlaceIdsForDay, type PlannedAccommodation } from '../../utils/plannedPlaces'
|
||||
@@ -194,16 +195,17 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
)
|
||||
const plannedFilterIds = plannedInDayIds ?? plannedIds
|
||||
const dayScoped = filter === 'planned' && plannedInDayIds !== null
|
||||
const visitedIds = useTripVisitedIds(tripId)
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const list = poolPlaces.filter(p => {
|
||||
if (!matchesPlacesFilter(p, { filter, categoryFilters, ratingFilter }, { plannedIds, plannedFilterIds })) return false
|
||||
if (!matchesPlacesFilter(p, { filter, categoryFilters, ratingFilter }, { plannedIds, plannedFilterIds, visitedIds })) return false
|
||||
if (!placeMatchesSearch(p, search)) return false
|
||||
if (localityFilter && !matchesLocality(localityOf.get(p.id), localityFilter)) return false
|
||||
return true
|
||||
})
|
||||
return sortPlaces(list, placesSort, language)
|
||||
}, [poolPlaces, filter, categoryFilters, search, plannedIds, plannedFilterIds, ratingFilter, localityFilter, localityOf, placesSort, language])
|
||||
}, [poolPlaces, filter, categoryFilters, search, plannedIds, plannedFilterIds, visitedIds, ratingFilter, localityFilter, localityOf, placesSort, language])
|
||||
|
||||
/**
|
||||
* How many places each "show" choice would leave, under the category and search
|
||||
@@ -218,9 +220,10 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
all: base.length,
|
||||
unplanned: base.filter(p => !plannedIds.has(p.id)).length,
|
||||
planned: base.filter(p => plannedFilterIds.has(p.id)).length,
|
||||
visited: base.filter(p => visitedIds.has(p.id)).length,
|
||||
tracks: base.filter(p => p.route_geometry).length,
|
||||
} satisfies Record<PlacesFilter, number>
|
||||
}, [poolPlaces, categoryFilters, search, plannedIds, plannedFilterIds])
|
||||
}, [poolPlaces, categoryFilters, search, plannedIds, plannedFilterIds, visitedIds])
|
||||
|
||||
/** The filters narrowing the list besides the search box, for the badge on the filter button. */
|
||||
|
||||
@@ -316,7 +319,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
markSelectionVisited, markVisitedBusy,
|
||||
exitSelectMode, toggleSelected, toggleCategoryFilter, dayPickerPlace, setDayPickerPlace,
|
||||
mobileShowDays, setMobileShowDays,
|
||||
hasTracks, plannedIds, plannedFilterIds, dayScoped, filtered, registerPlaceRow, isAssignedToSelectedDay, inDaySet,
|
||||
hasTracks, hasVisited: visitedIds.size > 0 || filter === 'visited', plannedIds, plannedFilterIds, dayScoped, filtered, registerPlaceRow, isAssignedToSelectedDay, inDaySet,
|
||||
openContextMenu, placeMenuItems,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEffect, useMemo } from 'react';
|
||||
|
||||
import { tripVisitedEntry, usePlaceVisitsStore, watchPlaceVisits } from '../store/placeVisitsStore';
|
||||
|
||||
/**
|
||||
* The places of a trip the reader confirmed a visit at (PLC-23), there or at the
|
||||
* same place elsewhere, for the "visited" choice of the place list and the map.
|
||||
* Read when the trip opens and again whenever a visit changes; offline it stays
|
||||
* empty, so the choice simply is not offered.
|
||||
*/
|
||||
export function useTripVisitedIds(tripId: number | null | undefined): ReadonlySet<number> {
|
||||
const entry = usePlaceVisitsStore((s) => tripVisitedEntry(s, tripId));
|
||||
const load = usePlaceVisitsStore((s) => s.loadTripVisited);
|
||||
|
||||
useEffect(() => watchPlaceVisits(), []);
|
||||
useEffect(() => {
|
||||
if (tripId == null) return;
|
||||
load(tripId).catch(() => {
|
||||
// Offline or without access: no visited places to offer.
|
||||
return undefined;
|
||||
});
|
||||
}, [tripId, load]);
|
||||
|
||||
const ids = entry?.placeIds;
|
||||
return useMemo(() => new Set(ids ?? []), [ids]);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import Markdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import remarkBreaks from 'remark-breaks'
|
||||
import { Camera, Check, Copy, ExternalLink, Loader2, MapPin, Navigation, Pencil, Trash2, X } from 'lucide-react'
|
||||
import PlaceLocationBadge from '../../../components/Collections/PlaceLocationBadge'
|
||||
import type { CollectionLabel, CollectionLink, CollectionPlace, CollectionStatus } from '@trek/shared'
|
||||
import type { Category, TranslationFn } from '../../../types'
|
||||
import { useCollectionPlaceForm } from '../../../components/Collections/useCollectionPlaceForm'
|
||||
@@ -119,14 +120,10 @@ export default function MCollPlaceSheet({
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-1 text-[1.3125rem] font-extrabold text-white">{held.name}</div>
|
||||
{!editing && <div className="relative"><PlaceLocationBadge address={held.address} lat={held.lat} lng={held.lng} t={t} /></div>}
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-[18px] pt-[14px]">
|
||||
{!editing && held.address && (
|
||||
<div className="flex items-start gap-[6px] font-geist text-[0.75rem] leading-[1.5] text-m-muted">
|
||||
<MapPin size={13} strokeWidth={2} className="mt-[1px] flex-none" /> {held.address}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Status cycle: two by two on a phone, so every label keeps its room */}
|
||||
<div className="mt-3 grid grid-cols-2 gap-[6px] wide:grid-cols-4">
|
||||
|
||||
@@ -21,7 +21,7 @@ interface MCollTripPickerSheetProps {
|
||||
* selected places and reconciles the dedup result into toasts.
|
||||
*/
|
||||
export default function MCollTripPickerSheet({ open, count, onCopy, carryOptions, onClose, t }: MCollTripPickerSheetProps) {
|
||||
const { loading, search, setSearch, filtered, busyTripId, dateRange, handleCopy, offersCarry, includeNotes, setIncludeNotes, tagIds, toggleTag } =
|
||||
const { loading, search, setSearch, filtered, busyTripId, dateRange, handleCopy, offersCarry, includeNotes, setIncludeNotes, tagIds, toggleTag, personalTagIds, togglePersonalTag } =
|
||||
useTripCopyPicker({ open, onCopy, onClose, t, carryOptions })
|
||||
|
||||
const title = t('collections.copyN', { count })
|
||||
@@ -42,7 +42,7 @@ export default function MCollTripPickerSheet({ open, count, onCopy, carryOptions
|
||||
</div>
|
||||
{offersCarry && carryOptions && (
|
||||
<div className="mb-3">
|
||||
<CopyCarryPanel options={carryOptions} includeNotes={includeNotes} onIncludeNotes={setIncludeNotes} tagIds={tagIds} onToggleTag={toggleTag} variant="sheet" t={t} />
|
||||
<CopyCarryPanel options={carryOptions} includeNotes={includeNotes} onIncludeNotes={setIncludeNotes} tagIds={tagIds} onToggleTag={toggleTag} personalTagIds={personalTagIds} onTogglePersonalTag={togglePersonalTag} variant="sheet" t={t} />
|
||||
</div>
|
||||
)}
|
||||
{loading ? (
|
||||
|
||||
@@ -651,7 +651,6 @@ function SelectionAction({ label, onClick, disabled, danger = false, children }:
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className={`flex h-10 min-w-0 flex-1 items-center justify-center rounded-full border border-[color:var(--m-rowbr)] bg-m-sheetop disabled:opacity-40 ${danger ? 'text-[color:var(--m-st-danger)]' : 'text-m-ink'}`}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import type { PlacesLibraryDetailResponse, Tag as TagRow } from '@trek/shared';
|
||||
import { Check, Pencil, Plus, Trash2, X } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useEntryTags } from '../../../components/Collections/useEntryTags';
|
||||
import ConfirmDialog from '../../../components/shared/ConfirmDialog';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { Eyebrow, INPUT_CLS } from './MCollSheetKit';
|
||||
|
||||
type EntryTags = ReturnType<typeof useEntryTags>;
|
||||
|
||||
function Dot({ color }: { color: string | null | undefined }) {
|
||||
// The tag's own colour, the one data-driven value of the chip.
|
||||
return <span className="h-2 w-2 flex-none rounded-full" style={{ background: color || 'var(--m-act)' }} />;
|
||||
}
|
||||
|
||||
const ICON_BTN = 'flex h-8 w-8 flex-none items-center justify-center rounded-full bg-m-ic text-m-muted';
|
||||
|
||||
/** One tag in the phone's picker: ticked when the place carries it, renamed or deleted in place. */
|
||||
function MTagRow({ tag, on, tags, t }: { tag: TagRow; on: boolean; tags: EntryTags; t: TranslationFn }) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [name, setName] = useState(String(tag.name));
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
if (editing) {
|
||||
return (
|
||||
<form
|
||||
className="flex items-center gap-2 py-1"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void tags.rename(tag.id, name);
|
||||
setEditing(false);
|
||||
}}
|
||||
>
|
||||
<input
|
||||
autoFocus
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
aria-label={t('placeTags.rename')}
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
<button type="submit" aria-label={t('common.save')} className={ICON_BTN}>
|
||||
<Check size={14} />
|
||||
</button>
|
||||
<button type="button" onClick={() => setEditing(false)} aria-label={t('common.cancel')} className={ICON_BTN}>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex items-center gap-2 py-1">
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
onClick={() => void tags.toggle(tag.id)}
|
||||
className="flex min-w-0 flex-1 items-center gap-2 py-1 text-start text-body text-m-ink"
|
||||
>
|
||||
<Dot color={tag.color} />
|
||||
<span className="min-w-0 flex-1 truncate">{tag.name}</span>
|
||||
{on && <Check size={15} className="flex-none" />}
|
||||
</button>
|
||||
<button type="button" onClick={() => setEditing(true)} aria-label={t('placeTags.rename')} className={ICON_BTN}>
|
||||
<Pencil size={13} />
|
||||
</button>
|
||||
<button type="button" onClick={() => setConfirm(true)} aria-label={t('placeTags.delete')} className={ICON_BTN}>
|
||||
<Trash2 size={13} />
|
||||
</button>
|
||||
<ConfirmDialog
|
||||
isOpen={confirm}
|
||||
onClose={() => setConfirm(false)}
|
||||
onConfirm={() => void tags.destroy(tag.id)}
|
||||
title={t('placeTags.deleteTitle', { name: String(tag.name) })}
|
||||
message={t('placeTags.deleteMessage')}
|
||||
confirmLabel={t('placeTags.delete')}
|
||||
danger
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The reader's own tags on a place on the phone (PLC-21); the logic is the desktop sheet's. */
|
||||
export default function MEntryTagsSection({
|
||||
data,
|
||||
onChanged,
|
||||
t,
|
||||
}: {
|
||||
data: PlacesLibraryDetailResponse | null;
|
||||
onChanged: () => void;
|
||||
t: TranslationFn;
|
||||
}) {
|
||||
const tags = useEntryTags({ entry: data?.entry ?? null, onChanged, t });
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<div className="mb-[6px] mt-4 flex items-center gap-2">
|
||||
<Eyebrow>{t('placeTags.title').toUpperCase()}</Eyebrow>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-expanded={open}
|
||||
aria-label={open ? t('common.close') : t('placeTags.add')}
|
||||
className="ms-auto flex h-7 w-7 items-center justify-center rounded-full bg-m-ic text-m-ink"
|
||||
>
|
||||
{open ? <X size={14} /> : <Plus size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
{tags.assigned.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
{tags.assigned.map((tag) => (
|
||||
<span
|
||||
key={tag.id}
|
||||
className="inline-flex items-center gap-1.5 rounded-full border border-m-rowbr bg-m-ic px-[10px] py-[5px] text-caption font-semibold text-m-ink"
|
||||
>
|
||||
<Dot color={tag.color} />
|
||||
{tag.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
!open && <p className="m-0 text-caption text-m-muted">{t('placeTags.private')}</p>
|
||||
)}
|
||||
{open && (
|
||||
<div className="mt-2 rounded-2xl border border-m-rowbr bg-m-sheetop p-3">
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (tags.canCreate) void tags.createAndAdd();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={tags.query}
|
||||
onChange={(e) => tags.setQuery(e.target.value)}
|
||||
placeholder={t('placeTags.search')}
|
||||
aria-label={t('placeTags.search')}
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
</form>
|
||||
<div className="mt-2 max-h-[260px] overflow-y-auto">
|
||||
{tags.matches.map((tag) => (
|
||||
<MTagRow key={tag.id} tag={tag} on={tags.assignedIds.includes(tag.id)} tags={tags} t={t} />
|
||||
))}
|
||||
{tags.matches.length === 0 && !tags.canCreate && (
|
||||
<p className="m-0 py-2 text-caption text-m-muted">{t('placeTags.none')}</p>
|
||||
)}
|
||||
</div>
|
||||
{tags.canCreate && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void tags.createAndAdd()}
|
||||
disabled={tags.busy}
|
||||
className="mt-1 flex w-full items-center gap-2 py-2 text-start text-body font-semibold text-m-ink"
|
||||
>
|
||||
<Plus size={15} /> {t('placeTags.create', { name: tags.query.trim() })}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,20 +1,5 @@
|
||||
import type { PlacesLibraryDetailResponse } from '@trek/shared';
|
||||
import {
|
||||
Bookmark,
|
||||
BookmarkPlus,
|
||||
ChevronRight,
|
||||
Copy,
|
||||
Hotel,
|
||||
Loader2,
|
||||
Luggage,
|
||||
MapPin,
|
||||
MapPinOff,
|
||||
Navigation,
|
||||
NotebookPen,
|
||||
Star,
|
||||
Ticket,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { BookmarkPlus, ChevronRight, Copy, Hotel, Loader2, Luggage, Navigation, Star, Ticket, X } from 'lucide-react';
|
||||
import { createElement, useRef, useState } from 'react';
|
||||
import { tripLine } from '../../../components/Collections/libraryDates';
|
||||
import {
|
||||
@@ -24,7 +9,9 @@ import {
|
||||
type TripOrigin,
|
||||
type TripPair,
|
||||
} from '../../../components/Collections/libraryPairs';
|
||||
import { listIcon } from '../../../components/Collections/listIcons';
|
||||
import { originName } from '../../../components/Collections/originName';
|
||||
import PlaceLocationBadge from '../../../components/Collections/PlaceLocationBadge';
|
||||
import {
|
||||
getNavigationTargets,
|
||||
navigationTargetLabel,
|
||||
@@ -37,6 +24,12 @@ import MSheet from '../../components/MSheet';
|
||||
import { categoryMeta, STATUS_SPEC, tint, UNCATEGORIZED_META } from './collectionsMobileModel';
|
||||
import './libraryCover.css';
|
||||
import { Eyebrow } from './MCollSheetKit';
|
||||
import MEntryTagsSection from './MEntryTagsSection';
|
||||
import MOriginNotesSection from './MOriginNotesSection';
|
||||
import MPlaceActivitiesSection from './MPlaceActivitiesSection';
|
||||
import MPlaceHistorySection from './MPlaceHistorySection';
|
||||
import MPlaceMediaSection from './MPlaceMediaSection';
|
||||
import MVisitsSection from './MVisitsSection';
|
||||
|
||||
interface MLibraryPlaceSheetProps {
|
||||
open: boolean;
|
||||
@@ -49,6 +42,8 @@ interface MLibraryPlaceSheetProps {
|
||||
onOpenTrip: (tripId: number, placeId: number) => void;
|
||||
onSaveToList: (origin: TripOrigin, detail: TripDetail) => void;
|
||||
onCopyToTrip: (collectionPlaceId: number) => void;
|
||||
/** A note was saved: read the place again. */
|
||||
onNotesSaved: () => void;
|
||||
t: TranslationFn;
|
||||
}
|
||||
|
||||
@@ -59,20 +54,6 @@ const CHIP =
|
||||
const ACTION =
|
||||
'flex flex-1 items-center justify-center gap-[6px] rounded-[13px] border border-m-rowbr bg-m-sheet px-2 py-[11px] text-caption font-semibold text-m-ink';
|
||||
|
||||
function Notes({ text, t }: { text: string | null; t: TranslationFn }) {
|
||||
if (!text?.trim()) return null;
|
||||
return (
|
||||
<span className="block rounded-xl bg-m-ic px-3 py-2">
|
||||
<span className="flex items-center gap-1 text-caption font-semibold text-m-faint">
|
||||
<NotebookPen size={11} /> {t('collections.notes')}
|
||||
</span>
|
||||
<span dir="auto" className="mt-1 block whitespace-pre-wrap text-body text-m-ink">
|
||||
{text}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
type Entry = NonNullable<PlacesLibraryDetailResponse['entry']>;
|
||||
|
||||
/** The cover band: the picture or a gradient, the category, the close button and the name. */
|
||||
@@ -116,9 +97,12 @@ function SheetCover({
|
||||
</button>
|
||||
</div>
|
||||
{entry && (
|
||||
<h2 dir="auto" className="m-libcover-name absolute inset-x-4 bottom-3 m-0 truncate text-title font-extrabold">
|
||||
{entry.name}
|
||||
</h2>
|
||||
<div className="absolute inset-x-4 bottom-3 min-w-0">
|
||||
<h2 dir="auto" className="m-libcover-name m-0 truncate text-title font-extrabold">
|
||||
{entry.name}
|
||||
</h2>
|
||||
<PlaceLocationBadge address={entry.address} lat={entry.lat} lng={entry.lng} t={t} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -149,8 +133,12 @@ function TripCard({
|
||||
aria-label={`${t('collections.library.openTrip')}: ${originName(origin)}`}
|
||||
>
|
||||
<span className="flex items-center gap-[10px]">
|
||||
<span className={ICO}>
|
||||
<Luggage size={15} />
|
||||
<span className={`${ICO} overflow-hidden`}>
|
||||
{origin.trip_cover ? (
|
||||
<img src={origin.trip_cover} alt="" className="h-full w-full object-cover" />
|
||||
) : (
|
||||
<Luggage size={15} />
|
||||
)}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span dir="auto" className="block truncate text-body font-bold text-m-ink">
|
||||
@@ -176,7 +164,6 @@ function TripCard({
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<Notes text={detail.notes} t={t} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -205,8 +192,15 @@ function ListCard({
|
||||
aria-label={`${t('collections.library.openList')}: ${originName(origin)}`}
|
||||
>
|
||||
<span className="flex items-center gap-[10px]">
|
||||
<span className={ICO}>
|
||||
<Bookmark size={15} />
|
||||
<span
|
||||
className={ICO}
|
||||
// The list's own colour, the one data-driven value of the tile.
|
||||
style={{
|
||||
color: origin.collection_color || 'var(--m-act)',
|
||||
background: `color-mix(in srgb, ${origin.collection_color || 'var(--m-act)'} 16%, var(--m-ic))`,
|
||||
}}
|
||||
>
|
||||
{createElement(listIcon(origin.collection_icon), { size: 15 })}
|
||||
</span>
|
||||
<span dir="auto" className="min-w-0 flex-1 truncate text-body font-bold text-m-ink">
|
||||
{originName(origin)}
|
||||
@@ -236,7 +230,6 @@ function ListCard({
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<Notes text={detail.notes} t={t} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -306,21 +299,12 @@ function SheetBody({
|
||||
onOpenTrip,
|
||||
onSaveToList,
|
||||
onCopyToTrip,
|
||||
onNotesSaved,
|
||||
t,
|
||||
}: Omit<MLibraryPlaceSheetProps, 'open' | 'loading' | 'cover' | 'onClose'> & { entry: Entry }) {
|
||||
const { trips, lists, description } = originPairs(data);
|
||||
return (
|
||||
<>
|
||||
{entry.address && (
|
||||
<p dir="auto" className="m-0 flex items-center gap-1 text-caption text-m-muted">
|
||||
<MapPin size={12} className="flex-none" /> {entry.address}
|
||||
</p>
|
||||
)}
|
||||
{(entry.lat == null || entry.lng == null) && (
|
||||
<p className="m-0 mt-1 flex items-center gap-1 text-caption text-m-muted">
|
||||
<MapPinOff size={12} className="flex-none text-warning" /> {t('places.noCoordinates')}
|
||||
</p>
|
||||
)}
|
||||
{description && (
|
||||
<p dir="auto" className="m-0 mt-3 whitespace-pre-wrap text-body text-m-ink">
|
||||
{description}
|
||||
@@ -359,6 +343,12 @@ function SheetBody({
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<MEntryTagsSection data={data} onChanged={onNotesSaved} t={t} />
|
||||
<MOriginNotesSection data={data} onSaved={onNotesSaved} t={t} />
|
||||
<MPlaceMediaSection entry={entry} t={t} />
|
||||
<MVisitsSection entry={entry} language={language} t={t} />
|
||||
<MPlaceActivitiesSection entry={entry} language={language} t={t} />
|
||||
<MPlaceHistorySection entry={entry} language={language} t={t} />
|
||||
<SheetActions
|
||||
entry={entry}
|
||||
trip={trips[0]}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { PlacesLibraryDetailResponse } from '@trek/shared';
|
||||
import { Bookmark, Luggage, Pencil, Plus } from 'lucide-react';
|
||||
import { useOriginNotes } from '../../../components/Collections/useOriginNotes';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { CancelPill, Eyebrow, PrimaryPill, TEXTAREA_CLS } from './MCollSheetKit';
|
||||
|
||||
/** The notes of a place on the phone (PLC-17), each with where it comes from; the logic is the desktop sheet's. */
|
||||
export default function MOriginNotesSection({
|
||||
data,
|
||||
onSaved,
|
||||
t,
|
||||
}: {
|
||||
data: PlacesLibraryDetailResponse | null;
|
||||
onSaved: () => void;
|
||||
t: TranslationFn;
|
||||
}) {
|
||||
const n = useOriginNotes({ data, onSaved, t });
|
||||
if (n.notes.length === 0 && n.targets.length === 0) return null;
|
||||
return (
|
||||
<>
|
||||
<div className="mb-[6px] mt-4 flex items-center gap-2">
|
||||
<Eyebrow>{t('collections.notes').toUpperCase()}</Eyebrow>
|
||||
{n.targets.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={n.add}
|
||||
aria-label={t('placeNotes.add')}
|
||||
className="ms-auto flex h-7 w-7 items-center justify-center rounded-full bg-m-ic text-m-ink"
|
||||
>
|
||||
<Plus size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{n.choosing && (
|
||||
<div className="mb-2 flex flex-wrap gap-[6px]">
|
||||
{n.targets.map((target) => (
|
||||
<button
|
||||
key={target.key}
|
||||
type="button"
|
||||
onClick={() => n.edit(target)}
|
||||
className="inline-flex items-center gap-1 rounded-full border border-m-rowbr bg-m-ic px-3 py-[6px] text-caption font-semibold text-m-ink"
|
||||
>
|
||||
{target.kind === 'trip' ? <Luggage size={11} /> : <Bookmark size={11} />} {target.source}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col gap-2">
|
||||
{n.notes.map((note) => (
|
||||
<div key={note.key} className="rounded-2xl border border-m-rowbr bg-m-sheet p-3">
|
||||
<div className="flex items-center gap-[6px] text-caption font-semibold text-m-faint">
|
||||
{note.kind === 'trip' ? <Luggage size={11} /> : <Bookmark size={11} />}
|
||||
<span className="min-w-0 flex-1 truncate">{note.source}</span>
|
||||
{note.canEdit && n.editing !== note.key && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => n.edit(note)}
|
||||
aria-label={t('placeNotes.edit')}
|
||||
className="flex h-7 w-7 items-center justify-center rounded-full bg-m-ic text-m-ink"
|
||||
>
|
||||
<Pencil size={13} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{n.editing === note.key ? (
|
||||
<>
|
||||
<textarea
|
||||
rows={4}
|
||||
autoFocus
|
||||
className={`${TEXTAREA_CLS} mt-2`}
|
||||
value={n.draft}
|
||||
onChange={(e) => n.setDraft(e.target.value)}
|
||||
aria-label={t('placeNotes.fieldLabel', { source: note.source })}
|
||||
/>
|
||||
<div className="mt-2 flex gap-2">
|
||||
<CancelPill onClick={n.cancel} className="flex-1">
|
||||
{t('common.cancel')}
|
||||
</CancelPill>
|
||||
<PrimaryPill onClick={() => void n.save()} disabled={n.busy} className="flex-1">
|
||||
{t('common.save')}
|
||||
</PrimaryPill>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p dir="auto" className="m-0 mt-1 whitespace-pre-wrap text-body text-m-ink">
|
||||
{note.text}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { PlaceActivity, PlacesLibraryEntry } from '@trek/shared';
|
||||
import { ChevronRight, Plus, Route, Ticket, X } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { activityLine } from '../../../components/Collections/placeExtrasText';
|
||||
import { activityHref, usePlaceActivities } from '../../../components/Collections/usePlaceActivities';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { Eyebrow } from './MCollSheetKit';
|
||||
|
||||
const CARD = 'flex w-full items-center gap-[10px] rounded-2xl border border-m-rowbr bg-m-sheet p-3 text-start';
|
||||
const ICO = 'flex h-[34px] w-[34px] flex-none items-center justify-center rounded-[10px] bg-m-ic text-m-muted';
|
||||
|
||||
function ActivityIcon({ type }: { type: PlaceActivity['type'] }) {
|
||||
return type === 'booking' ? <Ticket size={15} /> : <Route size={15} />;
|
||||
}
|
||||
|
||||
/** The tours and bookings of a place on the phone (PLC-18); the logic is the desktop sheet's. */
|
||||
export default function MPlaceActivitiesSection({
|
||||
entry,
|
||||
language,
|
||||
t,
|
||||
}: {
|
||||
entry: PlacesLibraryEntry;
|
||||
language: string;
|
||||
t: TranslationFn;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const a = usePlaceActivities({ entry, t });
|
||||
if (a.activities.length === 0 && !a.canLink) return null;
|
||||
return (
|
||||
<>
|
||||
<div className="mb-[6px] mt-4 flex items-center gap-2">
|
||||
<Eyebrow>{t('placeActivities.title').toUpperCase()}</Eyebrow>
|
||||
{a.canLink && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => (a.picking ? a.closePicker() : void a.openPicker())}
|
||||
disabled={a.busy}
|
||||
aria-label={a.picking ? t('common.close') : t('placeActivities.link')}
|
||||
className="ms-auto flex h-7 w-7 items-center justify-center rounded-full bg-m-ic text-m-ink disabled:opacity-50"
|
||||
>
|
||||
{a.picking ? <X size={14} /> : <Plus size={14} />}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
{a.activities.map((act) => (
|
||||
<div key={`${act.key}:${act.source.kind}`} className={CARD}>
|
||||
<span className={ICO}>
|
||||
<ActivityIcon type={act.type} />
|
||||
</span>
|
||||
<button type="button" onClick={() => navigate(activityHref(act))} className="min-w-0 flex-1 text-start">
|
||||
<span className="block truncate text-body font-bold text-m-ink">{act.title}</span>
|
||||
<span className="block truncate text-caption text-m-muted">{activityLine(act, language, t)}</span>
|
||||
</button>
|
||||
{act.can_unlink ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void a.unlink(act)}
|
||||
disabled={a.busy}
|
||||
aria-label={t('placeActivities.unlink')}
|
||||
className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-m-ic text-m-muted"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
) : (
|
||||
<ChevronRight size={16} className="flex-none text-m-faint rtl:-scale-x-100" />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{a.activities.length === 0 && !a.picking && (
|
||||
<p className="m-0 text-caption text-m-muted">{t('placeActivities.none')}</p>
|
||||
)}
|
||||
{a.picking && (
|
||||
<div className="rounded-2xl border border-m-rowbr bg-m-sheetop p-2">
|
||||
{a.picking.every((g) => g.candidates.length === 0) && (
|
||||
<p className="m-0 p-2 text-caption text-m-muted">{t('placeActivities.nothingToLink')}</p>
|
||||
)}
|
||||
{a.picking.map((g) =>
|
||||
g.candidates.map((c) => (
|
||||
<button
|
||||
key={`${g.source.origin.kind}:${c.key}`}
|
||||
type="button"
|
||||
disabled={a.busy}
|
||||
onClick={() => void a.link(g.source, c)}
|
||||
className="flex w-full items-center gap-[10px] rounded-xl p-2 text-start disabled:opacity-50"
|
||||
>
|
||||
<span className={ICO}>
|
||||
<ActivityIcon type={c.type} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-body font-semibold text-m-ink">{c.title}</span>
|
||||
<span className="block truncate text-caption text-m-muted">{activityLine(c, language, t)}</span>
|
||||
</span>
|
||||
<Plus size={15} className="flex-none text-m-muted" />
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { PlacesLibraryEntry } from '@trek/shared';
|
||||
import { ArrowRight } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { historyLine, historyMeta } from '../../../components/Collections/placeExtrasText';
|
||||
import { usePlaceHistory } from '../../../components/Collections/usePlaceHistory';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { Eyebrow } from './MCollSheetKit';
|
||||
|
||||
/** How many changes show before "show all" opens the rest. */
|
||||
const FOLDED = 3;
|
||||
|
||||
/** The change history of a place on the phone (PLC-14); the logic is the desktop sheet's. */
|
||||
export default function MPlaceHistorySection({
|
||||
entry,
|
||||
language,
|
||||
t,
|
||||
}: {
|
||||
entry: PlacesLibraryEntry;
|
||||
language: string;
|
||||
t: TranslationFn;
|
||||
}) {
|
||||
const h = usePlaceHistory(entry);
|
||||
const [open, setOpen] = useState(false);
|
||||
if (h.entries.length === 0) return null;
|
||||
const shown = open ? h.entries : h.entries.slice(0, FOLDED);
|
||||
return (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-4">{t('placeHistory.title').toUpperCase()}</Eyebrow>
|
||||
<ol className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{shown.map((e) => {
|
||||
const line = historyLine(e, t);
|
||||
return (
|
||||
<li key={e.id} className="border-s-2 border-m-rowbr ps-3">
|
||||
<span className="block text-body text-m-ink">
|
||||
<strong className="font-semibold">{line.field}</strong>
|
||||
{(line.from || line.to) && (
|
||||
<span className="text-m-muted">
|
||||
{': '}
|
||||
{line.from && <span className="line-through">{line.from}</span>}
|
||||
{line.from && line.to && <ArrowRight size={11} className="mx-1 inline align-[-1px]" />}
|
||||
{line.to && <span className="text-m-ink">{line.to}</span>}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="block text-caption text-m-faint">{historyMeta(e, t, language)}</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
{(open ? h.hasMore : h.entries.length > FOLDED || h.hasMore) && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={h.loadingMore}
|
||||
onClick={() => (open ? void h.more() : setOpen(true))}
|
||||
className="mt-2 text-caption font-semibold text-m-muted"
|
||||
>
|
||||
{open ? t('placeHistory.more') : t('placeHistory.showAll')}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { PlacesLibraryEntry } from '@trek/shared';
|
||||
import { ChevronRight, FileText } from 'lucide-react';
|
||||
import { usePlaceMedia } from '../../../components/Collections/usePlaceMedia';
|
||||
import PhotoLightbox from '../../../components/Journey/PhotoLightbox';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { Eyebrow } from './MCollSheetKit';
|
||||
|
||||
/** How many pictures the phone's row shows before it counts the rest on the last one. */
|
||||
const SHOWN = 6;
|
||||
|
||||
/** The pictures and trip files of a place on the phone (PLC-19, PLC-20); the logic is the desktop sheet's. */
|
||||
export default function MPlaceMediaSection({ entry, t }: { entry: PlacesLibraryEntry; t: TranslationFn }) {
|
||||
const m = usePlaceMedia(entry);
|
||||
if (m.photos.length === 0 && m.files.length === 0) return null;
|
||||
const rest = m.photos.length - SHOWN;
|
||||
return (
|
||||
<>
|
||||
{m.photos.length > 0 && (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-4">{t('places.media.photos').toUpperCase()}</Eyebrow>
|
||||
<div className="grid grid-cols-3 gap-[6px]">
|
||||
{m.photos.slice(0, SHOWN).map((p, i) => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
onClick={() => m.setOpen(i)}
|
||||
className="relative aspect-square overflow-hidden rounded-xl bg-m-ic"
|
||||
aria-label={p.caption}
|
||||
>
|
||||
<img src={p.thumbSrc} alt="" loading="lazy" className="h-full w-full object-cover" />
|
||||
{i === SHOWN - 1 && rest > 0 && (
|
||||
<>
|
||||
<span className="absolute inset-0 bg-m-sheet opacity-75" />
|
||||
<span className="absolute inset-0 grid place-items-center text-body font-bold text-m-ink">
|
||||
+{rest}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{m.files.length > 0 && (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-4">{t('places.media.files').toUpperCase()}</Eyebrow>
|
||||
<div className="flex flex-col gap-2">
|
||||
{m.files.map((f) => (
|
||||
<a
|
||||
key={f.file_id}
|
||||
href={f.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-[10px] rounded-2xl border border-m-rowbr bg-m-sheet p-3"
|
||||
>
|
||||
<span className="flex h-[34px] w-[34px] flex-none items-center justify-center rounded-[10px] bg-m-ic text-m-muted">
|
||||
<FileText size={15} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span dir="auto" className="block truncate text-body font-bold text-m-ink">
|
||||
{f.original_name}
|
||||
</span>
|
||||
<span className="block truncate text-caption text-m-muted">{f.trip_title}</span>
|
||||
</span>
|
||||
<ChevronRight size={16} className="flex-none text-m-faint rtl:-scale-x-100" />
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{m.open !== null && (
|
||||
<PhotoLightbox
|
||||
photos={m.photos.map((p) => ({
|
||||
id: p.id,
|
||||
src: p.src,
|
||||
thumbSrc: p.thumbSrc,
|
||||
caption: p.caption,
|
||||
provider: p.provider,
|
||||
mediaType: p.mediaType,
|
||||
}))}
|
||||
startIndex={m.open}
|
||||
onClose={m.close}
|
||||
label={entry.name}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
import type { CollectionPlace, CollectionStatus, PlacesLibraryEntry, PlacesLibrarySort } from '@trek/shared';
|
||||
import type {
|
||||
CollectionPlace,
|
||||
CollectionStatus,
|
||||
PlacesLibraryEntry,
|
||||
PlacesLibrarySort,
|
||||
Tag as TagRow,
|
||||
} from '@trek/shared';
|
||||
import {
|
||||
ArrowDownUp,
|
||||
Bookmark,
|
||||
@@ -13,13 +19,17 @@ import {
|
||||
MapPin,
|
||||
Search,
|
||||
Shapes,
|
||||
Tag,
|
||||
} from 'lucide-react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import CollectionMap from '../../../components/Collections/CollectionMap';
|
||||
import { saveDraftOf } from '../../../components/Collections/libraryPairs';
|
||||
import EntryTagDots from '../../../components/Collections/EntryTagDots';
|
||||
import { libraryCarryOptions, saveDraftOf } from '../../../components/Collections/libraryPairs';
|
||||
import { originName } from '../../../components/Collections/originName';
|
||||
import { usePersonalTags } from '../../../components/Collections/useEntryTags';
|
||||
import { usePlaceDuplicates } from '../../../components/Collections/usePlaceDuplicates';
|
||||
import { usePlacesLibrary, type LibraryKindFilter } from '../../../components/Collections/usePlacesLibrary';
|
||||
import VisitedMark from '../../../components/Collections/VisitedMark';
|
||||
import { STATUS_ORDER } from '../../../pages/collections/collectionsModel';
|
||||
import { useCollectionStore } from '../../../store/collectionStore';
|
||||
import { useSaveToCollectionStore } from '../../../store/saveToCollectionStore';
|
||||
@@ -42,7 +52,7 @@ interface MPlacesLibraryProps {
|
||||
t: TranslationFn;
|
||||
}
|
||||
|
||||
type Drop = 'kind' | 'status' | 'category' | 'sort';
|
||||
type Drop = 'kind' | 'status' | 'category' | 'tags' | 'sort';
|
||||
|
||||
/** A map point per entry with a position; the map speaks CollectionPlace, keyed by a running id. */
|
||||
function toMapPlaces(entries: PlacesLibraryEntry[]) {
|
||||
@@ -88,8 +98,12 @@ function Row({ entry, onOpen, t }: { entry: PlacesLibraryEntry; onOpen: () => vo
|
||||
<Icon size={17} strokeWidth={2.2} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span dir="auto" className="block truncate text-body font-bold text-m-ink">
|
||||
{entry.name}
|
||||
<span className="flex min-w-0 items-center gap-1">
|
||||
<span dir="auto" className="truncate text-body font-bold text-m-ink">
|
||||
{entry.name}
|
||||
</span>
|
||||
<VisitedMark count={entry.visit_count} t={t} />
|
||||
<EntryTagDots tags={entry.tags} />
|
||||
</span>
|
||||
{entry.address && (
|
||||
<span className="mt-[2px] flex items-center gap-[3px] truncate text-caption text-m-muted">
|
||||
@@ -126,6 +140,7 @@ function FilterDrop({
|
||||
drop,
|
||||
lib,
|
||||
categories,
|
||||
personalTags,
|
||||
kindLabel,
|
||||
pick,
|
||||
t,
|
||||
@@ -133,6 +148,7 @@ function FilterDrop({
|
||||
drop: Drop;
|
||||
lib: Library;
|
||||
categories: Category[];
|
||||
personalTags: readonly TagRow[];
|
||||
kindLabel: (k: LibraryKindFilter) => string;
|
||||
pick: (fn: () => void) => void;
|
||||
t: TranslationFn;
|
||||
@@ -204,6 +220,22 @@ function FilterDrop({
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
{drop === 'tags' &&
|
||||
personalTags.map((tag) => (
|
||||
<DropRow
|
||||
key={tag.id}
|
||||
icon={
|
||||
// The tag's own colour, the one data-driven value of the row.
|
||||
<span
|
||||
className="h-2.5 w-2.5 flex-none rounded-full"
|
||||
style={{ background: tag.color || 'var(--m-act)' }}
|
||||
/>
|
||||
}
|
||||
label={String(tag.name)}
|
||||
on={lib.tagIds.includes(tag.id)}
|
||||
onPick={() => lib.toggleTag(tag.id)}
|
||||
/>
|
||||
))}
|
||||
{drop === 'sort' &&
|
||||
(['name', 'updated'] as PlacesLibrarySort[]).map((s) => (
|
||||
<DropRow
|
||||
@@ -286,12 +318,14 @@ function Results({
|
||||
*/
|
||||
export default function MPlacesLibrary({ categories, language, dark, view, onView, navigate, t }: MPlacesLibraryProps) {
|
||||
const lib = usePlacesLibrary({ active: true, t });
|
||||
const personalTags = usePersonalTags();
|
||||
const dup = usePlaceDuplicates({ active: true, onChanged: lib.reload, t });
|
||||
const [showDup, setShowDup] = useState(false);
|
||||
const openSave = useSaveToCollectionStore((s) => s.open);
|
||||
const copyToTrip = useCollectionStore((s) => s.copyToTrip);
|
||||
const [drop, setDrop] = useState<Drop | null>(null);
|
||||
const [copyId, setCopyId] = useState<number | null>(null);
|
||||
const [copyCarry, setCopyCarry] = useState<ReturnType<typeof libraryCarryOptions>>(undefined);
|
||||
const map = useMemo(() => toMapPlaces(lib.entries), [lib.entries]);
|
||||
|
||||
const kindLabel = (k: LibraryKindFilter) =>
|
||||
@@ -377,6 +411,18 @@ export default function MPlacesLibrary({ categories, language, dark, view, onVie
|
||||
<ChevronDown size={12} strokeWidth={2} className="flex-none" />
|
||||
</button>
|
||||
)}
|
||||
{personalTags.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDrop((d) => (d === 'tags' ? null : 'tags'))}
|
||||
aria-expanded={drop === 'tags'}
|
||||
aria-label={t('placeTags.title')}
|
||||
className={`${chip(lib.tagIds.length > 0)} !flex-none px-3`}
|
||||
>
|
||||
<Tag size={13} strokeWidth={2} className="flex-none" />
|
||||
{lib.tagIds.length > 0 && <span>{lib.tagIds.length}</span>}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDrop((d) => (d === 'sort' ? null : 'sort'))}
|
||||
@@ -414,7 +460,15 @@ export default function MPlacesLibrary({ categories, language, dark, view, onVie
|
||||
<div
|
||||
className={`absolute inset-x-0 top-[calc(100%+6px)] z-20 max-h-[300px] overflow-y-auto p-[6px] ${DROP_PANEL}`}
|
||||
>
|
||||
<FilterDrop drop={drop} lib={lib} categories={categories} kindLabel={kindLabel} pick={pick} t={t} />
|
||||
<FilterDrop
|
||||
drop={drop}
|
||||
lib={lib}
|
||||
categories={categories}
|
||||
personalTags={personalTags}
|
||||
kindLabel={kindLabel}
|
||||
pick={pick}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -425,6 +479,7 @@ export default function MPlacesLibrary({ categories, language, dark, view, onVie
|
||||
open={lib.selectedKey != null}
|
||||
data={lib.detail}
|
||||
loading={lib.detailLoading}
|
||||
onNotesSaved={lib.reload}
|
||||
cover={lib.cover}
|
||||
language={language}
|
||||
onClose={lib.close}
|
||||
@@ -432,6 +487,8 @@ export default function MPlacesLibrary({ categories, language, dark, view, onVie
|
||||
onOpenTrip={(tripId, placeId) => navigate(`/trips/${tripId}?place=${placeId}`)}
|
||||
onSaveToList={(origin, d) => openSave(saveDraftOf(origin, d, lib.detail?.entry.category?.id))}
|
||||
onCopyToTrip={(id) => {
|
||||
// Read now: the sheet closes, and its place with it.
|
||||
setCopyCarry(libraryCarryOptions(lib.detail, id));
|
||||
lib.close();
|
||||
setCopyId(id);
|
||||
}}
|
||||
@@ -439,9 +496,15 @@ export default function MPlacesLibrary({ categories, language, dark, view, onVie
|
||||
/>
|
||||
<MDuplicatesSheet open={showDup} d={dup} onClose={() => setShowDup(false)} t={t} />
|
||||
<MCollTripPickerSheet
|
||||
carryOptions={copyCarry}
|
||||
open={copyId != null}
|
||||
count={1}
|
||||
onCopy={(tripId, carry) => copyToTrip(tripId, copyId != null ? [copyId] : [], undefined, carry)}
|
||||
onCopy={(tripId, carry) =>
|
||||
copyToTrip(tripId, copyId != null ? [copyId] : [], undefined, carry).then((res) => {
|
||||
lib.reload();
|
||||
return res;
|
||||
})
|
||||
}
|
||||
onClose={() => setCopyId(null)}
|
||||
t={t}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { PlacesLibraryEntry } from '@trek/shared';
|
||||
import { CalendarCheck } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
import { visitDate } from '../../../components/Collections/libraryDates';
|
||||
import { tripPlaceEntry, usePlaceVisits } from '../../../components/Collections/usePlaceVisits';
|
||||
import { Avatar } from '../../../components/Planner/TravelerPicker';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { Eyebrow } from './MCollSheetKit';
|
||||
|
||||
const CARD = 'flex w-full items-center gap-[10px] rounded-2xl border border-m-rowbr bg-m-sheet p-3';
|
||||
const ICO = 'flex h-[34px] w-[34px] flex-none items-center justify-center rounded-[10px] bg-m-ic text-m-muted';
|
||||
|
||||
/**
|
||||
* When the reader was at a place of All places on the phone (PLC-10): every past
|
||||
* day of a trip it was planned on. Not there at all without a visit.
|
||||
*/
|
||||
export default function MVisitsSection({
|
||||
entry,
|
||||
language,
|
||||
t,
|
||||
}: {
|
||||
entry: PlacesLibraryEntry;
|
||||
language: string;
|
||||
t: TranslationFn;
|
||||
}) {
|
||||
const v = usePlaceVisits({ entry });
|
||||
const last = visitDate(v.lastVisit, null, language);
|
||||
if (v.count === 0 || !last) return null;
|
||||
return (
|
||||
<>
|
||||
<div className="mb-[6px] mt-4 flex items-baseline gap-2">
|
||||
<Eyebrow>{t('visits.title').toUpperCase()}</Eyebrow>
|
||||
<span className="ms-auto truncate text-caption text-m-muted">
|
||||
{t('visits.summary', { count: v.count, date: last })}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
{v.visits.map((visit) => (
|
||||
<div key={`${visit.trip.id}:${visit.day_id}:${visit.place_id}`} className={CARD}>
|
||||
<span className={ICO}>
|
||||
<CalendarCheck size={15} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-body font-bold text-m-ink">
|
||||
{visitDate(visit.visited_on, visit.visited_time, language)}
|
||||
</span>
|
||||
<span className="block truncate text-caption text-m-muted">{visit.trip.title}</span>
|
||||
</span>
|
||||
{visit.participants.length > 1 && (
|
||||
<span className="flex flex-none">
|
||||
{visit.participants.slice(0, 3).map((p, i) => (
|
||||
<span key={p.id} className={i ? '-ms-1.5 flex rounded-full ring-2 ring-m-sheet' : 'flex'}>
|
||||
<Avatar userId={p.id} username={p.username} avatarUrl={p.avatar_url} size={20} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** A trip place's visits on the phone's place sheet: how often and when last; not shown before the first one. */
|
||||
export function MTripPlaceVisits({
|
||||
trip,
|
||||
place,
|
||||
language,
|
||||
t,
|
||||
}: {
|
||||
trip: { id: number; title: string; start_date?: string | null; end_date?: string | null };
|
||||
place: { id: number; name: string; address?: string | null; lat?: number | null; lng?: number | null };
|
||||
language: string;
|
||||
t: TranslationFn;
|
||||
}) {
|
||||
const entry = useMemo(() => tripPlaceEntry(trip, place), [trip, place]);
|
||||
const v = usePlaceVisits({ entry });
|
||||
const last = visitDate(v.lastVisit, null, language);
|
||||
if (v.count === 0 || !last) return null;
|
||||
return (
|
||||
<div className="mt-3 flex items-center gap-[10px] rounded-[13px] border border-m-inbr bg-m-inner px-3 py-[9px]">
|
||||
<CalendarCheck size={15} className="flex-none text-success" />
|
||||
<span className="min-w-0 flex-1 truncate text-body text-m-ink">
|
||||
{t('visits.summary', { count: v.count, date: last })}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import { MapCompassPill, type CompassMap } from '../../../../components/Map/MapC
|
||||
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 { TripListsPill } from '../../../../components/Collections/TripListsPill'
|
||||
import { useTripLists } from '../../../../components/Collections/useTripLists'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import { DawarichTrailPill } from '../../../../components/Map/DawarichTrailPill'
|
||||
import PoiCategoryPill from '../../../../components/Map/PoiCategoryPill'
|
||||
import { usePoiExplore } from '../../../../components/Map/usePoiExplore'
|
||||
@@ -342,11 +345,23 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
return vias.filter(v => !v.nightPause || v.nightPause.day === stage.dayNumber)
|
||||
}, [onStage, planner.roadtripMapVias, planner.routeVias, stage])
|
||||
|
||||
const pois = useMergedMapPois(
|
||||
const merged = useMergedMapPois(
|
||||
onStage ? planner.roadtripCorridor.visible : null,
|
||||
onStage ? NO_POIS : poi.pois,
|
||||
planner.refuel.offered,
|
||||
)
|
||||
// PLC-15/16: the lists the trip draws on, their places as pins beside the POIs.
|
||||
const { t } = useTranslation()
|
||||
const lists = useTripLists({ tripId: Number(planner.tripId), canEdit: planner.can('place_edit', planner.trip), t })
|
||||
const pois = useMemo(() => (lists.pois.length ? [...merged, ...lists.pois] : merged), [merged, lists.pois])
|
||||
const { claim } = lists
|
||||
const { handlePoiClick, openAddPlaceFromPoi, selectedDayId } = planner
|
||||
// Stable, so neither renderer rebuilds every POI pin on each render.
|
||||
const onPoiClick = useCallback((marker: Poi) => {
|
||||
if (claim(marker)) return
|
||||
if (onStage) handlePoiClick(marker)
|
||||
else openAddPlaceFromPoi(marker, selectedDayId)
|
||||
}, [claim, onStage, handlePoiClick, openAddPlaceFromPoi, selectedDayId])
|
||||
|
||||
return (
|
||||
// `isolate` keeps the map's internal z-indexes (Leaflet panes, the z-1000
|
||||
@@ -443,9 +458,7 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
// the distance it carries and sends it to the draft sheet with the stop kind, the
|
||||
// stay and the position in the chain already worked out. The plan tab has no
|
||||
// chain to place anything in, so there it stays the plain place form.
|
||||
onPoiClick={onStage
|
||||
? planner.handlePoiClick
|
||||
: marker => planner.openAddPlaceFromPoi(marker, planner.selectedDayId)}
|
||||
onPoiClick={onPoiClick}
|
||||
onViewportChange={onViewportChange}
|
||||
onMapReady={setGlMap}
|
||||
// Other ways of driving the leg the stage asked about, and the one lit up.
|
||||
@@ -539,6 +552,7 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
{!planner.roadtripActive && (
|
||||
<TripRouteOverviewPill active={planner.overviewShown} onToggle={planner.toggleOverview} />
|
||||
)}
|
||||
<TripListsPill lists={lists} t={t} />
|
||||
<PlaceNamesPill />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useTripVisitedIds } from '../../../../hooks/useTripVisitedIds'
|
||||
import { ReactNode, useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
Bookmark, CheckCheck, CheckCircle2, Download, ListChecks, Loader2, MapPinOff, Plus,
|
||||
@@ -76,14 +77,15 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
|
||||
|
||||
// A hotel is linked through its stay and a venue through its booking; neither is
|
||||
// ever dragged onto a day, and the pool used to call both unplanned (#2072).
|
||||
const visitedIds = useTripVisitedIds(tripId)
|
||||
const plannedIds = useMemo(
|
||||
() => plannedPlaceIds(assignments, planner.tripAccommodations, planner.reservations),
|
||||
[assignments, planner.tripAccommodations, planner.reservations],
|
||||
)
|
||||
const dayNumberByPlace = useMemo(() => firstPlannedDayNumbers(assignments, days), [assignments, days])
|
||||
const filtered = useMemo(() => {
|
||||
return filterPool(poolPlaces, { filter, categoryFilters, ratingFilter, search, plannedIds })
|
||||
}, [poolPlaces, filter, categoryFilters, ratingFilter, search, plannedIds])
|
||||
return filterPool(poolPlaces, { filter, categoryFilters, ratingFilter, search, plannedIds, visitedIds })
|
||||
}, [poolPlaces, filter, categoryFilters, ratingFilter, search, plannedIds, visitedIds])
|
||||
|
||||
// Compare the ids, not just the counts: a place removed remotely while another
|
||||
// one is selected keeps the sizes equal without the sets matching.
|
||||
@@ -159,6 +161,13 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
|
||||
label={t('places.planned')}
|
||||
onClick={() => pickFilter('planned')}
|
||||
/>
|
||||
{(visitedIds.size > 0 || filter === 'visited') && (
|
||||
<FilterChip
|
||||
active={filter === 'visited'}
|
||||
label={t('places.filterVisited')}
|
||||
onClick={() => pickFilter('visited')}
|
||||
/>
|
||||
)}
|
||||
{hasTracks && (
|
||||
<FilterChip
|
||||
active={filter === 'tracks'}
|
||||
|
||||
@@ -54,8 +54,10 @@ interface PoolFilterArgs {
|
||||
ratingFilter?: PlacesRatingFloor
|
||||
search: string
|
||||
plannedIds: Set<number>
|
||||
/** The trip's places the reader visited, for the "visited" choice (PLC-23). */
|
||||
visitedIds?: ReadonlySet<number>
|
||||
}
|
||||
|
||||
export function filterPool(places: Place[], { filter, categoryFilters, ratingFilter = 'all', search, plannedIds }: PoolFilterArgs): Place[] {
|
||||
return places.filter(p => matchesPlacesFilter(p, { filter, categoryFilters, ratingFilter }, { plannedIds }) && matchesSearch(p, search))
|
||||
export function filterPool(places: Place[], { filter, categoryFilters, ratingFilter = 'all', search, plannedIds, visitedIds }: PoolFilterArgs): Place[] {
|
||||
return places.filter(p => matchesPlacesFilter(p, { filter, categoryFilters, ratingFilter }, { plannedIds, visitedIds }) && matchesSearch(p, search))
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import { resolveTrackColor, inheritedTrackColor } from '../../../../components/M
|
||||
import { avatarSrc } from '../../../../utils/avatarSrc'
|
||||
import { safeHttpUrl } from '../../../../utils/safeUrl'
|
||||
import { openFile } from '../../../../utils/fileDownload'
|
||||
import { MTripPlaceVisits } from '../../collections/MVisitsSection'
|
||||
import { filesForPlace } from '../../../../utils/placeFiles'
|
||||
import { navigationTargetLabel, getNavigationTargets, openNavigationTarget } from '../../../../components/Planner/placeNavigation'
|
||||
import { addressWithoutCoordinates } from '../../../../components/Planner/placeCoordinates'
|
||||
@@ -543,6 +544,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
</>
|
||||
)}
|
||||
|
||||
{planner.trip && <MTripPlaceVisits trip={planner.trip} place={place} language={language} t={t} />}
|
||||
{/* ── Files ── */}
|
||||
<div className={`mt-3 rounded-[13px] px-3 py-[9px] ${INNER_CLS}`}>
|
||||
<div
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Dispatch, ReactElement, Ref, SetStateAction } from 'react'
|
||||
import { useCallback, useMemo, type Dispatch, type ReactElement, type Ref, type SetStateAction } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { MapViewAuto as MapView } from '../../components/Map/MapViewAuto'
|
||||
import { MapCompassPill, type CompassMap } from '../../components/Map/MapCompassPill'
|
||||
@@ -6,6 +6,9 @@ import { TripRouteOverviewPill, TripRouteOverviewPanel, TRIP_OVERVIEW_INSET } fr
|
||||
import { PlaceNamesPill } from '../../components/Map/PlaceNamesPill'
|
||||
import { DawarichTrailPill } from '../../components/Map/DawarichTrailPill'
|
||||
import PoiCategoryPill from '../../components/Map/PoiCategoryPill'
|
||||
import { TripListsPill } from '../../components/Collections/TripListsPill'
|
||||
import { useTripLists } from '../../components/Collections/useTripLists'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import ActivityCompareLegend from '../../components/Tours/activity/ActivityCompareLegend'
|
||||
import { useActivityCompareMap } from '../../components/Tours/activity/useActivityCompareMap'
|
||||
import type { Poi } from '../../components/Map/poiCategories'
|
||||
@@ -84,6 +87,15 @@ export function PlanMapStage({
|
||||
enabled: !roadtripActive && !overviewActive && !isMobile,
|
||||
places, mapPlaces, route, routeWalking, selectedPlaceId,
|
||||
})
|
||||
const { t } = useTranslation()
|
||||
// PLC-15/16: the lists the trip draws on, their places as pins beside the POIs.
|
||||
const lists = useTripLists({ tripId: Number(tripId), canEdit: can('place_edit', trip), t })
|
||||
const stagePois = useMemo(() => (lists.pois.length ? [...mapPois, ...lists.pois] : mapPois), [mapPois, lists.pois])
|
||||
// Stable, as handlePoiClick is: both renderers rebuild every POI pin when it changes.
|
||||
const { claim } = lists
|
||||
const onPoiClick = useCallback((poi: Poi) => {
|
||||
if (!claim(poi)) handlePoiClick(poi)
|
||||
}, [claim, handlePoiClick])
|
||||
return (
|
||||
<>
|
||||
<MapView
|
||||
@@ -139,8 +151,8 @@ export function PlanMapStage({
|
||||
the picture of that very list, and filtering the list while seventy pins stay
|
||||
on the map no longer answers "which of these") plus whatever the category
|
||||
pill found in view. Outside it, only the pill's hits. */
|
||||
pois={mapPois}
|
||||
onPoiClick={handlePoiClick}
|
||||
pois={stagePois}
|
||||
onPoiClick={onPoiClick}
|
||||
// Only while road trip mode is on: outside it there is no drive to drop onto.
|
||||
onPoiDropOnRoute={roadtripActive ? dropPoiOnRoute : undefined}
|
||||
// Clicking the drawn route puts a via there; only in road trip mode, where
|
||||
@@ -200,6 +212,7 @@ export function PlanMapStage({
|
||||
{!roadtripActive && (
|
||||
<TripRouteOverviewPill active={overviewShown} onToggle={toggleOverview} />
|
||||
)}
|
||||
<TripListsPill lists={lists} t={t} />
|
||||
<PlaceNamesPill />
|
||||
{/* Stays in road-trip mode, unlike the overview: the route that was
|
||||
actually driven is the thing you most want beside the planned
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useTripStore, type TripStoreState } from '../../store/tripStore'
|
||||
import type { Accommodation, Place } from '../../types'
|
||||
import { pendingStayPlaceIds } from '../../utils/pendingStays'
|
||||
import { useTripVisitedIds } from '../../hooks/useTripVisitedIds'
|
||||
import { matchesPlacesFilter } from '../../utils/placesFilter'
|
||||
import { plannedPlaceIds, plannedPlaceIdsForDay } from '../../utils/plannedPlaces'
|
||||
|
||||
@@ -39,6 +40,7 @@ export function useMapPlaces(options: MapPlacesOptions) {
|
||||
const placesFilter = useTripStore((s) => s.placesFilter)
|
||||
const placesCategoryFilter = useTripStore((s) => s.placesCategoryFilter)
|
||||
const placesRatingFilter = useTripStore((s) => s.placesRatingFilter)
|
||||
const visitedIds = useTripVisitedIds(placesFilter === 'visited' ? options.tripId : null)
|
||||
|
||||
const [expandedDayIds, setExpandedDayIds] = useState<Set<number> | null>(null)
|
||||
|
||||
@@ -86,14 +88,14 @@ export function useMapPlaces(options: MapPlacesOptions) {
|
||||
// must not drop its planned places.
|
||||
if (placesFilter !== 'planned' && hiddenPlaceIds.has(p.id)) return false
|
||||
// Pool, categories and rating floor: the very matcher the lists use (#1541).
|
||||
return matchesPlacesFilter(p, filterState, { plannedIds })
|
||||
return matchesPlacesFilter(p, filterState, { plannedIds, visitedIds })
|
||||
}).map(p => {
|
||||
// How the map tells a place apart (#2024, #2281); untouched places keep their identity.
|
||||
const compact = !!compactIds && !compactIds.has(p.id)
|
||||
const pending = pendingIds.has(p.id)
|
||||
return compact || pending ? { ...p, _compact: compact, _pending: pending } : p
|
||||
})
|
||||
}, [places, placesCategoryFilter, placesFilter, placesRatingFilter, assignments, expandedDayIds, selectedDayId, days, tripAccommodations, reservations, compactUnplanned, hideTours, hiddenTourIds])
|
||||
}, [places, placesCategoryFilter, placesFilter, placesRatingFilter, visitedIds, assignments, expandedDayIds, selectedDayId, days, tripAccommodations, reservations, compactUnplanned, hideTours, hiddenTourIds])
|
||||
|
||||
// The "Tracks" pool is only offered while a place carries a track. When the last
|
||||
// one goes (deleted here or by a collaborator), fall back to "all". That happens here
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import type {
|
||||
PlaceActivitiesResponse,
|
||||
PlaceActivity,
|
||||
PlaceActivityCandidatesResponse,
|
||||
PlaceLibraryActivitiesResponse,
|
||||
PlacesLibraryKind,
|
||||
TripPlaceActivityLinkRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { placeActivitiesApi } from '../api/placeActivities';
|
||||
import { requireOnline } from './onlineOnly';
|
||||
|
||||
/**
|
||||
* The bookings and tours a place is about (PLC-18). Online only on purpose:
|
||||
* what each person sees is the server's answer for their rights (Tours on
|
||||
* for the trip, their role on the list), and All places is online only.
|
||||
*/
|
||||
export const placeActivitiesRepo = {
|
||||
async tripPlace(tripId: number, placeId: number, signal?: AbortSignal): Promise<PlaceActivitiesResponse> {
|
||||
requireOnline();
|
||||
return await placeActivitiesApi.tripPlace(tripId, placeId, signal);
|
||||
},
|
||||
|
||||
async tripCandidates(
|
||||
tripId: number,
|
||||
placeId: number,
|
||||
signal?: AbortSignal
|
||||
): Promise<PlaceActivityCandidatesResponse> {
|
||||
requireOnline();
|
||||
return await placeActivitiesApi.tripCandidates(tripId, placeId, signal);
|
||||
},
|
||||
|
||||
async linkTrip(
|
||||
tripId: number,
|
||||
placeId: number,
|
||||
body: TripPlaceActivityLinkRequest
|
||||
): Promise<PlaceActivitiesResponse> {
|
||||
requireOnline();
|
||||
return await placeActivitiesApi.linkTrip(tripId, placeId, body);
|
||||
},
|
||||
|
||||
async savedPlace(collectionPlaceId: number, signal?: AbortSignal): Promise<PlaceActivitiesResponse> {
|
||||
requireOnline();
|
||||
return await placeActivitiesApi.savedPlace(collectionPlaceId, signal);
|
||||
},
|
||||
|
||||
async savedCandidates(collectionPlaceId: number, signal?: AbortSignal): Promise<PlaceActivityCandidatesResponse> {
|
||||
requireOnline();
|
||||
return await placeActivitiesApi.savedCandidates(collectionPlaceId, signal);
|
||||
},
|
||||
|
||||
async linkSaved(collectionPlaceId: number, collectionTourId: number): Promise<PlaceActivitiesResponse> {
|
||||
requireOnline();
|
||||
return await placeActivitiesApi.linkSaved(collectionPlaceId, collectionTourId);
|
||||
},
|
||||
|
||||
/**
|
||||
* Takes the link of an activity off its place, through the route its
|
||||
* source and target name: a trip place's booking or tour, a saved place's
|
||||
* kept tour. Something that belongs to the place by itself has no link to take.
|
||||
*/
|
||||
async unlink(activity: Pick<PlaceActivity, 'source' | 'target'>): Promise<PlaceActivitiesResponse> {
|
||||
requireOnline();
|
||||
const { source, target } = activity;
|
||||
if (source.kind === 'list') {
|
||||
if (target.kind !== 'collection_tour') throw new Error('A saved place only links kept tours');
|
||||
return await placeActivitiesApi.unlinkSaved(source.collection_place_id, target.collection_tour_id);
|
||||
}
|
||||
if (target.kind === 'reservation') {
|
||||
return await placeActivitiesApi.unlinkTripBooking(source.trip_id, source.place_id, target.reservation_id);
|
||||
}
|
||||
if (target.kind === 'tour') {
|
||||
return await placeActivitiesApi.unlinkTripTour(source.trip_id, source.place_id, target.tour_id);
|
||||
}
|
||||
throw new Error('A trip place only links bookings and tours of its trip');
|
||||
},
|
||||
|
||||
async libraryEntry(
|
||||
kind: PlacesLibraryKind,
|
||||
id: number,
|
||||
signal?: AbortSignal
|
||||
): Promise<PlaceLibraryActivitiesResponse> {
|
||||
requireOnline();
|
||||
return await placeActivitiesApi.libraryEntry(kind, id, signal);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { PlaceHistoryPageResponse, PlaceHistoryQueryInput, PlacesLibraryKind } from '@trek/shared';
|
||||
import { placeHistoryApi } from '../api/placeHistory';
|
||||
import { requireOnline } from './onlineOnly';
|
||||
|
||||
/**
|
||||
* PLC-14, online only like the rest of All places: which changes a person
|
||||
* may see follows from the trips and lists they reach right now, which only
|
||||
* the server knows at the moment it is asked, so there is no cache to answer
|
||||
* from.
|
||||
*/
|
||||
export const placeHistoryRepo = {
|
||||
async history(
|
||||
kind: PlacesLibraryKind,
|
||||
id: number,
|
||||
query: PlaceHistoryQueryInput = {},
|
||||
signal?: AbortSignal
|
||||
): Promise<PlaceHistoryPageResponse> {
|
||||
requireOnline();
|
||||
return await placeHistoryApi.history(kind, id, query, signal);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
import type {
|
||||
PlacesLibraryBulkTagsRequest,
|
||||
PlacesLibraryBulkTagsResponse,
|
||||
PlacesLibraryEntry,
|
||||
Tag,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { placeTagsApi } from '../api/placeTags';
|
||||
import { requireOnline } from './onlineOnly';
|
||||
|
||||
/**
|
||||
* PLC-21, online only on purpose like All places itself: the tags sit on
|
||||
* entries the server resolves from the trips and lists the user reaches at
|
||||
* the moment of asking, so there is no cache to answer from. Only the
|
||||
* user's personal tags come back (a trip's own tags never do).
|
||||
*/
|
||||
export const placeTagsRepo = {
|
||||
async list(): Promise<Tag[]> {
|
||||
requireOnline();
|
||||
const { tags } = await placeTagsApi.list();
|
||||
return tags.filter((tag) => tag.trip_id == null);
|
||||
},
|
||||
|
||||
async create(name: string, color?: string): Promise<Tag> {
|
||||
requireOnline();
|
||||
return (await placeTagsApi.create(color ? { name, color } : { name })).tag;
|
||||
},
|
||||
|
||||
async update(id: number, changes: { name?: string; color?: string }): Promise<Tag> {
|
||||
requireOnline();
|
||||
return (await placeTagsApi.update(id, changes)).tag;
|
||||
},
|
||||
|
||||
async remove(id: number): Promise<void> {
|
||||
requireOnline();
|
||||
await placeTagsApi.remove(id);
|
||||
},
|
||||
|
||||
/** The entry after the change, null once it is out of reach. */
|
||||
async setForEntry(key: string, tagIds: number[]): Promise<PlacesLibraryEntry | null> {
|
||||
requireOnline();
|
||||
return (await placeTagsApi.setForEntry({ key, tag_ids: tagIds })).entry;
|
||||
},
|
||||
|
||||
async bulk(body: PlacesLibraryBulkTagsRequest): Promise<PlacesLibraryBulkTagsResponse['entries']> {
|
||||
requireOnline();
|
||||
return (await placeTagsApi.bulk(body)).entries;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import type {
|
||||
PlaceMediaResponse,
|
||||
PlacesLibraryKind,
|
||||
PlaceVisitsForPlaceResponse,
|
||||
PlaceVisitsListQuery,
|
||||
PlaceVisitsListResponse,
|
||||
PlaceVisitTripVisitedResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { placeVisitsApi } from '../api/placeVisits';
|
||||
import { requireOnline } from './onlineOnly';
|
||||
|
||||
/**
|
||||
* Visits (D7, D8), read only: the server derives them from the trips' day
|
||||
* plans for each reader with their own rights, so nothing is kept on the
|
||||
* device. Offline, every call throws `OnlineOnlyError`, which the views turn
|
||||
* into "nothing to show".
|
||||
*/
|
||||
export const placeVisitsRepo = {
|
||||
async list(query: PlaceVisitsListQuery = {}, signal?: AbortSignal): Promise<PlaceVisitsListResponse> {
|
||||
requireOnline();
|
||||
return await placeVisitsApi.list(query, signal);
|
||||
},
|
||||
|
||||
async forPlace(kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlaceVisitsForPlaceResponse> {
|
||||
requireOnline();
|
||||
return await placeVisitsApi.forPlace(kind, id, signal);
|
||||
},
|
||||
|
||||
async tripVisited(tripId: number, signal?: AbortSignal): Promise<PlaceVisitTripVisitedResponse> {
|
||||
requireOnline();
|
||||
return await placeVisitsApi.tripVisited(tripId, signal);
|
||||
},
|
||||
|
||||
async media(kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlaceMediaResponse> {
|
||||
requireOnline();
|
||||
return await placeVisitsApi.media(kind, id, signal);
|
||||
},
|
||||
};
|
||||
@@ -4,7 +4,8 @@ import type {
|
||||
PlacesLibraryPageResponse,
|
||||
PlacesLibraryQueryInput,
|
||||
} from '@trek/shared';
|
||||
import { mapsApi } from '../api/client';
|
||||
import { mapsApi, placesApi } from '../api/client';
|
||||
import { collectionsApi } from '../api/collections';
|
||||
import { placesLibraryApi } from '../api/placesLibrary';
|
||||
import { requireOnline } from './onlineOnly';
|
||||
|
||||
@@ -35,4 +36,18 @@ export const placesLibraryRepo = {
|
||||
const res = await mapsApi.placePhoto(`${place.lat},${place.lng}`, place.lat, place.lng, place.name);
|
||||
return res?.photoUrl ?? null;
|
||||
},
|
||||
|
||||
/**
|
||||
* PLC-17: the notes one origin keeps of the place, written where they live: a
|
||||
* saved place's notes in its list, a trip place's in its trip. Who may write
|
||||
* them is the list's or the trip's own rule, checked by the server.
|
||||
*/
|
||||
async saveNotes(
|
||||
origin: { kind: 'trip'; trip_id: number; place_id: number } | { kind: 'list'; collection_place_id: number },
|
||||
notes: string | null
|
||||
): Promise<void> {
|
||||
requireOnline();
|
||||
if (origin.kind === 'list') await collectionsApi.updatePlace(origin.collection_place_id, { notes });
|
||||
else await placesApi.update(origin.trip_id, origin.place_id, { notes });
|
||||
},
|
||||
};
|
||||
|
||||
@@ -20,7 +20,8 @@ import type {
|
||||
export type IncomingCollectionInvite = CollectionListResponse['incomingInvites'][number]
|
||||
|
||||
/** What a copy into a trip takes along besides the places (D9): left out, neither notes nor tags. */
|
||||
type CopyToTripCarry = Pick<CollectionCopyToTripRequest, 'include_notes' | 'tag_ids'>
|
||||
/** What comes along into the trip: the notes, the list's tags, and (PLC-21) the personal tags chosen to share. */
|
||||
type CopyToTripCarry = Pick<CollectionCopyToTripRequest, 'include_notes' | 'tag_ids' | 'personal_tag_ids'>
|
||||
|
||||
/** Sentinel id for the client-side "All saved" union pseudo-list. */
|
||||
export const ALL_SAVED = 'all' as const
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import type {
|
||||
PlaceActivity,
|
||||
PlaceActivitySource,
|
||||
PlaceLibraryActivitySource,
|
||||
PlacesLibraryKind,
|
||||
TripPlaceActivityLinkRequest,
|
||||
} from '@trek/shared';
|
||||
import { create } from 'zustand';
|
||||
|
||||
import { addListener, removeListener } from '../api/websocket';
|
||||
import { placeActivitiesRepo } from '../repo/placeActivitiesRepo';
|
||||
import { useAuthStore } from './authStore';
|
||||
|
||||
/**
|
||||
* The bookings and tours a place is about (PLC-18), as the server answered
|
||||
* for the signed-in account: per trip place, per saved place and per entry of
|
||||
* All places. Keyed by account, because what each person sees follows their
|
||||
* own rights. A `placeActivities:changed` push reads again what the store
|
||||
* holds for that trip place (and the entries it is an origin of); a
|
||||
* `collections:updated` push does the same for the saved places of that list.
|
||||
*/
|
||||
|
||||
export interface PlaceActivitiesEntry {
|
||||
activities: PlaceActivity[];
|
||||
/** Whether the reader may link more: on this place, or for an entry on any of its origins. */
|
||||
canLink: boolean;
|
||||
/** For an entry of All places: its origins and whether each takes links. Empty otherwise. */
|
||||
sources: PlaceLibraryActivitySource[];
|
||||
}
|
||||
|
||||
/** Which place an entry of the store belongs to. */
|
||||
export type PlaceActivitiesTarget =
|
||||
| { kind: 'trip'; tripId: number; placeId: number }
|
||||
| { kind: 'list'; collectionPlaceId: number }
|
||||
| { kind: 'entry'; entryKind: PlacesLibraryKind; id: number };
|
||||
|
||||
interface PlaceActivitiesState {
|
||||
entries: Record<string, PlaceActivitiesEntry>;
|
||||
/** Reads the activities of a trip place, a saved place or an entry. Online only; throws when refused or offline. */
|
||||
load: (target: PlaceActivitiesTarget) => Promise<PlaceActivitiesEntry>;
|
||||
/** Links a booking or tour of the trip to the trip place. */
|
||||
linkTrip: (tripId: number, placeId: number, body: TripPlaceActivityLinkRequest) => Promise<void>;
|
||||
/** Links a tour kept in the list to the saved place. */
|
||||
linkSaved: (collectionPlaceId: number, collectionTourId: number) => Promise<void>;
|
||||
/** Takes the link of an activity off the place it was linked to; the booking or tour stays. */
|
||||
unlink: (activity: Pick<PlaceActivity, 'source' | 'target'>) => Promise<void>;
|
||||
}
|
||||
|
||||
function targetKey(target: PlaceActivitiesTarget): string {
|
||||
const user = useAuthStore.getState().user?.id ?? 'anon';
|
||||
if (target.kind === 'trip') return `${user}:trip:${target.tripId}:${target.placeId}`;
|
||||
if (target.kind === 'list') return `${user}:list:${target.collectionPlaceId}`;
|
||||
return `${user}:entry:${target.entryKind}:${target.id}`;
|
||||
}
|
||||
|
||||
/** The store entry of the place a source names. */
|
||||
function sourceTarget(source: PlaceActivitySource): PlaceActivitiesTarget {
|
||||
return source.kind === 'trip'
|
||||
? { kind: 'trip', tripId: source.trip_id, placeId: source.place_id }
|
||||
: { kind: 'list', collectionPlaceId: source.collection_place_id };
|
||||
}
|
||||
|
||||
/** The targets the store holds, read back from their keys, for the signed-in account. */
|
||||
function heldTargets(entries: Record<string, PlaceActivitiesEntry>): PlaceActivitiesTarget[] {
|
||||
const prefix = `${useAuthStore.getState().user?.id ?? 'anon'}:`;
|
||||
return Object.keys(entries).flatMap((key): PlaceActivitiesTarget[] => {
|
||||
if (!key.startsWith(prefix)) return [];
|
||||
const [kind, a, b] = key.slice(prefix.length).split(':');
|
||||
if (kind === 'trip') return [{ kind: 'trip', tripId: Number(a), placeId: Number(b) }];
|
||||
if (kind === 'list') return [{ kind: 'list', collectionPlaceId: Number(a) }];
|
||||
if (kind === 'entry' && (a === 'trip' || a === 'list')) return [{ kind: 'entry', entryKind: a, id: Number(b) }];
|
||||
return [];
|
||||
});
|
||||
}
|
||||
|
||||
export const usePlaceActivitiesStore = create<PlaceActivitiesState>((set, get) => {
|
||||
const put = (target: PlaceActivitiesTarget, entry: PlaceActivitiesEntry): PlaceActivitiesEntry => {
|
||||
set((state) => ({ entries: { ...state.entries, [targetKey(target)]: entry } }));
|
||||
return entry;
|
||||
};
|
||||
/** After a write: the place it changed, and every entry of All places held that has it as an origin. */
|
||||
const refreshAround = async (place: PlaceActivitiesTarget) => {
|
||||
const entries = get().entries;
|
||||
const around = heldTargets(entries).filter(
|
||||
(target) =>
|
||||
target.kind === 'entry' &&
|
||||
(entries[targetKey(target)]?.sources.some((origin) => isPlace(origin.source, place)) ?? false)
|
||||
);
|
||||
await Promise.all(around.map((target) => get().load(target)));
|
||||
};
|
||||
|
||||
return {
|
||||
entries: {},
|
||||
|
||||
load: async (target) => {
|
||||
if (target.kind === 'trip') {
|
||||
const { activities, can_link } = await placeActivitiesRepo.tripPlace(target.tripId, target.placeId);
|
||||
return put(target, { activities, canLink: can_link, sources: [] });
|
||||
}
|
||||
if (target.kind === 'list') {
|
||||
const { activities, can_link } = await placeActivitiesRepo.savedPlace(target.collectionPlaceId);
|
||||
return put(target, { activities, canLink: can_link, sources: [] });
|
||||
}
|
||||
const { activities, sources } = await placeActivitiesRepo.libraryEntry(target.entryKind, target.id);
|
||||
return put(target, { activities, canLink: sources.some((origin) => origin.can_link), sources });
|
||||
},
|
||||
|
||||
linkTrip: async (tripId, placeId, body) => {
|
||||
const { activities, can_link } = await placeActivitiesRepo.linkTrip(tripId, placeId, body);
|
||||
const place = { kind: 'trip', tripId, placeId } as const;
|
||||
put(place, { activities, canLink: can_link, sources: [] });
|
||||
await refreshAround(place);
|
||||
},
|
||||
|
||||
linkSaved: async (collectionPlaceId, collectionTourId) => {
|
||||
const { activities, can_link } = await placeActivitiesRepo.linkSaved(collectionPlaceId, collectionTourId);
|
||||
const place = { kind: 'list', collectionPlaceId } as const;
|
||||
put(place, { activities, canLink: can_link, sources: [] });
|
||||
await refreshAround(place);
|
||||
},
|
||||
|
||||
unlink: async (activity) => {
|
||||
const { activities, can_link } = await placeActivitiesRepo.unlink(activity);
|
||||
const place = sourceTarget(activity.source);
|
||||
put(place, { activities, canLink: can_link, sources: [] });
|
||||
await refreshAround(place);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
/** Whether an origin of an entry is the trip place or saved place `place`. */
|
||||
function isPlace(source: PlaceActivitySource, place: PlaceActivitiesTarget): boolean {
|
||||
if (source.kind === 'trip') return place.kind === 'trip' && place.placeId === source.place_id;
|
||||
return place.kind === 'list' && place.collectionPlaceId === source.collection_place_id;
|
||||
}
|
||||
|
||||
/** The store's entry for the signed-in account, if it holds one. */
|
||||
export function placeActivitiesEntry(
|
||||
state: Pick<PlaceActivitiesState, 'entries'>,
|
||||
target: PlaceActivitiesTarget
|
||||
): PlaceActivitiesEntry | undefined {
|
||||
return state.entries[targetKey(target)];
|
||||
}
|
||||
|
||||
/** Whether a held target is touched by a push: the trip place `placeId`, or the list `collectionId`. */
|
||||
function touched(
|
||||
target: PlaceActivitiesTarget,
|
||||
entry: PlaceActivitiesEntry | undefined,
|
||||
push: { placeId?: number; collectionId?: number }
|
||||
): boolean {
|
||||
if (target.kind === 'trip') return target.placeId === push.placeId;
|
||||
if (target.kind === 'list') {
|
||||
return (
|
||||
entry?.activities.some(
|
||||
(activity) => activity.source.kind === 'list' && activity.source.collection_id === push.collectionId
|
||||
) ?? false
|
||||
);
|
||||
}
|
||||
return (
|
||||
entry?.sources.some(({ source }) =>
|
||||
source.kind === 'trip' ? source.place_id === push.placeId : source.collection_id === push.collectionId
|
||||
) ?? false
|
||||
);
|
||||
}
|
||||
|
||||
const positiveId = (value: unknown): number | undefined => {
|
||||
const id = Number(value);
|
||||
return Number.isSafeInteger(id) && id > 0 ? id : undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies `placeActivities:changed` (a trip place's links changed) and
|
||||
* `collections:updated` (something in a list changed, its saved places'
|
||||
* links among it): reads again every held trip place, saved place and entry
|
||||
* the push touches. A saved place the store holds without any activity is
|
||||
* read again on every push of any list, since nothing says which list it is on.
|
||||
* Returns the function that stops listening.
|
||||
*/
|
||||
export function watchPlaceActivities(): () => void {
|
||||
const onEvent = (event: Record<string, unknown>) => {
|
||||
if (event?.type !== 'placeActivities:changed' && event?.type !== 'collections:updated') return;
|
||||
const push: { placeId?: number; collectionId?: number } =
|
||||
event.type === 'placeActivities:changed'
|
||||
? { placeId: positiveId(event.placeId) }
|
||||
: { collectionId: positiveId(event.collectionId) };
|
||||
if (push.placeId === undefined && push.collectionId === undefined) return;
|
||||
const store = usePlaceActivitiesStore.getState();
|
||||
for (const target of heldTargets(store.entries)) {
|
||||
const entry = placeActivitiesEntry(store, target);
|
||||
const unknownList = target.kind === 'list' && push.collectionId !== undefined && !entry?.activities.length;
|
||||
if (!unknownList && !touched(target, entry, push)) continue;
|
||||
void store.load(target).catch(() => {
|
||||
// Offline or refused: the store keeps the last answer until the next read.
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
};
|
||||
addListener(onEvent);
|
||||
return () => removeListener(onEvent);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { PlacesLibraryBulkTagsRequest, PlacesLibraryEntry, Tag } from '@trek/shared';
|
||||
import { create } from 'zustand';
|
||||
|
||||
import { addListener, removeListener } from '../api/websocket';
|
||||
import { placeTagsRepo } from '../repo/placeTagsRepo';
|
||||
|
||||
/**
|
||||
* PLC-21: the signed-in user's personal tags, as the tag picker and the tag
|
||||
* filter of All places offer them, by name. Online only, like the repo. The
|
||||
* assignments themselves are not kept here: an entry carries its own tags,
|
||||
* and a change answers the entries as they are now, for the caller to put
|
||||
* where it shows them. A `tags:changed` push (another tab or device changed
|
||||
* the tags) reads the list again.
|
||||
*/
|
||||
interface PlaceTagsState {
|
||||
tags: Tag[];
|
||||
loaded: boolean;
|
||||
/** Reads the tags again. Online only; throws when offline or refused. */
|
||||
load: () => Promise<Tag[]>;
|
||||
/** The user's tag of that name (case ignored), made now when there is none yet. */
|
||||
create: (name: string, color?: string) => Promise<Tag>;
|
||||
update: (id: number, changes: { name?: string; color?: string }) => Promise<Tag>;
|
||||
/** Deletes the tag; it comes off every place that carried it. */
|
||||
remove: (id: number) => Promise<void>;
|
||||
/** The entry carries exactly these tags from now on; answers the entry, null once out of reach. */
|
||||
setForEntry: (key: string, tagIds: number[]) => Promise<PlacesLibraryEntry | null>;
|
||||
/** Puts tags on several entries and takes others off; answers the entries. */
|
||||
bulk: (body: PlacesLibraryBulkTagsRequest) => Promise<PlacesLibraryEntry[]>;
|
||||
}
|
||||
|
||||
const byName = (a: Tag, b: Tag) => String(a.name).localeCompare(String(b.name)) || a.id - b.id;
|
||||
|
||||
/** The list with `tag` in it, once, in name order. */
|
||||
function withTag(tags: Tag[], tag: Tag): Tag[] {
|
||||
return [...tags.filter((other) => other.id !== tag.id), tag].sort(byName);
|
||||
}
|
||||
|
||||
export const usePlaceTagsStore = create<PlaceTagsState>((set) => ({
|
||||
tags: [],
|
||||
loaded: false,
|
||||
|
||||
async load() {
|
||||
const tags = [...(await placeTagsRepo.list())].sort(byName);
|
||||
set({ tags, loaded: true });
|
||||
return tags;
|
||||
},
|
||||
|
||||
async create(name, color) {
|
||||
const tag = await placeTagsRepo.create(name, color);
|
||||
set((state) => ({ tags: withTag(state.tags, tag) }));
|
||||
return tag;
|
||||
},
|
||||
|
||||
async update(id, changes) {
|
||||
const tag = await placeTagsRepo.update(id, changes);
|
||||
set((state) => ({ tags: withTag(state.tags, tag) }));
|
||||
return tag;
|
||||
},
|
||||
|
||||
async remove(id) {
|
||||
await placeTagsRepo.remove(id);
|
||||
set((state) => ({ tags: state.tags.filter((tag) => tag.id !== id) }));
|
||||
},
|
||||
|
||||
async setForEntry(key, tagIds) {
|
||||
return await placeTagsRepo.setForEntry(key, tagIds);
|
||||
},
|
||||
|
||||
async bulk(body) {
|
||||
return await placeTagsRepo.bulk(body);
|
||||
},
|
||||
}));
|
||||
|
||||
/**
|
||||
* Reads the tags again on a `tags:changed` push while the store has been
|
||||
* loaded once. Returns the unsubscribe.
|
||||
*/
|
||||
export function subscribePlaceTags(): () => void {
|
||||
const onEvent = (event: Record<string, unknown>) => {
|
||||
if (event?.type !== 'tags:changed') return;
|
||||
const store = usePlaceTagsStore.getState();
|
||||
if (!store.loaded) return;
|
||||
void store.load().catch(() => {
|
||||
// Offline or refused: the last list stays until the next read.
|
||||
return undefined;
|
||||
});
|
||||
};
|
||||
addListener(onEvent);
|
||||
return () => removeListener(onEvent);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { PlaceVisitTripVisitedResponse } from '@trek/shared';
|
||||
import { create } from 'zustand';
|
||||
|
||||
import { addListener, removeListener } from '../api/websocket';
|
||||
import { placeVisitsRepo } from '../repo/placeVisitsRepo';
|
||||
import { useAuthStore } from './authStore';
|
||||
|
||||
/**
|
||||
* Which places of a trip the signed-in account visited (PLC-23), for the
|
||||
* filter of the trip's place list and map, and a revision that moves whenever
|
||||
* a trip change may have changed them, so an open visit history or place
|
||||
* detail knows to read again. A visit is never entered: the server reads it
|
||||
* from the trips' day plans (a dated day up to today, the stop naming no one
|
||||
* or the reader), so the store follows the plan's own events. Keyed by
|
||||
* account and trip, because visits are per person. Online only.
|
||||
*/
|
||||
|
||||
interface TripVisitedEntry {
|
||||
placeIds: number[];
|
||||
places: PlaceVisitTripVisitedResponse['places'];
|
||||
}
|
||||
|
||||
interface PlaceVisitsState {
|
||||
visited: Record<string, TripVisitedEntry>;
|
||||
/** Grows by one whenever a pushed trip change may have changed the visits. */
|
||||
revision: number;
|
||||
/** Reads which of the trip's places the account visited. Throws when offline or refused. */
|
||||
loadTripVisited: (tripId: number) => Promise<TripVisitedEntry>;
|
||||
bump: () => void;
|
||||
}
|
||||
|
||||
function keyOf(tripId: number): string {
|
||||
return `${useAuthStore.getState().user?.id ?? 'anon'}:${tripId}`;
|
||||
}
|
||||
|
||||
export const usePlaceVisitsStore = create<PlaceVisitsState>((set) => ({
|
||||
visited: {},
|
||||
revision: 0,
|
||||
|
||||
loadTripVisited: async (tripId) => {
|
||||
const { place_ids, places } = await placeVisitsRepo.tripVisited(tripId);
|
||||
const entry = { placeIds: place_ids, places };
|
||||
set((state) => ({ visited: { ...state.visited, [keyOf(tripId)]: entry } }));
|
||||
return entry;
|
||||
},
|
||||
|
||||
bump: () => set((state) => ({ revision: state.revision + 1 })),
|
||||
}));
|
||||
|
||||
/** The trip's visited places for the signed-in account, if the store holds them. */
|
||||
export function tripVisitedEntry(
|
||||
state: PlaceVisitsState,
|
||||
tripId: number | null | undefined
|
||||
): TripVisitedEntry | undefined {
|
||||
return tripId == null ? undefined : state.visited[keyOf(tripId)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads again every trip whose visited places the store holds for this account,
|
||||
* after a visit changed here or reached it from elsewhere.
|
||||
*/
|
||||
export function refreshTripVisited(): void {
|
||||
const store = usePlaceVisitsStore.getState();
|
||||
store.bump();
|
||||
const prefix = `${useAuthStore.getState().user?.id ?? 'anon'}:`;
|
||||
const tripIds = Object.keys(store.visited)
|
||||
.filter((key) => key.startsWith(prefix))
|
||||
.map((key) => Number(key.slice(prefix.length)))
|
||||
.filter((id) => Number.isSafeInteger(id) && id > 0);
|
||||
void Promise.all(tripIds.map((tripId) => store.loadTripVisited(tripId))).catch(() => {
|
||||
// Offline or refused: the store keeps the last answer until the next read.
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The pushed changes that can change what the account visited: a place
|
||||
* planned on or taken off a day or given other participants, a day's date, a
|
||||
* place gone, someone joining or leaving a trip, a trip's dates, a trip gone
|
||||
* or the account's trips changing. A place in one trip can be the same place
|
||||
* as one in another (All places), so every held trip is read again.
|
||||
*/
|
||||
const VISIT_EVENTS: ReadonlySet<string> = new Set([
|
||||
'assignment:created',
|
||||
'assignment:updated',
|
||||
'assignment:deleted',
|
||||
'assignment:moved',
|
||||
'assignment:participants',
|
||||
'day:created',
|
||||
'day:updated',
|
||||
'day:deleted',
|
||||
'day:reordered',
|
||||
'place:deleted',
|
||||
'member:added',
|
||||
'member:removed',
|
||||
'trip:updated',
|
||||
'trip:deleted',
|
||||
'trips:changed',
|
||||
]);
|
||||
|
||||
/** How long a burst of plan changes (a drag across days, an undo) is gathered before reading again. */
|
||||
const REFRESH_DELAY_MS = 400;
|
||||
|
||||
/**
|
||||
* Follows the trip events that can change the visits: moves the revision and
|
||||
* reads again every trip whose visited places the store holds for this
|
||||
* account, once per burst. Returns the function that stops listening.
|
||||
*/
|
||||
export function watchPlaceVisits(): () => void {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
const onEvent = (event: Record<string, unknown>) => {
|
||||
if (typeof event?.type !== 'string' || !VISIT_EVENTS.has(event.type)) return;
|
||||
if (timer !== null) clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
timer = null;
|
||||
refreshTripVisited();
|
||||
}, REFRESH_DELAY_MS);
|
||||
};
|
||||
addListener(onEvent);
|
||||
return () => {
|
||||
if (timer !== null) clearTimeout(timer);
|
||||
removeListener(onEvent);
|
||||
};
|
||||
}
|
||||
@@ -735,3 +735,14 @@
|
||||
.trek-dash .col-lrow-caticon svg { display: block; }
|
||||
/* The average vote on the tile's other corner: an amber star, as on the map's pins, its figure inside. */
|
||||
.trek-dash .col-lrow-ratebadge { position: absolute; bottom: -5px; inset-inline-end: -6px; min-width: 20px; height: 20px; padding: 0 4px; border-radius: 10px; display: grid; place-items: center; background: #f59e0b; border: 1.5px solid var(--surface); box-sizing: border-box; font-size: 10px; font-weight: 700; line-height: 1; color: #fff; font-variant-numeric: tabular-nums; white-space: nowrap; text-shadow: 0 1px 1px rgba(0, 0, 0, .45); }
|
||||
/* A small action at the end of a sheet section's label, such as confirming a visit. */
|
||||
.trek-dash .col-detail-action { display: inline-flex; align-items: center; gap: 4px; padding: 3px 8px; border-radius: 8px; font-size: 12px; font-weight: 600; color: var(--ink-3); transition: background .12s, color .12s; }
|
||||
.trek-dash .col-detail-action:hover { background: var(--surface-2); color: var(--ink); }
|
||||
.trek-dash .col-detail-action:disabled { opacity: .5; }
|
||||
/* Trips and lists side by side: equal columns of cards of one height, each two lines. */
|
||||
.trek-dash .col-origin-pair { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; align-items: start; }
|
||||
.trek-dash .col-origin-pair > .col-detail-field { min-width: 0; }
|
||||
/* The origin tiles: a trip's cover filling its tile, a list's symbol in the list's own colour. */
|
||||
.trek-dash .col-origin-ico { overflow: hidden; }
|
||||
.trek-dash .col-origin-cover { width: 100%; height: 100%; object-fit: cover; }
|
||||
.trek-dash .col-origin-ico-list { background: color-mix(in srgb, var(--list) 16%, var(--surface)); color: var(--list); }
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Place } from '../types'
|
||||
|
||||
/**
|
||||
* The trip's places filter, in one place: the pool (all / unplanned / planned /
|
||||
* tracks), the category set, which the tags filter through as well, and the
|
||||
* visited / tracks), the category set, which the tags filter through as well, and the
|
||||
* minimum rating. The desktop list, the phone list and the map markers of both
|
||||
* shells apply this same predicate to the same values, held in the trip store
|
||||
* (#1541). The map keeps two deliberate differences of its own: with a day
|
||||
@@ -62,11 +62,14 @@ export interface PoolFilterSets {
|
||||
* open day (#2024) while 'unplanned' stays trip-wide.
|
||||
*/
|
||||
plannedFilterIds?: ReadonlySet<number> | null
|
||||
/** The places of the trip the reader confirmed a visit at, there or at the same place elsewhere (PLC-23). */
|
||||
visitedIds?: ReadonlySet<number> | null
|
||||
}
|
||||
|
||||
/** A null set means "not needed for this filter" and filters nothing out. */
|
||||
export function matchesPoolFilter(place: Place, filter: string, { plannedIds, plannedFilterIds = plannedIds }: PoolFilterSets): boolean {
|
||||
export function matchesPoolFilter(place: Place, filter: string, { plannedIds, plannedFilterIds = plannedIds, visitedIds }: PoolFilterSets): boolean {
|
||||
if (filter === 'unplanned') return !plannedIds?.has(place.id)
|
||||
if (filter === 'visited') return !!visitedIds?.has(place.id)
|
||||
if (filter === 'planned') return !plannedFilterIds || plannedFilterIds.has(place.id)
|
||||
if (filter === 'tracks') return !!place.route_geometry
|
||||
return true
|
||||
|
||||
Reference in New Issue
Block a user