feat(places): one place view for All places and the lists

The desktop dialog and the phone sheet of a place show its overview, notes,
tours and bookings, photos and files and its history in tabs, with the tags
of each list and trip, a markdown notes editor, uploads and the place
picture. The rating bar of All places is the rating row the lists show,
with its voters, and votes once for every copy. All places filters by a
lowest rating and sorts by it, and the edit form changes the first copy the
reader may edit, which the server carries to the others.
This commit is contained in:
Maurice
2026-11-29 23:36:43 +00:00
parent 783c98f41e
commit d758f4c592
78 changed files with 5604 additions and 2797 deletions
@@ -18,6 +18,8 @@ interface CollectionHeroProps {
/** List colour — drives the gradient wash (or tints the cover image). */
color: string
coverImage?: string | null
/** The two views that are not a list wear their own gradient: every place, and everything saved. */
variant?: 'library' | 'saved'
description?: string | null
links?: CollectionLink[]
/** Accepted members (owner first) — shown as an avatar stack when shared. */
@@ -47,7 +49,7 @@ function linkHost(url: string): string {
}
export default function CollectionHero({
eyebrow, title, color, coverImage, description, links,
eyebrow, title, color, coverImage, variant, description, links,
members, canShare, isOwner, canEdit, onEdit, shareMemberCount, onShare, onExport, exporting, t,
}: CollectionHeroProps): React.ReactElement {
const accepted = members.filter(m => m.status === 'accepted' || m.is_owner)
@@ -56,7 +58,7 @@ export default function CollectionHero({
const extra = accepted.length - shown.length
return (
<header className="col-hero" style={{ ['--hero-color' as string]: color }}>
<header className={variant ? `col-hero is-${variant}` : 'col-hero'} style={{ ['--hero-color' as string]: color }}>
{coverImage ? (
<>
<img className="col-hero-img" src={coverImage} alt="" />
@@ -4,7 +4,7 @@ import type { CollectionPlace, CollectionStatus, CollectionLabel } from '@trek/s
import type { TranslationFn } from '../../types'
import PlaceAvatar from '../shared/PlaceAvatar'
import StatusBadge from './StatusBadge'
import CollectionPlaceTags from './CollectionPlaceTags'
import EntryTagDots from './EntryTagDots'
import { usePlaceReorder } from './usePlaceReorder'
import CategoryBadge from './CategoryBadge'
@@ -119,7 +119,7 @@ export default function CollectionList({
<RowAvatar place={place} t={t} />
)}
<div className="li">
<div className="t">{place.category?.name && <CategoryBadge category={place.category} />}<span className="nm">{place.name}</span></div>
<div className="t">{place.category?.name && <CategoryBadge category={place.category} />}<span className="nm">{place.name}</span><EntryTagDots tags={placeLabels} /></div>
{place.address && (
<div className="s">
<MapPin size={11} />
@@ -127,7 +127,6 @@ export default function CollectionList({
</div>
)}
</div>
<CollectionPlaceTags place={place} labels={placeLabels} showCategory={false} />
<div className="col-lrow-status">
<StatusBadge status={place.status} onChange={selectMode || !onStatusChange ? undefined : next => onStatusChange(place.id, next)} t={t} />
</div>
@@ -1,307 +1,549 @@
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'
import remarkBreaks from 'remark-breaks'
import { markdownLinkComponents } from '../shared/markdownLink'
import { X, Pencil, Copy, Trash2, MapPin, Link2, Plus, ExternalLink, Check, Tags, Camera, Loader2, Navigation } from 'lucide-react'
import type { CollectionPlace, CollectionStatus, CollectionLink, CollectionLabel } from '@trek/shared'
import type { Category, TranslationFn } from '../../types'
import MarkdownToolbar from '../Journey/MarkdownToolbar'
import { NumericInput } from '../shared/NumericInput'
import { entityGradient } from '../../utils/gradients'
import { getCategoryIcon } from '../shared/categoryIcons'
import { NavigationMenu } from '../shared/NavigationMenu'
import { navigationTargetLabel, getNavigationTargets, openNavigationTarget } from '../Planner/placeNavigation'
import { STATUS_META, STATUS_ORDER, normalizeLinkUrl } from '../../pages/collections/collectionsModel'
import { Tooltip } from '../shared/Tooltip'
import PlaceRating from '../shared/StarRating'
import { useCollectionPlaceForm } from './useCollectionPlaceForm'
import { CollectionLocationSearch } from './CollectionLocationSearch'
import CategoryTileMenu from './CategoryTileMenu'
import type { CollectionLabel, CollectionLink, CollectionPlace, CollectionStatus } from '@trek/shared';
import {
Camera,
Check,
Copy,
ExternalLink,
Link2,
Loader2,
MapPin,
Navigation,
Pencil,
Plus,
Trash2,
} from 'lucide-react';
import React, { useId, useRef, useState } from 'react';
import Markdown from 'react-markdown';
import { useNavigate } from 'react-router';
import remarkBreaks from 'remark-breaks';
import remarkGfm from 'remark-gfm';
import { useTranslation } from '../../i18n';
import { STATUS_META, STATUS_ORDER, normalizeLinkUrl } from '../../pages/collections/collectionsModel';
import type { Category, TranslationFn } from '../../types';
import { entityGradient } from '../../utils/gradients';
import { placesPath } from '../../utils/placesRoutes';
import MarkdownToolbar from '../Journey/MarkdownToolbar';
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation';
import { getCategoryIcon } from '../shared/categoryIcons';
import { DialogShell } from '../shared/DialogShell';
import { markdownLinkComponents } from '../shared/markdownLink';
import { NavigationMenu } from '../shared/NavigationMenu';
import { NumericInput } from '../shared/NumericInput';
import PlaceRating from '../shared/StarRating';
import { Tooltip } from '../shared/Tooltip';
import CategoryTileMenu from './CategoryTileMenu';
import { CollectionLocationSearch } from './CollectionLocationSearch';
import { originPairs } from './libraryPairs';
import PlaceLocationBadge from './PlaceLocationBadge';
import PlaceOrigins from './PlaceOrigins';
import './placeSheet.css';
import PlaceSheetTabs from './PlaceSheetTabs';
import PlaceTagsCard from './PlaceTagsCard';
import { useCollectionPlaceForm } from './useCollectionPlaceForm';
import { useLibraryPlace } from './useLibraryPlace';
import { usePlaceSheet } from './usePlaceSheet';
import { usePlaceTags } from './usePlaceTags';
function linkHost(url: string): string {
try { return new URL(url).hostname.replace(/^www\./, '') } catch { return url }
try {
return new URL(url).hostname.replace(/^www\./, '');
} catch {
return url;
}
}
type PlacePatch = {
name?: string;
description?: string | null;
notes?: string | null;
links?: CollectionLink[];
category_id?: number | null;
label_ids?: number[];
image_url?: string | null;
lat?: number | null;
lng?: number | null;
address?: string | null;
};
interface CollectionPlaceDetailProps {
place: CollectionPlace
canEdit: boolean
canDelete: boolean
categories: Category[]
/** The active list's custom labels, for the assign chips. */
labels: CollectionLabel[]
/** When set, dock the sheet over that column (desktop split) instead of centred. */
anchorRect?: DockRect | null
onClose: () => void
onSetStatus: (status: CollectionStatus) => void
onSave: (patch: { name?: string; description?: string | null; notes?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; lat?: number | null; lng?: number | null; address?: string | null }) => Promise<void>
place: CollectionPlace;
canEdit: boolean;
canDelete: boolean;
categories: Category[];
/** The active list's tags, which the edit form keeps as they are. */
labels: CollectionLabel[];
/** True while a dialog opened from here is open: Escape and the backdrop leave this one alone. */
blocked?: boolean;
onClose: () => void;
onSetStatus: (status: CollectionStatus) => void;
onSave: (patch: PlacePatch) => Promise<void>;
/** Upload a custom cover image (#1136); enables the cover change/remove controls. */
onUploadImage?: (file: File) => Promise<void>
onCopyToTrip: () => void
onRemove: () => void
onUploadImage?: (file: File) => Promise<void>;
onCopyToTrip: () => void;
onRemove: () => void;
/** Cast/clear the current user's star vote (#1435); every member may vote. */
onRate?: (rating: number | null) => Promise<void> | void
t: TranslationFn
onRate?: (rating: number | null) => Promise<void> | void;
t: TranslationFn;
}
function StatusSegment({ status, onSet, t }: { status: CollectionStatus; onSet: (s: CollectionStatus) => void; t: TranslationFn }): React.ReactElement {
function StatusSegment({
status,
onSet,
t,
}: {
status: CollectionStatus;
onSet: (s: CollectionStatus) => void;
t: TranslationFn;
}): React.ReactElement {
return (
<div className="col-detail-seg" role="group">
{STATUS_ORDER.map(s => {
const Icon = STATUS_META[s].icon
const on = status === s
{STATUS_ORDER.map((s) => {
const Icon = STATUS_META[s].icon;
const on = status === s;
return (
<button key={s} type="button" aria-pressed={on} onClick={() => onSet(s)} className={on ? 'on' : ''}>
<Icon size={14} style={{ color: on ? STATUS_META[s].color : undefined }} /> {t(STATUS_META[s].labelKey)}
</button>
)
);
})}
</div>
)
);
}
/**
* Bottom detail sheet for a saved place — an opaque, clearly-sectioned card
* (cover → meta → status → description → links) docked over the list column.
* Read mode renders the description as markdown + link chips; edit mode swaps in
* name / category / markdown description / links, saving via updatePlace. Status
* is an always-live segmented control (auto-saves).
*/
export default function CollectionPlaceDetail({
place, canEdit, canDelete, categories, labels, anchorRect, onClose, onSetStatus, onSave, onUploadImage, onCopyToTrip, onRemove, onRate, t,
}: CollectionPlaceDetailProps): React.ReactElement {
const coverInputRef = useRef<HTMLInputElement>(null)
const [navOpen, setNavOpen] = useState(false)
const navBtnRef = useRef<HTMLButtonElement>(null)
const navigationTargets = getNavigationTargets(place)
const descRef = useRef<HTMLTextAreaElement>(null)
const {
editing, setEditing, name, setName, categoryId, setCategoryId, description, setDescription, notes, setNotes, links, setLinks, setLink,
labelIds, toggleLabel, address, setAddress, lat, setLat, lng, setLng, pickPosition, positionPicked, needsPosition, saving, imgBusy, cover: banner, assignedLabels,
handleImagePick: handleCoverPick, handleImageRemove, cancelEdit: resetForm, save,
} = useCollectionPlaceForm({ place, labels, onSave, onUploadImage, t, normalizeLinkUrl, withCoordinates: true })
const coordPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
const text = e.clipboardData.getData('text').trim()
const match = text.match(/^(-?\d+(?:\.\d*)?)(?:\s*[,;]\s*|\s+)(-?\d+(?:\.\d*)?)$/)
if (match) { e.preventDefault(); setLat(match[1]); setLng(match[2]) }
}
const CatIcon = getCategoryIcon(place.category?.icon)
type Form = ReturnType<typeof useCollectionPlaceForm>;
/** The cover: the picture or a gradient, the category, the picture controls, close, and the name. */
function Cover({
place,
form,
canEdit,
categories,
labelId,
onUploadImage,
onClose,
t,
}: {
place: CollectionPlace;
form: Form;
canEdit: boolean;
categories: Category[];
labelId: string;
onUploadImage?: (file: File) => Promise<void>;
onClose: () => void;
t: TranslationFn;
}) {
const coverInputRef = useRef<HTMLInputElement>(null);
const CatIcon = getCategoryIcon(place.category?.icon);
const banner = form.cover;
return (
<div className={`col-detail${anchorRect ? ' docked' : ''}`} style={dockStyle(anchorRect)} role="presentation" onClick={e => e.stopPropagation()}>
<div className="col-detail-cover" style={banner ? undefined : { backgroundImage: entityGradient(place.id) }}>
{banner && <img src={banner} alt="" />}
<div className="col-detail-cover-scrim" />
{/* Chip and cover controls share the top bar. The controls keep the end and
never shrink, so a long category name ellipsizes instead of sliding under
them, however many buttons there are and whatever size phones give them. */}
<div className="absolute start-[14px] end-[12px] top-[12px] z-[2] flex items-center gap-[8px]">
{place.category?.name && (
<span className="col-detail-cover-cat min-w-0" style={{ ['--cat' as string]: place.category.color || '#6366f1' }}>
<CatIcon size={12} className="flex-none" />
<span className="truncate">{place.category.name}</span>
</span>
)}
{/* The cover controls wear the close button's class, so they get its look,
hover and phone size. */}
<div className="ms-auto flex flex-none gap-[6px]">
{canEdit && onUploadImage && (
<>
<input ref={coverInputRef} type="file" accept="image/jpeg,image/png,image/gif,image/webp,.heic,.heif" style={{ display: 'none' }} onChange={handleCoverPick} />
{place.image_url && !imgBusy && (
<Tooltip label={t('places.removeImage')} placement="bottom">
<button type="button" className="col-detail-close" onClick={handleImageRemove} aria-label={t('places.removeImage')}>
<Trash2 size={16} />
</button>
</Tooltip>
)}
<Tooltip label={place.image_url ? t('places.changeImage') : t('places.uploadImage')} placement="bottom">
<div className="col-detail-cover" style={banner ? undefined : { backgroundImage: entityGradient(place.id) }}>
{banner && <img src={banner} alt="" />}
<div className="col-detail-cover-scrim" />
<div className="absolute end-[12px] start-[14px] top-[12px] z-[2] flex items-center gap-[8px]">
{place.category?.name && (
<span
className="col-detail-cover-cat min-w-0"
style={{ ['--cat' as string]: place.category.color || 'var(--accent)' }}
>
<CatIcon size={12} className="flex-none" />
<span className="truncate">{place.category.name}</span>
</span>
)}
<div className="ms-auto flex flex-none gap-[6px]">
{canEdit && onUploadImage && (
<>
<input
ref={coverInputRef}
type="file"
accept="image/jpeg,image/png,image/gif,image/webp,.heic,.heif"
className="hidden"
onChange={form.handleImagePick}
/>
{place.image_url && !form.imgBusy && (
<Tooltip label={t('places.removeImage')} placement="bottom">
<button
type="button"
className="col-detail-close"
style={imgBusy ? { cursor: 'default' } : undefined}
onClick={() => { if (!imgBusy) coverInputRef.current?.click() }}
aria-label={place.image_url ? t('places.changeImage') : t('places.uploadImage')}
onClick={form.handleImageRemove}
aria-label={t('places.removeImage')}
>
{imgBusy ? <Loader2 size={16} className="animate-spin" /> : <Camera size={16} />}
<Trash2 size={16} />
</button>
</Tooltip>
</>
)}
<button type="button" className="col-detail-close" onClick={onClose} aria-label={t('common.close')}><X size={16} /></button>
</div>
</div>
<div className="col-detail-head">
{editing ? (
// The category rides in front of the name instead of a chip row in the form.
<div className="flex items-center gap-2.5">
{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>
<PlaceLocationBadge address={place.address} lat={place.lat} lng={place.lng} t={t} />
)}
<Tooltip label={place.image_url ? t('places.changeImage') : t('places.uploadImage')} placement="bottom">
<button
type="button"
className="col-detail-close"
onClick={() => {
if (!form.imgBusy) coverInputRef.current?.click();
}}
aria-label={place.image_url ? t('places.changeImage') : t('places.uploadImage')}
>
{form.imgBusy ? <Loader2 size={16} className="animate-spin" /> : <Camera size={16} />}
</button>
</Tooltip>
</>
)}
</div>
</div>
<div className="col-detail-body">
{/* Status — live for editors, read-only for viewers */}
<StatusSegment status={place.status} onSet={canEdit ? onSetStatus : () => {}} t={t} />
{/* Collaborative rating (#1435) — every member votes; the average shows. */}
{/* Rating and labels on one line, each on its own ground.
A bare line of stars read as another row of text, and the labels tried the
cover photo first — where a blue chip on a blue sky is simply not there.
Side by side they are two badges answering two questions about the place. */}
{(onRate || assignedLabels.length > 0) && (
<div className="col-detail-badges">
{onRate && (
<div className="col-detail-rating">
<PlaceRating ratings={place.ratings ?? []} ratingAvg={place.rating_avg} onRate={onRate} />
</div>
<div className="col-detail-head">
{form.editing ? (
// The category rides in front of the name instead of a chip row in the form.
<div className="flex items-center gap-2.5">
{categories.length > 0 && (
<CategoryTileMenu
categories={categories}
value={form.categoryId}
onChange={form.setCategoryId}
size={40}
t={t}
/>
)}
{!editing && assignedLabels.map(l => (
<span key={l.id} className="col-labelchip on static big" style={{ ['--label' as string]: l.color || 'var(--accent)' }}>
<span className="col-labelchip-dot" /> {l.name}
</span>
))}
</div>
)}
{editing ? (
<div className="col-detail-edit">
{/* A place that has no position yet can be looked up here (#2837). */}
{needsPosition && <CollectionLocationSearch picked={positionPicked} onPick={pickPosition} t={t} />}
{/* Address (#1870): free text, the coordinates stay separate */}
<div className="col-detail-field">
<div className="col-detail-label"><MapPin size={12} /> {t('places.formAddress')}</div>
<input value={address} onChange={e => setAddress(e.target.value)} placeholder={t('places.formAddressPlaceholder')} className="col-detail-input" />
</div>
{/* Coordinates */}
<div className="col-detail-field">
<div className="col-detail-label"><MapPin size={12} /> {t('collections.coordinates')}</div>
<div className="col-detail-link-row">
<NumericInput mode="signed" value={lat} onValueChange={setLat} onPaste={coordPaste} placeholder={t('places.formLat')} className="col-detail-input flex-1" />
<NumericInput mode="signed" value={lng} onValueChange={setLng} placeholder={t('places.formLng')} className="col-detail-input flex-1" />
</div>
</div>
{/* Labels */}
{labels.length > 0 && (
<div className="col-detail-field">
<div className="col-detail-label"><Tags size={12} /> {t('collections.labels.title')}</div>
<div className="col-detail-cats">
{labels.map(l => {
const on = labelIds.includes(l.id)
return (
<button key={l.id} type="button" onClick={() => toggleLabel(l.id)} className={`col-detail-cat${on ? ' on' : ''}`} style={{ ['--cat' as string]: l.color || '#6366f1' }}>
<span className="col-labelchip-dot" /> {l.name}
</button>
)
})}
</div>
</div>
)}
{/* Description */}
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.description')}</div>
<MarkdownToolbar textareaRef={descRef} onUpdate={setDescription} />
<textarea ref={descRef} value={description} onChange={e => setDescription(e.target.value)} rows={4} placeholder={t('collections.descriptionPlaceholder')} className="col-detail-textarea" />
</div>
{/* Notes: the traveller's own, apart from the description (#3168) */}
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.notes')}</div>
<textarea value={notes} onChange={e => setNotes(e.target.value)} rows={3} placeholder={t('collections.notesPlaceholder')} className="col-detail-textarea" />
</div>
{/* Links */}
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.links')}</div>
<div className="col-detail-links-edit">
{links.map((l, i) => (
<div key={i} className="col-detail-link-row">
<input value={l.label ?? ''} onChange={e => setLink(i, { label: e.target.value })} placeholder={t('collections.linkLabel')} className="col-detail-input w-28" />
<input value={l.url} onChange={e => setLink(i, { url: e.target.value })} placeholder="https://…" className="col-detail-input flex-1" />
<button type="button" onClick={() => setLinks(links.filter((_, idx) => idx !== i))} className="col-detail-icon-btn" aria-label={t('common.delete')}><Trash2 size={14} /></button>
</div>
))}
<button type="button" onClick={() => setLinks([...links, { url: '' }])} className="col-detail-add-link"><Plus size={13} /> <Link2 size={12} /> {t('collections.addLink')}</button>
</div>
</div>
<input
value={form.name}
onChange={(e) => form.setName(e.target.value)}
className="col-detail-name-input min-w-0 flex-1"
autoFocus
aria-label={t('common.name')}
/>
</div>
) : (
<>
{place.description && (
<div className="col-detail-md collab-note-md">
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{place.description}</Markdown>
</div>
)}
{place.notes?.trim() && (
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.notes')}</div>
<p className="m-0 whitespace-pre-wrap text-body text-content-muted [overflow-wrap:anywhere]">{place.notes}</p>
</div>
)}
{place.links && place.links.length > 0 && (
<div className="col-detail-links">
{place.links.map((l, i) => (
<a key={i} href={l.url} target="_blank" rel="noopener noreferrer" className="col-detail-link">
<ExternalLink size={13} /> {l.label || linkHost(l.url)}
</a>
))}
</div>
)}
</>
)}
</div>
<div className="col-detail-footer">
{editing ? (
<>
<button type="button" onClick={resetForm} className="col-detail-btn">{t('common.cancel')}</button>
<button type="button" onClick={save} disabled={saving} className="col-detail-btn primary"><Check size={14} /> {t('common.save')}</button>
</>
) : (
<>
{canEdit && <button type="button" onClick={() => setEditing(true)} className="col-detail-btn"><Pencil size={14} /> {t('common.edit')}</button>}
<button type="button" onClick={onCopyToTrip} className="col-detail-btn"><Copy size={14} /> {t('collections.copyToTrip')}</button>
{/* Beside the other two rather than up by the address: getting directions is
something you DO with the place, like editing it or copying it into a
trip, and the row of things you do belongs in one place. */}
{navigationTargets.length > 0 && (
<>
<button
ref={navBtnRef}
type="button"
className="col-detail-btn"
onClick={() => {
if (navigationTargets.length === 1) openNavigationTarget(navigationTargets[0])
else setNavOpen(o => !o)
}}
>
<Navigation size={14} />
{navigationTargets.length === 1 ? navigationTargetLabel(navigationTargets[0], t) : t('inspector.navigation')}
</button>
{navOpen && (
<NavigationMenu
targets={navigationTargets}
anchor={navBtnRef.current}
onClose={() => setNavOpen(false)}
/>
)}
</>
)}
<div className="col-detail-footer-spacer" />
{canDelete && <button type="button" onClick={onRemove} className="col-detail-btn danger"><Trash2 size={14} /> {t('collections.removeFromList')}</button>}
<h2 id={labelId} className="col-detail-name">
{place.name}
</h2>
<PlaceLocationBadge address={place.address} lat={place.lat} lng={place.lng} t={t} />
</>
)}
</div>
</div>
)
);
}
/** The edit form beside the cover: position, address, description and links. */
function EditForm({ form, t }: { form: Form; t: TranslationFn }) {
const descRef = useRef<HTMLTextAreaElement>(null);
const coordPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
const text = e.clipboardData.getData('text').trim();
const match = text.match(/^(-?\d+(?:\.\d*)?)(?:\s*[,;]\s*|\s+)(-?\d+(?:\.\d*)?)$/);
if (match) {
e.preventDefault();
form.setLat(match[1]);
form.setLng(match[2]);
}
};
return (
<div className="col-detail-edit">
{/* A place that has no position yet can be looked up here (#2837). */}
{form.needsPosition && <CollectionLocationSearch picked={form.positionPicked} onPick={form.pickPosition} t={t} />}
<div className="col-detail-field">
<div className="col-detail-label">
<MapPin size={12} /> {t('places.formAddress')}
</div>
<input
value={form.address}
onChange={(e) => form.setAddress(e.target.value)}
placeholder={t('places.formAddressPlaceholder')}
className="col-detail-input"
/>
</div>
<div className="col-detail-field">
<div className="col-detail-label">
<MapPin size={12} /> {t('collections.coordinates')}
</div>
<div className="col-detail-link-row">
<NumericInput
mode="signed"
value={form.lat}
onValueChange={form.setLat}
onPaste={coordPaste}
placeholder={t('places.formLat')}
className="col-detail-input flex-1"
/>
<NumericInput
mode="signed"
value={form.lng}
onValueChange={form.setLng}
placeholder={t('places.formLng')}
className="col-detail-input flex-1"
/>
</div>
</div>
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.description')}</div>
<MarkdownToolbar textareaRef={descRef} onUpdate={form.setDescription} />
<textarea
ref={descRef}
value={form.description}
onChange={(e) => form.setDescription(e.target.value)}
rows={5}
placeholder={t('collections.descriptionPlaceholder')}
className="col-detail-textarea"
/>
</div>
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.links')}</div>
<div className="col-detail-links-edit">
{form.links.map((l, i) => (
<div key={i} className="col-detail-link-row">
<input
value={l.label ?? ''}
onChange={(e) => form.setLink(i, { label: e.target.value })}
placeholder={t('collections.linkLabel')}
className="col-detail-input w-28"
/>
<input
value={l.url}
onChange={(e) => form.setLink(i, { url: e.target.value })}
placeholder="https://…"
className="col-detail-input flex-1"
/>
<button
type="button"
onClick={() => form.setLinks(form.links.filter((_, idx) => idx !== i))}
className="col-detail-icon-btn"
aria-label={t('common.delete')}
>
<Trash2 size={14} />
</button>
</div>
))}
<button
type="button"
onClick={() => form.setLinks([...form.links, { url: '' }])}
className="col-detail-add-link"
>
<Plus size={13} /> <Link2 size={12} /> {t('collections.addLink')}
</button>
</div>
</div>
</div>
);
}
/** The row of things to do with the place: edit, copy into a trip, get there, take it off the list. */
function Footer({
place,
form,
canEdit,
canDelete,
onCopyToTrip,
onRemove,
t,
}: {
place: CollectionPlace;
form: Form;
canEdit: boolean;
canDelete: boolean;
onCopyToTrip: () => void;
onRemove: () => void;
t: TranslationFn;
}) {
const [navOpen, setNavOpen] = useState(false);
const navBtnRef = useRef<HTMLButtonElement>(null);
const targets = getNavigationTargets(place);
if (form.editing) {
return (
<div className="col-detail-footer">
<div className="col-detail-footer-spacer" />
<button type="button" onClick={form.cancelEdit} className="col-detail-btn">
{t('common.cancel')}
</button>
<button
type="button"
onClick={() => void form.save()}
disabled={form.saving}
className="col-detail-btn primary"
>
<Check size={14} /> {t('common.save')}
</button>
</div>
);
}
return (
<div className="col-detail-footer">
{canEdit && (
<Tooltip label={t('common.edit')}>
<button
type="button"
onClick={() => form.setEditing(true)}
aria-label={t('common.edit')}
className="place-icon-btn"
>
<Pencil size={15} />
</button>
</Tooltip>
)}
{targets.length > 0 && (
<>
<button
ref={navBtnRef}
type="button"
className="col-detail-btn"
onClick={() => {
if (targets.length === 1) openNavigationTarget(targets[0]);
else setNavOpen((o) => !o);
}}
>
<Navigation size={14} />
{targets.length === 1 ? navigationTargetLabel(targets[0], t) : t('inspector.navigation')}
</button>
{navOpen && <NavigationMenu targets={targets} anchor={navBtnRef.current} onClose={() => setNavOpen(false)} />}
</>
)}
<button type="button" onClick={onCopyToTrip} className="col-detail-btn">
<Copy size={14} /> {t('collections.copyToTrip')}
</button>
{canDelete && (
<Tooltip label={t('collections.removeFromList')}>
<button
type="button"
onClick={onRemove}
aria-label={t('collections.removeFromList')}
className="place-icon-btn danger ms-auto"
>
<Trash2 size={15} />
</button>
</Tooltip>
)}
</div>
);
}
/**
* A place of a list, in the one place view All places opens too: a wide dialog
* with the place on the start side (its picture, name and position, the list's
* status and votes for it, the description and links, the things to do with it)
* and the same tabs beside it as anywhere else: where the place is kept and the
* tags it carries there, its notes, tours and bookings, pictures, and changes.
*/
export default function CollectionPlaceDetail({
place,
canEdit,
canDelete,
categories,
labels,
blocked,
onClose,
onSetStatus,
onSave,
onUploadImage,
onCopyToTrip,
onRemove,
onRate,
t,
}: CollectionPlaceDetailProps): React.ReactElement {
const labelId = useId();
const navigate = useNavigate();
const { language } = useTranslation();
// The list's own change (status, votes, an edit, a remote one) shows in the tabs too.
const library = useLibraryPlace('list', place.id, place);
const { reload } = library;
const save = async (patch: PlacePatch) => {
await onSave(patch);
reload();
};
const form = useCollectionPlaceForm({
place,
labels,
onSave: save,
onUploadImage,
t,
normalizeLinkUrl,
withCoordinates: true,
});
const sheet = usePlaceSheet({ data: library.data, onChanged: reload, t });
const tags = usePlaceTags({ data: library.data, onChanged: reload, t });
const { trips, lists } = originPairs(library.data);
const entry = library.data?.entry ?? null;
return (
<DialogShell
onClose={onClose}
labelledBy={labelId}
width="wide"
blocked={blocked}
header={null}
bodyClassName="trek-dash place-sheet"
discardGuard={
form.editing ? [form.name, form.description, form.address, form.lat, form.lng, form.links] : undefined
}
>
<aside className="place-aside">
<Cover
place={place}
form={form}
canEdit={canEdit}
categories={categories}
labelId={labelId}
onUploadImage={onUploadImage}
onClose={onClose}
t={t}
/>
<div className="place-aside-body">
<StatusSegment status={place.status} onSet={canEdit ? onSetStatus : () => {}} t={t} />
{/* Collaborative rating (#1435): every member votes, the average shows. */}
{onRate && (
<div className="place-rating">
<PlaceRating ratings={place.ratings ?? []} ratingAvg={place.rating_avg} onRate={onRate} />
</div>
)}
{form.editing ? (
<EditForm form={form} t={t} />
) : (
<>
{place.description ? (
<div className="col-detail-md collab-note-md">
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>
{place.description}
</Markdown>
</div>
) : null}
{place.links && place.links.length > 0 && (
<div className="col-detail-links">
{place.links.map((l, i) => (
<a key={i} href={l.url} target="_blank" rel="noopener noreferrer" className="col-detail-link">
<ExternalLink size={13} /> {l.label || linkHost(l.url)}
</a>
))}
</div>
)}
</>
)}
</div>
<Footer
place={place}
form={form}
canEdit={canEdit}
canDelete={canDelete}
onCopyToTrip={onCopyToTrip}
onRemove={onRemove}
t={t}
/>
</aside>
<PlaceSheetTabs
sheet={sheet}
onClose={onClose}
language={language}
t={t}
overview={
entry && (
<>
<PlaceTagsCard tags={tags} t={t} />
<PlaceOrigins
entry={entry}
trips={trips}
lists={lists}
language={language}
onOpenTrip={(tripId, placeId) => void navigate(`/trips/${tripId}?place=${placeId}`)}
onOpenList={(collectionId, placeId) => void navigate(`${placesPath(collectionId)}?place=${placeId}`)}
t={t}
/>
</>
)
}
/>
</DialogShell>
);
}
@@ -1,148 +0,0 @@
import type { CollectionLabel, CollectionPlace } from '@trek/shared';
import React, { createElement, useEffect, useRef, useState } from 'react';
import { getCategoryIcon } from '../shared/categoryIcons';
import { Tooltip } from '../shared/Tooltip';
/**
* One observer for every row and chip of a list, so a list of hundreds of places does
* not hold one per element. An element starts with one notification once observed.
*/
const sizeWatch = new Map<Element, () => void>();
let sizeObserver: ResizeObserver | null = null;
function watchSize(el: Element, onResize: () => void): () => void {
if (typeof ResizeObserver === 'undefined') return () => {};
sizeObserver ??= new ResizeObserver((entries) => {
for (const entry of entries) sizeWatch.get(entry.target)?.();
});
sizeWatch.set(el, onResize);
sizeObserver.observe(el);
return () => {
sizeWatch.delete(el);
sizeObserver?.unobserve(el);
};
}
/**
* The tooltip of a label or category chip: only while the chip cuts its name short,
* since one repeating the words on screen says nothing.
*/
function ChipTooltip({
label,
children,
}: {
label: string;
children: React.ReactElement<React.HTMLAttributes<HTMLElement> & React.RefAttributes<HTMLElement>>;
}): React.ReactElement {
const [cut, setCut] = useState(false);
const ref = useRef<HTMLElement | null>(null);
useEffect(() => {
const text = ref.current?.querySelector('.col-lrow-txt');
if (!text) return undefined;
return watchSize(text, () => setCut(text.scrollWidth > text.clientWidth + 1));
}, []);
return (
<Tooltip label={label} placement="top" disabled={!cut}>
{React.cloneElement(children, { ref })}
</Tooltip>
);
}
/** The room a "+N" chip takes, held free while the labels are fitted. */
const MORE_CHIP = 34;
/**
* A chip's own width, also while the row squeezes it: the part its name is cut short by
* is the name's scroll width over its box, up to the widest the chip may grow.
*/
const naturalWidth = (el: HTMLElement): number => {
const text = el.querySelector<HTMLElement>('.col-lrow-txt');
const full = el.offsetWidth + (text ? text.scrollWidth - text.clientWidth : 0);
const cap = parseFloat(getComputedStyle(el).maxWidth);
return Number.isFinite(cap) ? Math.min(full, cap) : full;
};
/**
* How many labels fit beside the category in `row`: as many as it holds with room left
* for the "+N" chip, and at least one, which then shortens its name. Every label is in
* the row, the ones that do not fit kept out of sight, so each can be measured.
*/
function labelsThatFit(row: HTMLElement): number {
const gap = parseFloat(getComputedStyle(row).columnGap) || 0;
const labels = Array.from(row.querySelectorAll<HTMLElement>('.col-lrow-label'));
const fixed = Array.from(row.querySelectorAll<HTMLElement>('.col-lrow-cat, .col-lrow-div'))
.filter((el) => el.offsetWidth > 0)
.reduce((sum, el) => sum + naturalWidth(el) + gap, 0);
let used = fixed;
let fit = 0;
for (let i = 0; i < labels.length; i++) {
const left = labels.length - i - 1;
const need = used + naturalWidth(labels[i]) + (left > 0 ? gap + MORE_CHIP : 0);
if (need > row.clientWidth && i > 0) break;
used += naturalWidth(labels[i]) + gap;
fit = i + 1;
}
return fit;
}
/**
* A place row's category and labels, on one line that never wraps (#2981). The category
* comes first, then as many labels as the row has room for, then a "+N" chip naming the
* rest in its tooltip, so a wide list shows every label and a narrow one the first.
*/
export default function CollectionPlaceTags({
place,
labels,
showCategory = true,
}: {
place: CollectionPlace;
labels: CollectionLabel[];
/** Off where the row shows the category on the place's tile instead. */
showCategory?: boolean;
}): React.ReactElement | null {
const ref = useRef<HTMLDivElement>(null);
const [fit, setFit] = useState(labels.length);
const labelKey = labels.map((l) => `${l.id}:${l.name}`).join('|');
const categoryName = showCategory ? (place.category?.name ?? null) : null;
// Fitted on every change of the row's width and once more whenever its labels change:
// observing anew hands the observer's first notification to the new labels.
useEffect(() => {
const row = ref.current;
if (!row) return undefined;
return watchSize(row, () => setFit(labelsThatFit(row)));
}, [labelKey, categoryName]);
if (!labels.length && !categoryName) return null;
const shown = Math.min(labels.length, Math.max(1, fit));
const hidden = labels.slice(shown);
return (
<div ref={ref} className="col-lrow-tags">
{categoryName && (
<ChipTooltip label={categoryName}>
<span className="col-lrow-cat" style={{ ['--cat' as string]: place.category?.color || '#6366f1' }}>
{createElement(getCategoryIcon(place.category?.icon ?? undefined), { size: 11 })}{' '}
<span className="col-lrow-txt">{categoryName}</span>
</span>
</ChipTooltip>
)}
{labels.map((l, i) => (
<ChipTooltip key={l.id} label={l.name}>
<span
className={i < shown ? 'col-lrow-label' : 'col-lrow-label is-over'}
style={{ ['--label' as string]: l.color || 'var(--accent)' }}
aria-hidden={i < shown ? undefined : true}
>
<span className="col-labelchip-dot" /> <span className="col-lrow-txt">{l.name}</span>
</span>
</ChipTooltip>
))}
{hidden.length > 0 && (
<Tooltip label={hidden.map((l) => l.name).join(', ')} placement="top">
<span className="col-lrow-more">+{hidden.length}</span>
</Tooltip>
)}
<span className="col-lrow-div" aria-hidden />
</div>
);
}
@@ -1,4 +1,4 @@
import { NotebookPen, Tag } from 'lucide-react';
import { Check, NotebookPen, Tag } from 'lucide-react';
import React from 'react';
import type { TranslationFn } from '../../types';
import ToggleSwitch from '../Settings/ToggleSwitch';
@@ -8,10 +8,9 @@ interface CopyCarryPanelProps {
options: CopyCarryOptions;
includeNotes: boolean;
onIncludeNotes: (on: boolean) => void;
tagIds: number[];
onToggleTag: (id: number) => void;
personalTagIds?: number[];
onTogglePersonalTag?: (id: number) => void;
/** The picked tags, by their carry keys. */
tagIds: string[];
onToggleTag: (key: string) => void;
/** The phone sheet wears the mobile tokens, the desktop dialog the app's. */
variant: 'dialog' | 'sheet';
t: TranslationFn;
@@ -19,74 +18,64 @@ interface CopyCarryPanelProps {
const LOOK = {
dialog: {
box: 'rounded-[14px] border border-edge-faint bg-surface-secondary px-3.5 py-3',
title: 'text-content-muted',
label: 'text-content',
box: 'rounded-[16px] border border-edge-faint bg-surface-secondary',
tile: 'bg-surface-card text-content-muted',
title: 'text-content',
hint: 'text-content-faint',
chipOff: 'border-edge-faint bg-surface-card text-content-muted',
chipOn: 'border-accent bg-accent text-accent-text',
eyebrow: 'text-content-faint',
chip: 'border-edge-faint bg-surface-card text-content-muted',
link: 'text-content-muted hover:text-content',
},
sheet: {
box: 'rounded-2xl border border-m-rowbr bg-m-sheetop px-3.5 py-3',
title: 'text-m-muted',
label: 'text-m-ink',
box: 'rounded-[18px] border border-m-rowbr bg-m-sheetop',
tile: 'bg-m-ic text-m-muted',
title: 'text-m-ink',
hint: 'text-m-faint',
chipOff: 'border-m-rowbr bg-m-ic text-m-muted',
chipOn: 'border-m-act bg-m-act text-m-actfg',
eyebrow: 'text-m-faint',
chip: 'border-m-rowbr bg-m-ic text-m-muted',
link: 'text-m-muted',
},
} 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({
/** One thing that can come along: a tile, what it is, a line on it, and its control. */
function Option({
icon,
title,
hint,
tags,
picked,
onToggle,
control,
look,
children,
}: {
icon: React.ReactNode;
title: string;
hint: string;
tags: { id: number; name: string; color?: string | null }[];
picked: number[];
onToggle: (id: number) => void;
control?: React.ReactNode;
look: Look;
children?: React.ReactNode;
}) {
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 className="flex flex-col gap-2.5 px-3.5 py-3">
<div className="flex items-center gap-3">
<span className={`grid h-9 w-9 flex-none place-items-center rounded-[10px] ${look.tile}`} aria-hidden="true">
{icon}
</span>
<div className="min-w-0 flex-1">
<div className={`text-body font-semibold ${look.title}`}>{title}</div>
<div className={`text-caption ${look.hint}`}>{hint}</div>
</div>
{control}
</div>
{children}
</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
* tag taken along becomes a tag of the trip, shared with its travellers.
* What goes along when saved places are copied into a trip (#3168): the list's
* notes and the list's tags. Nothing comes along unless it is picked here; a tag
* taken along becomes a tag of the trip, which everyone in the trip sees.
*/
export default function CopyCarryPanel({
options,
@@ -94,49 +83,82 @@ export default function CopyCarryPanel({
onIncludeNotes,
tagIds,
onToggleTag,
personalTagIds,
onTogglePersonalTag,
variant,
t,
}: CopyCarryPanelProps): React.ReactElement {
const look = LOOK[variant];
const allOn = options.tags.length > 0 && options.tags.every((tag) => tagIds.includes(tag.key));
const toggleAll = () => {
for (const tag of options.tags) if (tagIds.includes(tag.key) === allOn) onToggleTag(tag.key);
};
return (
<section className={`flex flex-col gap-3 ${look.box}`} aria-label={t('collections.copyCarry.title')}>
<div className={`text-caption font-semibold ${look.title}`}>{t('collections.copyCarry.title')}</div>
{options.hasNotes && (
<div className="flex items-center gap-3">
<NotebookPen size={15} className={`flex-none ${look.hint}`} aria-hidden="true" />
<div className="min-w-0 flex-1">
<div className={`text-body font-semibold ${look.label}`}>{t('collections.copyCarry.notes')}</div>
<div className={`text-caption ${look.hint}`}>{t('collections.copyCarry.notesHint')}</div>
</div>
<ToggleSwitch
on={includeNotes}
onToggle={() => onIncludeNotes(!includeNotes)}
label={t('collections.copyCarry.notes')}
<section className="flex flex-col gap-2" aria-label={t('collections.copyCarry.title')}>
<div className={`px-1 text-caption font-semibold ${look.eyebrow}`}>{t('collections.copyCarry.title')}</div>
<div
className={`flex flex-col divide-y ${look.box} ${variant === 'dialog' ? 'divide-edge-faint' : 'divide-m-rowbr'}`}
>
{options.hasNotes && (
<Option
icon={<NotebookPen size={16} />}
title={t('collections.copyCarry.notes')}
hint={t('collections.copyCarry.notesHint')}
look={look}
control={
<ToggleSwitch
on={includeNotes}
onToggle={() => onIncludeNotes(!includeNotes)}
label={t('collections.copyCarry.notes')}
/>
}
/>
</div>
)}
{options.tags.length > 0 && (
<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}
/>
)}
)}
{options.tags.length > 0 && (
<Option
icon={<Tag size={16} />}
title={t('collections.copyCarry.tags')}
hint={t('collections.copyCarry.tagsHint')}
look={look}
control={
<button type="button" onClick={toggleAll} className={`flex-none text-caption font-semibold ${look.link}`}>
{allOn ? t('collections.copyCarry.none') : t('collections.copyCarry.all')}
</button>
}
>
<div className="flex flex-wrap gap-1.5 ps-12" role="group" aria-label={t('collections.copyCarry.tags')}>
{options.tags.map((tag) => {
const on = tagIds.includes(tag.key);
const color = tag.color || 'var(--accent)';
return (
<button
key={tag.key}
type="button"
aria-pressed={on}
onClick={() => onToggleTag(tag.key)}
className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-caption font-semibold ${on ? '' : look.chip}`}
// The tag's own colour carries the picked chip; an unpicked one stays quiet.
style={
on
? {
color,
background: `color-mix(in srgb, ${color} 14%, transparent)`,
borderColor: `color-mix(in srgb, ${color} 40%, transparent)`,
}
: undefined
}
>
{on ? (
<Check size={12} strokeWidth={2.6} />
) : (
<span className="h-2 w-2 flex-none rounded-full" style={{ background: color }} />
)}
{tag.name}
</button>
);
})}
</div>
</Option>
)}
</div>
</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, personalTagIds, togglePersonalTag } =
const { loading, search, setSearch, filtered, busyTripId, dateRange, handleCopy, offersCarry, includeNotes, setIncludeNotes, tagIds, toggleTag } =
useTripCopyPicker({ open: isOpen, onCopy, onClose, t, emptySelection: placeIds.length === 0, carryOptions })
if (!isOpen) return null
@@ -36,8 +36,6 @@ export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, car
onClose={onClose}
labelledBy={labelId}
width="narrow"
// The list shrinks while the search narrows it; a pinned top edge keeps the field still.
align="top"
header={(
<DialogHeader
tile={<DialogTile><Copy size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>}
@@ -66,8 +64,11 @@ export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, car
/>
</div>
{offersCarry && carryOptions && (
<CopyCarryPanel options={carryOptions} includeNotes={includeNotes} onIncludeNotes={setIncludeNotes} tagIds={tagIds} onToggleTag={toggleTag} personalTagIds={personalTagIds} onTogglePersonalTag={togglePersonalTag} variant="dialog" t={t} />
<CopyCarryPanel options={carryOptions} includeNotes={includeNotes} onIncludeNotes={setIncludeNotes} tagIds={tagIds} onToggleTag={toggleTag} variant="dialog" t={t} />
)}
{/* One fixed height for the trips, whatever the search leaves: the centred dialog
then keeps its size and the search field stays where it is while typing. */}
<div className="h-[min(360px,45vh)] overflow-y-auto">
{loading ? (
<div className="flex items-center justify-center py-8 text-content-faint">
<Loader2 size={20} className="animate-spin" />
@@ -104,6 +105,7 @@ export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, car
})}
</div>
)}
</div>
</DialogShell>
)
}
@@ -1,12 +1,15 @@
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.
* The tags of a row of All places, from its lists and trips: 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 {
export default function EntryTagDots({
tags,
}: {
tags: readonly { name: string; color?: string | null }[] | undefined;
}): React.ReactElement | null {
if (!tags?.length) return null;
return (
<Tooltip label={tags.map((tag) => tag.name).join(', ')}>
@@ -17,7 +20,7 @@ export default function EntryTagDots({ tags }: { tags: PlacesLibraryTag[] | unde
>
{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 key={tag.name} className="h-2 w-2 rounded-full" style={{ background: tag.color || 'var(--accent)' }} />
))}
</span>
</Tooltip>
@@ -1,202 +0,0 @@
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>
);
}
@@ -1,8 +1,9 @@
import type { CollectionStatus, PlacesLibraryCounts, PlacesLibrarySort, Tag as TagRow } from '@trek/shared';
import { ArrowDownUp, Bookmark, CopyCheck, Globe2, Layers, Luggage, Tag } from 'lucide-react';
import type { CollectionStatus, PlacesLibraryCounts, PlacesLibrarySort } from '@trek/shared';
import { ArrowDownUp, Bookmark, CopyCheck, Globe2, Layers, Luggage, Star, Tag } from 'lucide-react';
import React from 'react';
import type { Category, TranslationFn } from '../../types';
import { getCategoryIcon } from '../shared/categoryIcons';
import { FilledStar } from '../shared/StarRating';
import { STATUS_META, STATUS_ORDER } from './collectionStatus';
import FilterDropdown, { type FilterOption } from './FilterDropdown';
import TagFilterDropdown from './TagFilterDropdown';
@@ -19,21 +20,26 @@ interface LibraryFilterBarProps {
onCategory: (id: number | 'all') => void;
sort: PlacesLibrarySort;
onSort: (sort: PlacesLibrarySort) => void;
/** At least this many stars on the average vote, or all places. */
minRating?: number | 'all';
onMinRating?: (minRating: number | 'all') => void;
/** How many pairs look like one place (PLC-13); the button shows while there are any. */
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;
/** The tag names on the places, and the ones the list is narrowed to. */
tags?: readonly { name: string; color: string | null }[];
tagNames?: readonly string[];
onToggleTag?: (name: string) => void;
t: TranslationFn;
}
const RATING_FLOORS = [5, 4, 3, 2, 1] as const;
/**
* The filter row of "All places", built from the same compact dropdowns as the
* lists' row: where a place comes from (trips, lists or both, with their counts),
* the status it has in a list, its category, and the order.
* the status it has in a list, its category, its rating, and the order.
*/
export default function LibraryFilterBar({
kind,
@@ -46,11 +52,13 @@ export default function LibraryFilterBar({
onCategory,
sort,
onSort,
minRating = 'all',
onMinRating,
duplicates = 0,
duplicatesMore = false,
onDuplicates,
tags = [],
tagIds = [],
tagNames = [],
onToggleTag,
t,
}: LibraryFilterBarProps): React.ReactElement {
@@ -77,9 +85,15 @@ export default function LibraryFilterBar({
return { key: c.id, label: c.name, icon: <Icon size={13} style={{ color: c.color ?? undefined }} /> };
}),
];
// As the lists' rating filter: all, then at least 5 down to 1 stars.
const ratingOpts: FilterOption[] = [
{ key: 'all', label: t('common.all') },
...RATING_FLOORS.map((n) => ({ key: n, label: `${n}+`, icon: <FilledStar size={13} /> })),
];
const sortOpts: FilterOption[] = [
{ key: 'name', label: t('collections.sort.nameAsc') },
{ key: 'updated', label: t('collections.library.sortUpdated') },
{ key: 'rating', label: t('collections.library.sortRating') },
];
return (
<div className="col-filterbar">
@@ -103,7 +117,15 @@ export default function LibraryFilterBar({
lead={<Tag size={13} />}
/>
)}
{onToggleTag && <TagFilterDropdown tags={tags} picked={tagIds} onToggle={onToggleTag} t={t} />}
{onMinRating && (
<FilterDropdown
current={minRating}
options={ratingOpts}
onSelect={(k) => onMinRating(k as number | 'all')}
lead={<Star size={13} />}
/>
)}
{onToggleTag && <TagFilterDropdown tags={tags} picked={tagNames} onToggle={onToggleTag} t={t} />}
<FilterDropdown
current={sort}
options={sortOpts}
@@ -1,45 +1,25 @@
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import {
Bookmark,
BookmarkPlus,
ChevronRight,
Copy,
Hotel,
Loader2,
Luggage,
Navigation,
Star,
Ticket,
X,
} from 'lucide-react';
import React, { createElement, useRef, useState } from 'react';
import type { TranslationFn } from '../../types';
import { BookmarkPlus, Check, Copy, Loader2, Navigation, Pencil } from 'lucide-react';
import React, { createElement, useId, useRef, useState } from 'react';
import type { Category, TranslationFn } from '../../types';
import { entityGradient } from '../../utils/gradients';
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation';
import { getCategoryIcon } from '../shared/categoryIcons';
import { DialogShell } from '../shared/DialogShell';
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,
type ListDetail,
type ListOrigin,
type ListPair,
type TripDetail,
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 { Tooltip } from '../shared/Tooltip';
import { originPairs, type ListPair, type TripDetail, type TripOrigin, type TripPair } from './libraryPairs';
import PlaceEditForm from './PlaceEditForm';
import PlaceLocationBadge from './PlaceLocationBadge';
import PlaceMediaSection from './PlaceMediaSection';
import StatusBadge from './StatusBadge';
import VisitsSection from './VisitsSection';
import PlaceOrigins from './PlaceOrigins';
import PlaceRatingRow from './PlaceRatingRow';
import './placeSheet.css';
import PlaceSheetTabs from './PlaceSheetTabs';
import PlaceTagsCard from './PlaceTagsCard';
import { usePlaceEdit, type PlaceEditState } from './usePlaceEdit';
import { usePlaceRating } from './usePlaceRating';
import { usePlaceSheet } from './usePlaceSheet';
import { usePlaceTags } from './usePlaceTags';
interface LibraryPlaceDetailProps {
data: PlacesLibraryDetailResponse | null;
@@ -47,8 +27,9 @@ interface LibraryPlaceDetailProps {
/** The place's own image, or the provider's photo for it. */
cover: string | null;
language: string;
/** Where the sheet docks: over the list column in the split, centred otherwise. */
anchorRect?: DockRect | null;
categories: Category[];
/** True while a dialog opened from here is open: Escape and the backdrop leave this one alone. */
blocked?: boolean;
onClose: () => void;
onOpenList: (collectionId: number, collectionPlaceId: number) => void;
onOpenTrip: (tripId: number, placeId: number) => void;
@@ -56,159 +37,23 @@ 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. */
/** Something of the place was saved: read it again. */
onNotesSaved: () => void;
t: TranslationFn;
}
function TripCard({
origin,
detail,
entryName,
language,
onOpen,
t,
}: {
origin: TripOrigin;
detail: TripDetail;
entryName: string;
language: string;
onOpen: () => void;
t: TranslationFn;
}) {
const line = tripLine(origin, detail, language, t);
const extras = detail.has_accommodation || detail.has_reservation || detail.info.name !== entryName;
return (
<button
type="button"
className="col-origin"
onClick={onOpen}
aria-label={`${t('collections.library.openTrip')}: ${originName(origin)}`}
>
<span className="col-origin-head">
<span className="col-origin-ico">
{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>
{line && <span className="sub">{line}</span>}
</span>
{origin.read_only && <span className="col-origin-tag">{t('collections.library.readOnly')}</span>}
<ChevronRight size={16} className="col-origin-chev" />
</span>
{extras && (
<span className="col-origin-chips">
{detail.info.name !== entryName && (
<span className="col-origin-chip">{t('collections.library.calledHere', { name: detail.info.name })}</span>
)}
{detail.has_accommodation && (
<span className="col-origin-chip">
<Hotel size={11} /> {t('collections.library.stay')}
</span>
)}
{detail.has_reservation && (
<span className="col-origin-chip">
<Ticket size={11} /> {t('collections.library.booking')}
</span>
)}
</span>
)}
</button>
);
}
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;
}) {
const extras = detail.labels.length > 0 || detail.rating.average != null || detail.info.name !== entryName;
return (
<button
type="button"
className="col-origin"
onClick={onOpen}
aria-label={`${t('collections.library.openList')}: ${originName(origin)}`}
>
<span className="col-origin-head">
<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>
{!compact && <StatusBadge status={origin.status} t={t} />}
<ChevronRight size={16} className="col-origin-chev" />
</span>
{extras && (
<span className="col-origin-chips">
{detail.info.name !== entryName && (
<span className="col-origin-chip">{t('collections.library.calledHere', { name: detail.info.name })}</span>
)}
{detail.labels.map((label) => (
<span
key={label.id}
className="col-labelchip on static"
style={{ ['--label' as string]: label.color || 'var(--accent)' }}
>
<span className="col-labelchip-dot" /> {label.name}
</span>
))}
{detail.rating.average != null && (
<span className="col-origin-chip">
<Star size={11} />{' '}
{t('collections.library.rating', {
rating: detail.rating.average.toFixed(1),
count: detail.rating.count,
})}
</span>
)}
</span>
)}
</button>
);
}
type Entry = NonNullable<PlacesLibraryDetailResponse['entry']>;
/** The cover band: the picture or a gradient, the category, the close button and the name. */
/** The cover band: the picture or a gradient, the category and the name. */
function DetailCover({
entry,
cover,
onClose,
labelId,
t,
}: {
entry: Entry | null;
cover: string | null;
onClose: () => void;
labelId: string;
t: TranslationFn;
}) {
const gradient = entry ? entry.key.length + entry.name.length : 0;
@@ -226,13 +71,12 @@ function DetailCover({
<span className="truncate">{entry.category.name}</span>
</span>
)}
<button type="button" className="col-detail-close ms-auto" onClick={onClose} aria-label={t('common.close')}>
<X size={16} />
</button>
</div>
{entry && (
<div className="col-detail-head">
<h2 className="col-detail-name">{entry.name}</h2>
<h2 id={labelId} className="col-detail-name">
{entry.name}
</h2>
<PlaceLocationBadge address={entry.address} lat={entry.lat} lng={entry.lng} t={t} />
</div>
)}
@@ -240,88 +84,12 @@ function DetailCover({
);
}
/** The body: where it is, its description, then every trip and every list it sits in. */
function DetailBody({
data,
onNotesSaved,
entry,
trips,
lists,
description,
language,
onOpenTrip,
onOpenList,
t,
}: {
data: PlacesLibraryDetailResponse | null;
onNotesSaved: () => void;
entry: Entry;
trips: TripPair[];
lists: ListPair[];
description: string | undefined;
language: string;
onOpenTrip: (tripId: number, placeId: number) => void;
onOpenList: (collectionId: number, collectionPlaceId: number) => void;
t: TranslationFn;
}) {
const paired = trips.length > 0 && lists.length > 0;
return (
<>
{description && <div className="col-detail-md whitespace-pre-wrap">{description}</div>}
{/* 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} />
</>
);
}
/** The footer: navigate there, save the trip's place to a list, copy the list's place to a trip. */
/** The footer: edit, navigate there, save the trip's place to a list, copy the list's place to a trip. */
function DetailFooter({
entry,
trip,
list,
edit,
onSaveToList,
onCopyToTrip,
t,
@@ -329,6 +97,7 @@ function DetailFooter({
entry: Entry;
trip: TripPair | undefined;
list: ListPair | undefined;
edit: PlaceEditState;
onSaveToList: (origin: TripOrigin, detail: TripDetail) => void;
onCopyToTrip: (collectionPlaceId: number) => void;
t: TranslationFn;
@@ -337,8 +106,33 @@ function DetailFooter({
const navRef = useRef<HTMLButtonElement>(null);
const targets = getNavigationTargets({ name: entry.name, address: entry.address, lat: entry.lat, lng: entry.lng });
const single = targets.length === 1 ? targets[0] : null;
if (edit.editing) {
return (
<div className="col-detail-footer">
<div className="col-detail-footer-spacer" />
<button type="button" onClick={edit.cancel} className="col-detail-btn">
{t('common.cancel')}
</button>
<button
type="button"
onClick={() => void edit.save()}
disabled={edit.saving}
className="col-detail-btn primary"
>
<Check size={14} /> {t('common.save')}
</button>
</div>
);
}
return (
<div className="col-detail-footer">
{edit.canEdit && (
<Tooltip label={t('common.edit')}>
<button type="button" onClick={edit.start} aria-label={t('common.edit')} className="place-icon-btn">
<Pencil size={15} />
</button>
</Tooltip>
)}
{targets.length > 0 && (
<>
<button
@@ -352,8 +146,7 @@ function DetailFooter({
{navOpen && <NavigationMenu targets={targets} anchor={navRef.current} onClose={() => setNavOpen(false)} />}
</>
)}
<div className="col-detail-footer-spacer" />
{trip && (
{trip && !list && (
<button type="button" className="col-detail-btn" onClick={() => onSaveToList(trip.origin, trip.detail)}>
<BookmarkPlus size={14} /> {t('inspector.saveToCollection')}
</button>
@@ -368,17 +161,19 @@ function DetailFooter({
}
/**
* One place of "All places" (PLC-08), in the same sheet a saved place opens in:
* docked over the list column, cover and category on top, then every trip and list
* the place sits in with what each keeps of it, so a note from a list and a day from
* a trip are never mistaken for one another. The list stays as it was underneath.
* One place of All places (PLC-08) in the one place view a list opens too: a wide
* dialog with the place on the start side (cover, name, where it is, what it is,
* the things to do with it) and its tabs beside it. The overview names every trip
* and list it sits in and the tags they give it; the other tabs hold its notes,
* tours and bookings, pictures and files, and its changes.
*/
export default function LibraryPlaceDetail({
data,
loading,
cover,
language,
anchorRect,
categories,
blocked,
onClose,
onOpenList,
onOpenTrip,
@@ -387,48 +182,73 @@ export default function LibraryPlaceDetail({
onNotesSaved,
t,
}: LibraryPlaceDetailProps): React.ReactElement {
const labelId = useId();
const entry = data?.entry ?? null;
const { trips, lists, description } = originPairs(data);
const sheet = usePlaceSheet({ data, onChanged: onNotesSaved, t });
const tags = usePlaceTags({ data, onChanged: onNotesSaved, t });
const edit = usePlaceEdit({ data, onSaved: onNotesSaved, t });
const rating = usePlaceRating({ data, onChanged: onNotesSaved, t });
return (
<div
className={anchorRect ? 'col-detail docked' : 'col-detail'}
style={dockStyle(anchorRect)}
role="dialog"
aria-label={entry?.name ?? t('collections.library.title')}
<DialogShell
onClose={onClose}
labelledBy={labelId}
width="wide"
blocked={blocked}
header={null}
bodyClassName="trek-dash place-sheet"
discardGuard={edit.editing ? edit.draft : undefined}
>
<DetailCover entry={entry} cover={cover} onClose={onClose} t={t} />
<div className="col-detail-body">
{loading && !entry && (
<div className="flex justify-center py-6 text-content-faint">
<Loader2 size={20} className="animate-spin" />
</div>
)}
<aside className="place-aside">
<DetailCover entry={entry} cover={cover} labelId={labelId} t={t} />
<div className="place-aside-body">
{entry && !edit.editing && <PlaceRatingRow rating={rating} />}
{loading && !entry && (
<div className="flex justify-center py-6 text-content-faint">
<Loader2 size={20} className="animate-spin" />
</div>
)}
{edit.editing ? (
<PlaceEditForm edit={edit} categories={categories} t={t} />
) : (
description && <div className="col-detail-md whitespace-pre-wrap">{description}</div>
)}
</div>
{entry && (
<DetailBody
data={data}
onNotesSaved={onNotesSaved}
<DetailFooter
entry={entry}
trips={trips}
lists={lists}
description={description}
language={language}
onOpenTrip={onOpenTrip}
onOpenList={onOpenList}
trip={trips[0]}
list={lists[0]}
edit={edit}
onSaveToList={onSaveToList}
onCopyToTrip={onCopyToTrip}
t={t}
/>
)}
</div>
{entry && (
<DetailFooter
entry={entry}
trip={trips[0]}
list={lists[0]}
onSaveToList={onSaveToList}
onCopyToTrip={onCopyToTrip}
t={t}
/>
)}
</div>
</aside>
<PlaceSheetTabs
sheet={sheet}
onClose={onClose}
language={language}
t={t}
overview={
entry && (
<>
<PlaceTagsCard tags={tags} t={t} />
<PlaceOrigins
entry={entry}
trips={trips}
lists={lists}
language={language}
onOpenTrip={onOpenTrip}
onOpenList={onOpenList}
t={t}
/>
</>
)
}
/>
</DialogShell>
);
}
@@ -1,16 +1,173 @@
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import { Bookmark, Luggage, NotebookPen, Pencil, Plus } from 'lucide-react';
import React from 'react';
import { Bookmark, Eye, Layers, Luggage, NotebookPen, Pencil, PenLine } from 'lucide-react';
import React, { useRef } from 'react';
import Markdown from 'react-markdown';
import remarkBreaks from 'remark-breaks';
import remarkGfm from 'remark-gfm';
import type { TranslationFn } from '../../types';
import { TEXTAREA } from '../shared/dialogParts';
import MarkdownToolbar from '../Journey/MarkdownToolbar';
import { markdownLinkComponents } from '../shared/markdownLink';
import { Tooltip } from '../shared/Tooltip';
import { useOriginNotes } from './useOriginNotes';
import PlaceCard from './PlaceCard';
import { useOriginNotes, type OriginNote } from './useOriginNotes';
type Notes = ReturnType<typeof useOriginNotes>;
const SourceIcon = ({ kind }: { kind: 'trip' | 'list' }) =>
kind === 'trip' ? <Luggage size={12} /> : <Bookmark size={12} />;
/** A note as written: markdown with links, under where it is kept. */
function NoteCard({ note, n, t }: { note: OriginNote; n: Notes; t: TranslationFn }) {
return (
<article className="place-note">
<header className="place-note-head">
<SourceIcon kind={note.kind} />
<span className="min-w-0 flex-1 truncate">{note.source}</span>
{note.canEdit && (
<Tooltip label={t('placeNotes.edit')}>
<button
type="button"
onClick={() => n.edit(note)}
aria-label={t('placeNotes.edit')}
className="place-note-edit"
>
<Pencil size={13} />
</button>
</Tooltip>
)}
</header>
<div className="col-detail-md collab-note-md place-note-body">
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>
{note.text}
</Markdown>
</div>
</article>
);
}
/**
* 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.
* Writing a note: where it goes (chips, while it is a new one), a markdown
* toolbar, writing or a preview of how it reads, and save. Ctrl or Cmd + Enter saves.
*/
function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) {
const ref = useRef<HTMLTextAreaElement>(null);
const current = n.composeTargets.find((x) => x.key === n.editing) ?? n.notes.find((x) => x.key === n.editing);
const multi = n.isNew && n.composeTargets.length > 1;
return (
<>
{multi && (
<div className="place-editor-for">
<span className="me-1">{t('placeNotes.for')}</span>
<button
type="button"
aria-pressed={n.everywhere}
onClick={() => n.retarget('all')}
data-no-press
className={n.everywhere ? 'place-for-chip on' : 'place-for-chip'}
>
<Layers size={12} /> {t('placeMedia.everywhere')}
</button>
{n.composeTargets.map((x) => (
<button
key={x.key}
type="button"
aria-pressed={!n.everywhere && x.key === n.editing}
onClick={() => n.retarget(x.key)}
data-no-press
className={!n.everywhere && x.key === n.editing ? 'place-for-chip on' : 'place-for-chip'}
>
<SourceIcon kind={x.kind} /> {x.source}
</button>
))}
</div>
)}
<div className="place-editor">
{!multi && current && (
<div className="place-note-head">
<SourceIcon kind={current.kind} />
<span className="min-w-0 flex-1 truncate">{current.source}</span>
</div>
)}
<div className="place-editor-bar">
{!n.preview && <MarkdownToolbar textareaRef={ref} onUpdate={n.setDraft} />}
<div className="place-seg ms-auto" role="group">
<button type="button" aria-pressed={!n.preview} onClick={() => n.setPreview(false)}>
<PenLine size={12} /> {t('placeNotes.write')}
</button>
<button type="button" aria-pressed={n.preview} onClick={() => n.setPreview(true)}>
<Eye size={12} /> {t('placeNotes.preview')}
</button>
</div>
</div>
{n.preview ? (
<div className="col-detail-md collab-note-md place-editor-preview">
{n.draft.trim() ? (
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>
{n.draft}
</Markdown>
) : (
<span className="col-origin-sub">{t('placeNotes.nothingYet')}</span>
)}
</div>
) : (
<textarea
ref={ref}
autoFocus
rows={6}
value={n.draft}
onChange={(e) => n.setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
void n.save();
}
}}
placeholder={t('placeNotes.placeholder')}
aria-label={current ? t('placeNotes.fieldLabel', { source: current.source }) : t('collections.notes')}
className="place-editor-text"
/>
)}
<footer className="place-editor-foot">
<span className="col-origin-sub">{t('placeNotes.markdownHint')}</span>
<button type="button" onClick={n.cancel} className="col-detail-btn ms-auto">
{t('common.cancel')}
</button>
<button type="button" onClick={() => void n.save()} disabled={n.busy} className="col-detail-btn primary">
{t('common.save')}
</button>
</footer>
</div>
</>
);
}
/**
* The notes of a place in the desktop view (PLC-17): each trip's and each list's
* own, rendered as markdown under where it is kept, then a "write a note" field
* that opens the editor. A note is edited where it lives and only where allowed.
*/
export function OriginNotesView({ state: n, t }: { state: Notes; t: TranslationFn }): React.ReactElement | null {
if (n.notes.length === 0 && n.targets.length === 0 && !n.editing) return null;
return (
<PlaceCard icon={NotebookPen} title={t('collections.notes')} count={n.notes.filter((x) => x.text.trim()).length}>
{n.notes.map((note) =>
n.editing === note.key && !n.isNew ? (
<NoteEditor key={note.key} n={n} t={t} />
) : (
note.text.trim() && <NoteCard key={note.key} note={note} n={n} t={t} />
)
)}
{n.isNew && <NoteEditor n={n} t={t} />}
{!n.editing && n.targets.length > 0 && (
<button type="button" onClick={n.compose} className="place-composer">
<PenLine size={15} />
{t('placeNotes.composer')}
</button>
)}
</PlaceCard>
);
}
export default function OriginNotesSection({
data,
onSaved,
@@ -21,72 +178,5 @@ export default function OriginNotesSection({
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>
);
return <OriginNotesView state={n} t={t} />;
}
@@ -4,6 +4,7 @@ import React from 'react';
import { useNavigate } from 'react-router';
import type { TranslationFn } from '../../types';
import { Tooltip } from '../shared/Tooltip';
import PlaceCard from './PlaceCard';
import { activityLine } from './placeExtrasText';
import { activityHref, usePlaceActivities } from './usePlaceActivities';
@@ -20,42 +21,43 @@ function ActivityIcon({ type }: { type: PlaceActivity['type'] }) {
* 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,
export function PlaceActivitiesView({
state: a,
language,
t,
}: {
entry: PlacesLibraryEntry;
state: ReturnType<typeof usePlaceActivities>;
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"
>
<PlaceCard
icon={Ticket}
title={t('placeActivities.title')}
count={a.activities.length}
action={
a.canLink &&
!a.picking && (
<button type="button" onClick={() => void a.openPicker()} disabled={a.busy} className="col-detail-action">
<Plus size={13} /> {t('placeActivities.link')}
</button>
)}
</div>
)
}
rows={a.activities.length > 0}
>
{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">
<button
type="button"
onClick={() => void navigate(activityHref(act))}
className="col-origin-title text-start"
>
<span className="nm">{act.title}</span>
<span className="sub">{activityLine(act, language, t)}</span>
</button>
@@ -77,10 +79,20 @@ export default function PlaceActivitiesSection({
</span>
</div>
))}
{a.activities.length === 0 && !a.picking && <p className="col-origin-sub m-0">{t('placeActivities.none')}</p>}
{a.activities.length === 0 && !a.picking && (
<button
type="button"
onClick={() => void a.openPicker()}
disabled={!a.canLink || a.busy}
className="place-composer"
>
<Link2 size={15} />
{t('placeActivities.none')}
</button>
)}
{a.picking && (
<div className="col-origin cursor-default">
<span className="flex items-center gap-2 text-caption font-semibold text-content-muted">
<span className="place-pick-head">
<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} />
@@ -111,6 +123,19 @@ export default function PlaceActivitiesSection({
)}
</div>
)}
</section>
</PlaceCard>
);
}
export default function PlaceActivitiesSection({
entry,
language,
t,
}: {
entry: PlacesLibraryEntry;
language: string;
t: TranslationFn;
}): React.ReactElement | null {
const a = usePlaceActivities({ entry, t });
return <PlaceActivitiesView state={a} language={language} t={t} />;
}
@@ -0,0 +1,41 @@
import type { LucideIcon } from 'lucide-react';
import React, { createElement } from 'react';
/**
* One group of the place view (tags, visits, notes, tours, pictures, changes),
* built like TREK's settings card but in the Places palette: a head band with the
* icon tile, the title, how many it holds and its action, and the body below.
*/
export default function PlaceCard({
icon,
title,
count,
action,
rows = false,
children,
}: {
icon: LucideIcon;
title: string;
/** Shown as a badge beside the title when above zero. */
count?: number;
action?: React.ReactNode;
/** The children are rows of one block, divided by lines, the way a settings card lists its rows. */
rows?: boolean;
children?: React.ReactNode;
}): React.ReactElement {
return (
<section className="place-card" aria-label={title}>
<header className="place-card-head">
<span className="place-card-ico" aria-hidden="true">
{createElement(icon, { size: 16 })}
</span>
<h3 className="place-card-title">{title}</h3>
{!!count && <span className="place-card-count">{count}</span>}
{action && <span className="ms-auto flex items-center gap-1">{action}</span>}
</header>
{children != null && (
<div className="place-card-body">{rows ? <div className="place-rows">{children}</div> : children}</div>
)}
</section>
);
}
@@ -0,0 +1,91 @@
import { MapPin } from 'lucide-react';
import React from 'react';
import type { Category, TranslationFn } from '../../types';
import { NumericInput } from '../shared/NumericInput';
import CategoryTileMenu from './CategoryTileMenu';
import type { PlaceEditState } from './usePlaceEdit';
/**
* The edit form of a place of All places in the desktop dialog: the name with
* its category, the address, the position and the description. The change is
* made on every copy of the place in the reader's lists and trips they may edit.
*/
export default function PlaceEditForm({
edit,
categories,
t,
}: {
edit: PlaceEditState;
categories: Category[];
t: TranslationFn;
}): React.ReactElement | null {
const { draft, target } = edit;
if (!draft || !target) return null;
return (
<div className="col-detail-edit">
<div className="col-detail-field">
<div className="col-detail-label">{t('common.name')}</div>
<div className="flex items-center gap-2.5">
{categories.length > 0 && (
<CategoryTileMenu
categories={categories}
value={draft.categoryId}
onChange={(id) => edit.set('categoryId', id)}
size={36}
t={t}
/>
)}
<input
autoFocus
value={draft.name}
onChange={(e) => edit.set('name', e.target.value)}
aria-label={t('common.name')}
className="col-detail-input min-w-0 flex-1"
/>
</div>
</div>
<div className="col-detail-field">
<div className="col-detail-label">
<MapPin size={12} /> {t('places.formAddress')}
</div>
<input
value={draft.address}
onChange={(e) => edit.set('address', e.target.value)}
placeholder={t('places.formAddressPlaceholder')}
className="col-detail-input"
/>
</div>
<div className="col-detail-field">
<div className="col-detail-label">
<MapPin size={12} /> {t('collections.coordinates')}
</div>
<div className="col-detail-link-row">
<NumericInput
mode="signed"
value={draft.lat}
onValueChange={(v) => edit.set('lat', v)}
placeholder={t('places.formLat')}
className="col-detail-input flex-1"
/>
<NumericInput
mode="signed"
value={draft.lng}
onValueChange={(v) => edit.set('lng', v)}
placeholder={t('places.formLng')}
className="col-detail-input flex-1"
/>
</div>
</div>
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.description')}</div>
<textarea
value={draft.description}
onChange={(e) => edit.set('description', e.target.value)}
rows={5}
placeholder={t('collections.descriptionPlaceholder')}
className="col-detail-textarea"
/>
</div>
</div>
);
}
@@ -2,7 +2,9 @@ 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 { Avatar } from '../Planner/TravelerPicker';
import PlaceCard from './PlaceCard';
import { historyEditor, historyLine, historyWhen } from './placeExtrasText';
import { usePlaceHistory } from './usePlaceHistory';
/** How many changes show before "show all" opens the rest. */
@@ -14,44 +16,50 @@ const FOLDED = 3;
* 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,
export function PlaceHistoryView({
state: h,
language,
folded = true,
t,
}: {
entry: PlacesLibraryEntry;
state: ReturnType<typeof usePlaceHistory>;
language: string;
/** In its own tab the whole history shows at once; folded, the newest few. */
folded?: boolean;
t: TranslationFn;
}): React.ReactElement | null {
const h = usePlaceHistory(entry);
const [open, setOpen] = useState(false);
const [open, setOpen] = useState(!folded);
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">
<PlaceCard icon={History} title={t('placeHistory.title')} count={h.entries.length}>
<ol className="place-timeline">
{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 key={e.id} className="place-tl-item">
<span className="place-tl-dot" aria-hidden="true" />
<div className="place-tl-head">
<strong>{line.field}</strong>
<time className="place-tl-when">{historyWhen(e, language)}</time>
</div>
{(line.from || line.to) && (
<div className="place-tl-diff">
{line.from && <span className="place-tl-from">{line.from}</span>}
{line.from && line.to && <ArrowRight size={12} className="place-tl-arrow" aria-hidden="true" />}
{line.to && <span className="place-tl-to">{line.to}</span>}
</div>
)}
<div className="place-tl-meta">
{e.editor && !e.automatic ? (
<Avatar userId={e.editor.id} username={e.editor.username} avatarUrl={e.editor.avatar_url} size={18} />
) : null}
<span>{historyEditor(e, t)}</span>
<span className="place-tl-src">
{e.origin.kind === 'trip' ? <Luggage size={11} /> : <Bookmark size={11} />}
{e.origin.kind === 'trip' ? e.origin.trip_title : e.origin.collection_name}
</span>
</div>
</li>
);
})}
@@ -69,6 +77,19 @@ export default function PlaceHistorySection({
{!open ? t('placeHistory.showAll') : t('placeHistory.more')}
</button>
)}
</section>
</PlaceCard>
);
}
export default function PlaceHistorySection({
entry,
language,
t,
}: {
entry: PlacesLibraryEntry;
language: string;
t: TranslationFn;
}): React.ReactElement | null {
const h = usePlaceHistory(entry);
return <PlaceHistoryView state={h} language={language} t={t} />;
}
@@ -1,13 +1,9 @@
import { MapPin, MapPinOff } from 'lucide-react';
import React from 'react';
import type { TranslationFn } from '../../types';
import { coordsText } from './placeExtrasText';
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
@@ -1,63 +1,124 @@
import type { PlacesLibraryEntry } from '@trek/shared';
import { FileText, Images } from 'lucide-react';
import { Bookmark, FileText, Images, Layers, Loader2, Luggage, Plus, Upload } from 'lucide-react';
import React from 'react';
import type { TranslationFn } from '../../types';
import PhotoLightbox from '../Journey/PhotoLightbox';
import { usePlaceMedia } from './usePlaceMedia';
import { Tooltip } from '../shared/Tooltip';
import PlaceCard from './PlaceCard';
import { useMediaAdd } from './mediaAdd';
import { usePlaceMedia, type MediaTarget } from './usePlaceMedia';
type Media = ReturnType<typeof usePlaceMedia>;
/** How many pictures the strip shows before it counts the rest on the last one. */
const SHOWN = 8;
/** Where an upload goes, asked when the place takes one in more than one trip or list. */
function TargetChoice({ m, pick, t }: { m: Media; pick: (target: MediaTarget | 'all') => void; t: TranslationFn }) {
if (!m.choosing) return null;
return (
<div className="place-editor-for">
<span className="me-1">{t('placeMedia.where')}</span>
<button type="button" data-no-press onClick={() => pick('all')} className="place-for-chip">
<Layers size={12} /> {t('placeMedia.everywhere')}
</button>
{m.targets.map((x) => (
<button key={x.key} type="button" data-no-press onClick={() => pick(x)} className="place-for-chip">
{x.kind === 'trip' ? <Luggage size={12} /> : <Bookmark size={12} />}
{t(x.kind === 'trip' ? 'placeMedia.toTrip' : 'placeMedia.toList', { name: x.source })}
</button>
))}
</div>
);
}
/**
* 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,
export function PlaceMediaView({
state: m,
label,
t,
}: {
entry: PlacesLibraryEntry;
state: ReturnType<typeof usePlaceMedia>;
/** The place's name, for the lightbox. */
label: string;
t: TranslationFn;
}): React.ReactElement | null {
const m = usePlaceMedia(entry);
if (m.photos.length === 0 && m.files.length === 0) return null;
const add = useMediaAdd(m);
const canAdd = m.targets.length > 0;
if (m.photos.length === 0 && m.files.length === 0 && !canAdd) return null;
const rest = m.photos.length - SHOWN;
const addAction = canAdd && (
<button type="button" onClick={add.start} disabled={m.uploading} className="col-detail-action">
{m.uploading ? <Loader2 size={13} className="animate-spin" /> : <Plus size={13} />} {t('placeMedia.add')}
</button>
);
return (
<>
{add.field}
{m.photos.length === 0 && m.files.length === 0 && (
<PlaceCard icon={Images} title={t('placeSheet.tab.media')}>
<button type="button" onClick={add.start} disabled={m.uploading} className="place-dropzone">
{m.uploading ? <Loader2 size={18} className="animate-spin" /> : <Upload size={18} />}
<span className="font-semibold text-content">{t('placeMedia.addFirst')}</span>
<span>{t('placeMedia.hint')}</span>
</button>
<TargetChoice m={m} pick={add.pick} t={t} />
</PlaceCard>
)}
{m.photos.length > 0 && (
<section className="col-detail-field">
<div className="col-detail-label">
<Images size={12} /> {t('places.media.photos')}
</div>
<PlaceCard icon={Images} title={t('places.media.photos')} count={m.photos.length} action={addAction}>
<TargetChoice m={m} pick={add.pick} t={t} />
<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>
</>
<div key={p.id} className="place-photo">
<button
type="button"
onClick={() => m.setOpen(i)}
className="relative block h-full w-full"
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>
{p.src === m.cover && <span className="place-photo-badge">{t('placeMedia.isCover')}</span>}
{m.canCover(p) && !(i === SHOWN - 1 && rest > 0) && (
<Tooltip label={t('placeMedia.setCover')}>
<button
type="button"
onClick={() => void m.setCover(p)}
disabled={m.uploading}
aria-label={t('placeMedia.setCover')}
className="place-photo-cover"
>
<ImageUp size={13} />
</button>
</Tooltip>
)}
</button>
</div>
))}
</div>
</section>
</PlaceCard>
)}
{m.files.length > 0 && (
<section className="col-detail-field">
<div className="col-detail-label">
<FileText size={12} /> {t('places.media.files')}
</div>
<PlaceCard
rows
icon={FileText}
title={t('places.media.files')}
count={m.files.length}
action={m.photos.length === 0 ? addAction : undefined}
>
{m.photos.length === 0 && <TargetChoice m={m} pick={add.pick} t={t} />}
{m.files.map((f) => (
<a key={f.file_id} href={f.url} target="_blank" rel="noreferrer" className="col-origin">
<span className="col-origin-head">
@@ -71,7 +132,7 @@ export default function PlaceMediaSection({
</span>
</a>
))}
</section>
</PlaceCard>
)}
{m.open !== null && (
<PhotoLightbox
@@ -85,9 +146,20 @@ export default function PlaceMediaSection({
}))}
startIndex={m.open}
onClose={m.close}
label={entry.name}
label={label}
/>
)}
</>
);
}
export default function PlaceMediaSection({
entry,
t,
}: {
entry: PlacesLibraryEntry;
t: TranslationFn;
}): React.ReactElement | null {
const m = usePlaceMedia(entry, t);
return <PlaceMediaView state={m} label={entry.name} t={t} />;
}
@@ -0,0 +1,177 @@
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import { Bookmark, ChevronRight, Hotel, Luggage, Ticket } from 'lucide-react';
import { createElement } from 'react';
import type { TranslationFn } from '../../types';
import { STATUS_META } from './collectionStatus';
import { tripLine } from './libraryDates';
import type { ListDetail, ListOrigin, ListPair, TripDetail, TripOrigin, TripPair } from './libraryPairs';
import { listIcon } from './listIcons';
import { originName } from './originName';
import PlaceCard from './PlaceCard';
type Entry = NonNullable<PlacesLibraryDetailResponse['entry']>;
function TripCard({
origin,
detail,
entryName,
language,
onOpen,
t,
}: {
origin: TripOrigin;
detail: TripDetail;
entryName: string;
language: string;
onOpen: () => void;
t: TranslationFn;
}) {
const line = tripLine(origin, detail, language, t);
const extras = detail.has_accommodation || detail.has_reservation || detail.info.name !== entryName;
return (
<button
type="button"
className="col-origin"
onClick={onOpen}
aria-label={`${t('collections.library.openTrip')}: ${originName(origin)}`}
>
<span className="col-origin-head">
<span className="col-origin-ico">
{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>
{line && <span className="sub">{line}</span>}
</span>
{origin.read_only && <span className="col-origin-tag">{t('collections.library.readOnly')}</span>}
<ChevronRight size={16} className="col-origin-chev" />
</span>
{extras && (
<span className="col-origin-chips">
{detail.info.name !== entryName && (
<span className="col-origin-chip">{t('collections.library.calledHere', { name: detail.info.name })}</span>
)}
{detail.has_accommodation && (
<span className="col-origin-chip">
<Hotel size={11} /> {t('collections.library.stay')}
</span>
)}
{detail.has_reservation && (
<span className="col-origin-chip">
<Ticket size={11} /> {t('collections.library.booking')}
</span>
)}
</span>
)}
</button>
);
}
function ListCard({
origin,
detail,
entryName,
onOpen,
t,
}: {
origin: ListOrigin;
detail: ListDetail;
entryName: string;
onOpen: () => void;
t: TranslationFn;
}) {
const status = STATUS_META[origin.status];
const extras = detail.info.name !== entryName;
return (
<button
type="button"
className="col-origin"
onClick={onOpen}
aria-label={`${t('collections.library.openList')}: ${originName(origin)}`}
>
<span className="col-origin-head">
<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>
<span className="sub inline-flex items-center gap-1">
{createElement(status.icon, { size: 12, strokeWidth: 2.4, style: { color: status.color } })}
{t(status.labelKey)}
</span>
</span>
<ChevronRight size={16} className="col-origin-chev" />
</span>
{extras && (
<span className="col-origin-chips">
{detail.info.name !== entryName && (
<span className="col-origin-chip">{t('collections.library.calledHere', { name: detail.info.name })}</span>
)}
</span>
)}
</button>
);
}
/**
* Where the place is kept, in the overview of the one place view: its lists and
* its trips, each a card that opens the place there.
*/
export default function PlaceOrigins({
entry,
trips,
lists,
language,
onOpenTrip,
onOpenList,
t,
}: {
entry: Entry;
trips: TripPair[];
lists: ListPair[];
language: string;
onOpenTrip: (tripId: number, placeId: number) => void;
onOpenList: (collectionId: number, collectionPlaceId: number) => void;
t: TranslationFn;
}) {
return (
<>
{lists.length > 0 && (
<PlaceCard icon={Bookmark} title={t('collections.library.inLists')} count={lists.length} rows>
{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}
/>
))}
</PlaceCard>
)}
{trips.length > 0 && (
<PlaceCard icon={Luggage} title={t('collections.library.inTrips')} count={trips.length} rows>
{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}
/>
))}
</PlaceCard>
)}
</>
);
}
@@ -0,0 +1,22 @@
import React from 'react';
import PlaceRating from '../shared/StarRating';
import type { PlaceRatingState } from './usePlaceRating';
/**
* The votes on a place of All places beside it, as one bar: the rating row the
* lists show (stars to vote with, the average, how many voted and who, with
* their votes on hover). The vote counts in every list and trip the place is
* in. The phone sheet uses it as it is.
*/
export default function PlaceRatingRow({ rating }: { rating: PlaceRatingState }): React.ReactElement | null {
if (!rating.rating) return null;
return (
<div className="place-rating">
<PlaceRating
ratings={rating.votes}
ratingAvg={rating.rating.average}
onRate={(value) => void rating.rate(value)}
/>
</div>
);
}
@@ -0,0 +1,80 @@
import { X } from 'lucide-react';
import React, { createElement, useId } from 'react';
import type { TranslationFn } from '../../types';
import { OriginNotesView } from './OriginNotesSection';
import { PlaceActivitiesView } from './PlaceActivitiesSection';
import { PlaceHistoryView } from './PlaceHistorySection';
import { PlaceMediaView } from './PlaceMediaSection';
import { PLACE_TAB_EMPTY, PLACE_TAB_ICON, PLACE_TAB_LABEL, PLACE_TABS, type PlaceSheetState } from './usePlaceSheet';
import { VisitsView } from './VisitsSection';
/**
* The tabs of the one place view on the desktop: the overview (where the place
* is kept, its tags, its visits), then its notes, tours and bookings, pictures
* and files, and its changes, each tab counting what it holds. The overview's
* first part comes from the caller, the rest is the same wherever it opens.
*/
export default function PlaceSheetTabs({
sheet,
overview,
language,
onClose,
t,
}: {
sheet: PlaceSheetState;
overview: React.ReactNode;
language: string;
/** The dialog's close, at the top end of the tabs wherever the place opened from. */
onClose: () => void;
t: TranslationFn;
}): React.ReactElement {
const id = useId();
const { tab } = sheet;
return (
<div className="place-main">
<div className="place-tabbar">
<div className="place-tabs" role="tablist" aria-label={t('placeSheet.tabs')}>
{PLACE_TABS.map((key) => (
<button
key={key}
id={`${id}-${key}`}
type="button"
role="tab"
aria-selected={tab === key}
aria-controls={`${id}-panel`}
onClick={() => sheet.setTab(key)}
className="place-tab"
>
{t(PLACE_TAB_LABEL[key])}
{sheet.counts[key] > 0 && <span className="place-tab-count">{sheet.counts[key]}</span>}
</button>
))}
</div>
<button type="button" onClick={onClose} aria-label={t('common.close')} className="place-icon-btn place-close">
<X size={16} />
</button>
</div>
<div id={`${id}-panel`} role="tabpanel" aria-labelledby={`${id}-${tab}`} className="place-panel">
{sheet.empty[tab] ? (
<div className="place-empty">
<span className="place-empty-ico">{createElement(PLACE_TAB_ICON[tab], { size: 22 })}</span>
{t(PLACE_TAB_EMPTY[tab])}
</div>
) : (
<>
{tab === 'overview' && (
<>
{overview}
<VisitsView state={sheet.visits} language={language} t={t} />
</>
)}
{tab === 'notes' && <OriginNotesView state={sheet.notes} t={t} />}
{tab === 'activities' && <PlaceActivitiesView state={sheet.activities} language={language} t={t} />}
{tab === 'media' && sheet.entry && <PlaceMediaView state={sheet.media} label={sheet.entry.name} t={t} />}
{tab === 'history' && <PlaceHistoryView state={sheet.history} language={language} folded={false} t={t} />}
</>
)}
</div>
</div>
);
}
@@ -0,0 +1,169 @@
import { Bookmark, Check, Luggage, Plus, Search, Tag, X } from 'lucide-react';
import React, { useEffect, useRef } from 'react';
import type { TranslationFn } from '../../types';
import PlaceCard from './PlaceCard';
import type { PlaceTagsState, TagGroup } from './usePlaceTags';
/** The open group's picker: search, tick the list's or trip's tags, make a new one from the search. */
function TagPicker({ tags, group, t }: { tags: PlaceTagsState; group: TagGroup; t: TranslationFn }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const onDown = (e: PointerEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) tags.openPicker(null);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
// The picker closes, the dialog behind it stays.
e.preventDefault();
tags.openPicker(null);
}
};
document.addEventListener('pointerdown', onDown);
document.addEventListener('keydown', onKey, true);
return () => {
document.removeEventListener('pointerdown', onDown);
document.removeEventListener('keydown', onKey, true);
};
}, [tags]);
const assigned = new Set(group.assigned.map((x) => x.id));
const name = tags.query.trim();
return (
<div ref={ref} role="menu" aria-label={t('placeTags.title')} className="place-picker">
<form
className="place-picker-search"
onSubmit={(e) => {
e.preventDefault();
if (tags.canCreate) void tags.createAndAdd();
}}
>
<Search size={14} aria-hidden="true" />
<input
autoFocus
value={tags.query}
onChange={(e) => tags.setQuery(e.target.value)}
placeholder={t('placeTags.search')}
aria-label={t('placeTags.search')}
/>
</form>
<div className="place-picker-list">
{tags.matches.map((tag) => {
const on = assigned.has(tag.id);
return (
<button
key={tag.id}
type="button"
role="menuitemcheckbox"
aria-checked={on}
disabled={tags.busy}
onClick={() => void tags.toggle(group, tag.id)}
className={on ? 'place-picker-opt on' : 'place-picker-opt'}
>
{/* The tag's own colour, the one data-driven value of the row. */}
<span className="place-tag-dot" style={{ ['--tag' as string]: tag.color || 'var(--accent)' }} />
<span className="min-w-0 flex-1 truncate">{tag.name}</span>
{on && <Check size={14} className="flex-none" />}
</button>
);
})}
{tags.matches.length === 0 && !tags.canCreate && <p className="place-picker-empty">{t('placeTags.none')}</p>}
</div>
{tags.canCreate && (
<>
{tags.matches.length > 0 && <div className="place-picker-sep" />}
<button
type="button"
onClick={() => void tags.createAndAdd()}
disabled={tags.busy}
className="place-picker-opt"
>
<span className="place-picker-plus" aria-hidden="true">
<Plus size={12} strokeWidth={2.6} />
</span>
<span className="min-w-0 flex-1 truncate">
{t('placeTags.createPrefix')} <strong className="place-picker-new">{name}</strong>
</span>
</button>
</>
)}
</div>
);
}
/**
* One list's or trip's tags on the place: the chips in their colours, then a
* dashed "+ Tag" chip in the same row that opens the picker. Where it comes from
* is named only when the place sits in more than one list or trip.
*/
function Group({ group, named, tags, t }: { group: TagGroup; named: boolean; tags: PlaceTagsState; t: TranslationFn }) {
const open = tags.openKey === group.key;
if (!group.canEdit && group.assigned.length === 0 && !named) {
return <p className="col-origin-sub m-0">{t('placeTags.noneHere')}</p>;
}
return (
<div className="place-tag-group">
{named && (
<span className="place-tag-src">
{group.kind === 'trip' ? <Luggage size={12} /> : <Bookmark size={12} />}
<span className="truncate">{group.source}</span>
</span>
)}
<div className="place-tag-row">
{group.assigned.map((tag) => (
<span key={tag.id} className="place-tag-chip" style={{ ['--tag' as string]: tag.color || 'var(--accent)' }}>
<span className="place-tag-dot" />
{tag.name}
{group.canEdit && (
<button
type="button"
onClick={() => void tags.toggle(group, tag.id)}
disabled={tags.busy}
aria-label={t('placeTags.removeFrom', { name: tag.name })}
className="place-tag-x"
>
<X size={11} strokeWidth={2.6} />
</button>
)}
</span>
))}
{group.canEdit && (
<span className="relative">
<button
type="button"
onClick={() => tags.openPicker(open ? null : group.key)}
aria-expanded={open}
className={open ? 'place-tag-add on' : 'place-tag-add'}
>
<Plus size={12} strokeWidth={2.6} /> {t('placeTags.add')}
</button>
{open && <TagPicker tags={tags} group={group} t={t} />}
</span>
)}
{!group.canEdit && group.assigned.length === 0 && (
<span className="col-origin-sub">{t('placeTags.noneHere')}</span>
)}
</div>
</div>
);
}
/**
* The tags of a place in the desktop view, wherever it opens: one group per list
* and per trip it sits in, each with the tags everyone there sees, and a picker to
* put one on, take one off or make a new one in that list or trip.
*/
export default function PlaceTagsCard({
tags,
t,
}: {
tags: PlaceTagsState;
t: TranslationFn;
}): React.ReactElement | null {
if (tags.groups.length === 0) return null;
return (
<PlaceCard icon={Tag} title={t('placeTags.title')} count={tags.total} rows>
{tags.groups.map((group) => (
<Group key={group.key} group={group} named={tags.groups.length > 1} tags={tags} t={t} />
))}
</PlaceCard>
);
}
@@ -1,7 +1,6 @@
import type { CollectionPlace, PlacesLibraryEntry } from '@trek/shared';
import { Loader2, MapPin, Search } from 'lucide-react';
import React, { useMemo, useState } from 'react';
import { useElementRect } from '../../hooks/useElementRect';
import { useCollectionStore } from '../../store/collectionStore';
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';
import type { Category, TranslationFn } from '../../types';
@@ -11,14 +10,13 @@ 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 { usePersonalTags } from './useEntryTags';
import { ratingBadge } from './ratingLabel';
import { usePlaceDuplicates } from './usePlaceDuplicates';
import { usePlacesLibrary } from './usePlacesLibrary';
import VisitedMark from './VisitedMark';
@@ -137,6 +135,15 @@ function LibraryRows({
: null
}
/>
{ratingBadge(entry.rating?.average) && (
<span
className="col-lrow-ratebadge"
role="img"
aria-label={t('collections.ratingBadge', { rating: ratingBadge(entry.rating?.average) })}
>
{ratingBadge(entry.rating?.average)}
</span>
)}
</span>
<div className="li">
<div className="t">
@@ -189,14 +196,12 @@ 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);
const saving = useSaveToCollectionStore((s) => s.target != null);
const copyToTrip = useCollectionStore((s) => s.copyToTrip);
const [copyId, setCopyId] = useState<number | null>(null);
const listCol = useElementRect<HTMLDivElement>();
const mapCol = useElementRect<HTMLDivElement>();
const map = useMemo(() => toMapPlaces(lib.entries), [lib.entries]);
const selectedMapId = lib.selectedKey ? (map.idOf.get(lib.selectedKey) ?? null) : null;
const split = isWide && map.places.length > 0;
@@ -213,12 +218,14 @@ export default function PlacesLibraryView({
onCategory={lib.setCategoryId}
sort={lib.sort}
onSort={lib.setSort}
minRating={lib.minRating}
onMinRating={lib.setMinRating}
duplicates={dup.pairs.length}
duplicatesMore={dup.hasMore}
onDuplicates={() => setShowDup(true)}
tags={personalTags}
tagIds={lib.tagIds}
onToggleTag={lib.toggleTag}
tags={lib.tagOptions}
tagNames={lib.tagNames}
onToggleTag={lib.toggleTagName}
t={t}
/>
);
@@ -247,16 +254,12 @@ export default function PlacesLibraryView({
</>
);
const anchor = detailDock(split, view, mapCol.rect, listCol.rect);
return (
<>
{split ? (
<div className={view === 'map' ? 'col-split map-full' : 'col-split'}>
<div className="col-split-list" ref={listCol.ref}>
{listColumn}
</div>
<div className="col-split-map" ref={mapCol.ref}>
<div className="col-split-list">{listColumn}</div>
<div className="col-split-map">
<CollectionMapPanel
places={map.places}
selectedPlaceId={selectedMapId}
@@ -291,7 +294,8 @@ export default function PlacesLibraryView({
onNotesSaved={lib.reload}
cover={lib.cover}
language={language}
anchorRect={anchor}
categories={categories}
blocked={copyId != null || saving}
onClose={lib.close}
onOpenList={(collectionId, placeId) => navigate(`${placesPath(collectionId)}?place=${placeId}`)}
onOpenTrip={(tripId, placeId) => navigate(`/trips/${tripId}?place=${placeId}`)}
@@ -1,12 +1,11 @@
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.
* The tag filter of All places, shaped like the dropdowns beside it but with
* several picks at once: a place shows when one of its lists or trips gives it a
* tag of any of the picked names. Not drawn while no place has a tag.
*/
export default function TagFilterDropdown({
tags,
@@ -14,9 +13,9 @@ export default function TagFilterDropdown({
onToggle,
t,
}: {
tags: readonly TagRow[];
picked: readonly number[];
onToggle: (id: number) => void;
tags: readonly { name: string; color: string | null }[];
picked: readonly string[];
onToggle: (name: string) => void;
t: TranslationFn;
}): React.ReactElement | null {
const [open, setOpen] = useState(false);
@@ -42,7 +41,7 @@ export default function TagFilterDropdown({
picked.length === 0
? t('placeTags.filterAll')
: picked.length === 1
? String(tags.find((tag) => tag.id === picked[0])?.name ?? '')
? picked[0]
: t('placeTags.filterCount', { count: picked.length });
return (
<div className="col-filter" ref={ref}>
@@ -61,15 +60,15 @@ export default function TagFilterDropdown({
{open && (
<div className="col-filter-pop" role="listbox" aria-multiselectable="true">
{tags.map((tag) => {
const on = picked.includes(tag.id);
const on = picked.some((name) => name.toLowerCase() === tag.name.toLowerCase());
return (
<button
key={tag.id}
key={tag.name}
type="button"
role="option"
aria-selected={on}
className={['col-filter-opt', on && 'on'].filter(Boolean).join(' ')}
onClick={() => onToggle(tag.id)}
onClick={() => onToggle(tag.name)}
>
{/* The tag's own colour, the one data-driven value of the row. */}
<span className="col-filter-dot" style={{ background: tag.color || 'var(--accent)' }} />
@@ -112,7 +112,7 @@ export function TripListsPill({ lists, t }: { lists: TripLists; t: TranslationFn
<Tooltip label={t('tripLists.open')}>
<button
type="button"
onClick={() => navigate(placesPath(l.collection_id))}
onClick={() => void navigate(placesPath(l.collection_id))}
aria-label={t('tripLists.open')}
className={ICON_BTN}
>
@@ -5,6 +5,7 @@ import type { TranslationFn } from '../../types';
import { Avatar } from '../Planner/TravelerPicker';
import { Tooltip } from '../shared/Tooltip';
import { visitDate } from './libraryDates';
import PlaceCard from './PlaceCard';
import { usePlaceVisits } from './usePlaceVisits';
/** One visit as a card like the trips and lists above it: the day, the trip and who was there. */
@@ -41,6 +42,32 @@ function VisitCard({ visit, language }: { visit: PlaceVisit; language: string })
* trip it was planned on, newest first. Nothing to enter; without visits the
* section is not there at all.
*/
export function VisitsView({
state: v,
language,
t,
}: {
state: ReturnType<typeof usePlaceVisits>;
language: string;
t: TranslationFn;
}): React.ReactElement | null {
const last = visitDate(v.lastVisit, null, language);
if (v.count === 0 || !last) return null;
return (
<PlaceCard
icon={CalendarCheck}
title={t('visits.title')}
count={v.count}
action={<span className="col-origin-sub">{t('visits.summary', { count: v.count, date: last })}</span>}
rows
>
{v.visits.map((visit) => (
<VisitCard key={`${visit.trip.id}:${visit.day_id}:${visit.place_id}`} visit={visit} language={language} />
))}
</PlaceCard>
);
}
export default function VisitsSection({
entry,
language,
@@ -51,19 +78,5 @@ export default function VisitsSection({
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>
);
return <VisitsView state={v} language={language} t={t} />;
}
@@ -1,27 +0,0 @@
import type { CSSProperties } from 'react';
/** A column's measured place in the viewport, which a place sheet docks over. */
export type DockRect = Pick<DOMRect, 'left' | 'width'>;
/**
* Where a place sheet docks in the desktop split, for a list and for "All places"
* alike: over the list column beside the map, on the map's start edge when the map
* has the whole width, and nowhere (a centred sheet) when there is no split.
*/
export function detailDock(
split: boolean,
view: 'list' | 'map' | string,
mapRect: DockRect | null | undefined,
listRect: DockRect | null | undefined
): DockRect | null {
if (!split) return null;
if (view !== 'map') return listRect ?? null;
if (!mapRect) return null;
return { left: mapRect.left + 12, width: Math.min(420, mapRect.width - 24) }; // rtl-lint-disable: a measured viewport position, like the list dock
}
/** The docked sheet's own style: the measured column, nothing when it is centred. */
export function dockStyle(rect: DockRect | null | undefined): CSSProperties | undefined {
if (!rect) return undefined;
return { left: rect.left, width: rect.width, transform: 'none' }; // rtl-lint-disable: the measured column, not a side of the text
}
@@ -1,4 +1,5 @@
import type { PlacesLibraryDetail, PlacesLibraryDetailResponse, PlacesLibraryOrigin } from '@trek/shared';
import { carryKey } from './useTripCopyPicker';
export type TripOrigin = Extract<PlacesLibraryOrigin, { kind: 'trip' }>;
export type ListOrigin = Extract<PlacesLibraryOrigin, { kind: 'list' }>;
@@ -47,15 +48,13 @@ export function saveDraftOf(origin: TripOrigin, detail: TripDetail, categoryId:
/**
* 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.
* list and the list's tags on it. 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 })),
tags: (pair?.detail.labels ?? []).map((l) => ({ key: carryKey('label', l.id), name: l.name, color: l.color })),
};
}
@@ -0,0 +1,39 @@
import { useRef } from 'react';
import type { MediaTarget, usePlaceMedia } from './usePlaceMedia';
/**
* Adding a picture or file: one target opens the file dialog at once; several ask
* first where it goes (a trip keeps any file, a list a picture of the place).
* The trigger is the card's action, or the empty card's own wide button.
*/
export function useMediaAdd(m: ReturnType<typeof usePlaceMedia>) {
const input = useRef<HTMLInputElement>(null);
const target = useRef<readonly MediaTarget[]>([]);
/** One trip or list, or every one of them at once (`'all'`). */
const pick = (next: MediaTarget | 'all') => {
target.current = next === 'all' ? m.targets : [next];
m.setChoosing(false);
if (input.current) {
input.current.accept = target.current.every((x) => x.kind === 'list') ? 'image/*' : '';
input.current.click();
}
};
const start = () => {
if (m.targets.length === 1) pick(m.targets[0]);
else m.setChoosing(!m.choosing);
};
const field = (
<input
ref={input}
type="file"
multiple
className="hidden"
onChange={(e) => {
const files = Array.from(e.target.files ?? []);
e.target.value = '';
if (target.current.length) void m.upload(target.current, files);
}}
/>
);
return { start, pick, field };
}
@@ -51,8 +51,7 @@ export function activityLine(
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(', ');
/** A position as the location badge shows it, five decimals, about a metre. */
export function coordsText(lat: number, lng: number): string {
return `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
}
@@ -0,0 +1,874 @@
/* The one place view (All places and lists alike): a wide dialog of two columns,
the place itself on the start side and its tabs of cards beside it. The dialog
portals out of the page, so it wears .trek-dash for the page's tokens and
only takes back the page's own background and height. */
.trek-dash.place-sheet {
min-height: 0;
height: min(640px, calc(100dvh - 80px));
display: grid;
grid-template-columns: minmax(300px, 360px) minmax(0, 1fr);
background: var(--surface);
}
.trek-dash .place-aside {
display: flex;
flex-direction: column;
min-height: 0;
border-inline-end: 1px solid var(--line);
}
.trek-dash .place-aside .col-detail-cover {
height: 188px;
}
.trek-dash .place-aside-body {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
padding: 16px 18px;
display: flex;
flex-direction: column;
gap: 14px;
}
.trek-dash .place-aside .col-detail-footer {
flex-wrap: wrap;
}
.trek-dash .place-main {
display: flex;
flex-direction: column;
min-height: 0;
background: var(--bg);
}
.trek-dash .place-tabbar {
display: flex;
align-items: center;
gap: 8px;
padding-inline-end: 12px;
border-bottom: 1px solid var(--line);
background: var(--surface);
}
.trek-dash .place-tabs {
flex: 1 1 auto;
min-width: 0;
display: flex;
gap: 2px;
padding: 12px 16px 0;
overflow-x: auto;
scrollbar-width: none;
}
.trek-dash .place-tab {
position: relative;
display: inline-flex;
align-items: center;
gap: 6px;
padding: 9px 12px 11px;
font-size: 13px;
font-weight: 600;
color: var(--ink-3);
white-space: nowrap;
transition: color 0.12s;
}
.trek-dash .place-tab:hover {
color: var(--ink);
}
.trek-dash .place-tab[aria-selected='true'] {
color: var(--ink);
}
.trek-dash .place-tab[aria-selected='true']::after {
content: '';
position: absolute;
inset-inline: 10px;
bottom: -1px;
height: 2px;
border-radius: 2px;
background: var(--accent);
}
.trek-dash .place-tab-count {
min-width: 18px;
padding: 1px 6px;
border-radius: 999px;
font-size: 11px;
font-weight: 700;
text-align: center;
color: var(--ink-2);
background: var(--surface-2);
border: 1px solid var(--line);
}
.trek-dash .place-panel {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
padding: 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
.trek-dash .place-empty {
margin: auto;
max-width: 300px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
text-align: center;
font-size: 13px;
color: var(--ink-3);
}
.trek-dash .place-empty-ico {
width: 44px;
height: 44px;
display: grid;
place-items: center;
border-radius: 14px;
background: var(--surface);
border: 1px solid var(--line);
color: var(--ink-3);
}
/* A card, built like the settings card in the Places palette: the head band
with the icon tile and title, then the body with its rows. */
.trek-dash .place-card {
/* A card keeps its height in the scrolling panel; the panel scrolls, the card never clips. */
flex-shrink: 0;
overflow: hidden;
border-radius: 16px;
border: 1px solid var(--line);
background: var(--surface);
}
.trek-dash .place-card-head {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
border-bottom: 1px solid var(--line);
/* The dialogs' head tone (NEUTRAL_TINT): a 7% wash of the accent over the card. */
background: color-mix(in srgb, var(--accent) 7%, var(--surface));
}
.trek-dash .place-card-ico {
width: 34px;
height: 34px;
flex-shrink: 0;
display: grid;
place-items: center;
border-radius: 10px;
background: var(--surface);
color: var(--ink-2);
box-shadow: var(--sh-xs);
}
.trek-dash .place-card-title {
margin: 0;
font-size: 14px;
font-weight: 700;
color: var(--ink);
}
.trek-dash .place-card-count {
padding: 1px 7px;
border-radius: 999px;
font-size: 11px;
font-weight: 700;
color: var(--ink-3);
background: var(--surface);
border: 1px solid var(--line);
}
.trek-dash .place-card-body {
display: flex;
flex-direction: column;
gap: 10px;
padding: 14px;
}
.trek-dash .place-card-body .col-origin,
.trek-dash .place-card-body .place-note,
.trek-dash .place-card-body .place-editor,
.trek-dash .place-card-body .place-editor-for,
.trek-dash .place-card-body .place-composer {
background: var(--bg);
border-color: var(--line);
}
/* Tags: every container's own, one group per list or trip, chips in their colour. */
.trek-dash .place-tag-group {
display: flex;
flex-direction: column;
gap: 6px;
}
.trek-dash .place-tag-group + .place-tag-group {
padding-top: 10px;
border-top: 1px dashed var(--line);
}
.trek-dash .place-tag-src {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 11.5px;
font-weight: 600;
color: var(--ink-3);
min-width: 0;
}
.trek-dash .place-tag-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border-radius: 999px;
font-size: 12px;
font-weight: 600;
color: var(--ink);
background: color-mix(in oklch, var(--tag, var(--accent)) 14%, var(--surface));
border: 1px solid color-mix(in oklch, var(--tag, var(--accent)) 35%, transparent);
}
.trek-dash .place-tag-dot {
width: 8px;
height: 8px;
border-radius: 999px;
flex-shrink: 0;
background: var(--tag, var(--accent));
}
@media (max-width: 860px) {
.trek-dash.place-sheet {
grid-template-columns: minmax(0, 1fr);
height: auto;
max-height: calc(100dvh - 80px);
overflow-y: auto;
}
.trek-dash .place-aside {
border-inline-end: 0;
border-bottom: 1px solid var(--line);
}
}
/* The things to do with the place: edit as a round icon, the rest as pills, one row. */
.trek-dash .place-aside .col-detail-footer {
flex-wrap: nowrap;
gap: 6px;
padding: 12px 14px;
}
.trek-dash .place-icon-btn {
width: 36px;
height: 36px;
flex-shrink: 0;
display: grid;
place-items: center;
border-radius: 999px;
color: var(--ink-2);
background: var(--surface-2);
border: 1px solid var(--line);
transition:
background 0.12s,
color 0.12s;
}
.trek-dash .place-icon-btn:hover {
background: var(--surface);
color: var(--ink);
}
.trek-dash .place-icon-btn.danger {
color: oklch(0.6 0.2 25);
}
.trek-dash .place-aside .col-detail-btn {
min-width: 0;
}
.trek-dash .place-aside .col-detail-seg {
grid-template-columns: repeat(2, 1fr);
}
.trek-dash .place-close {
width: 32px;
height: 32px;
flex-shrink: 0;
}
/* The tag picker, shaped like the filter menus: a quiet search line, rows of one
height and size, and "make a new tag" set apart below them. */
.trek-dash .place-picker {
position: absolute;
inset-inline-end: 0;
top: calc(100% + 6px);
z-index: 30;
width: 260px;
display: flex;
flex-direction: column;
gap: 2px;
padding: 6px;
border-radius: 12px;
background: var(--surface);
border: 1px solid var(--line);
box-shadow: var(--sh-lg);
}
.trek-dash .place-picker-search {
display: flex;
align-items: center;
gap: 8px;
height: 34px;
padding: 0 10px;
margin-bottom: 4px;
border-radius: 9px;
background: var(--surface-2);
color: var(--ink-3);
}
.trek-dash .place-picker-search input {
flex: 1 1 auto;
min-width: 0;
border: 0;
outline: none;
background: transparent;
font: inherit;
font-size: 13px;
color: var(--ink);
}
.trek-dash .place-picker-search input::placeholder {
color: var(--ink-3);
}
.trek-dash .place-picker-list {
display: flex;
flex-direction: column;
gap: 2px;
max-height: 220px;
overflow-y: auto;
}
.trek-dash .place-picker-opt {
display: flex;
align-items: center;
gap: 9px;
width: 100%;
padding: 7px 9px;
border-radius: 8px;
font-size: 13px;
color: var(--ink-2);
text-align: start;
transition: background 0.12s;
}
.trek-dash .place-picker-opt:hover {
background: var(--surface-2);
}
.trek-dash .place-picker-opt.on {
color: var(--ink);
font-weight: 600;
}
.trek-dash .place-picker-opt:disabled {
opacity: 0.6;
}
.trek-dash .place-picker-empty {
margin: 0;
padding: 7px 9px;
font-size: 12px;
color: var(--ink-3);
}
.trek-dash .place-picker-sep {
height: 1px;
margin: 4px 2px;
background: var(--line);
}
.trek-dash .place-picker-plus {
width: 18px;
height: 18px;
flex-shrink: 0;
display: grid;
place-items: center;
border-radius: 999px;
background: var(--accent);
color: var(--accent-text);
}
.trek-dash .place-picker-new {
font-weight: 700;
color: var(--ink);
}
/* Tags in one flowing row: the chips, then "+ Tag" as a dashed chip of the same
height; a chip's remove cross shows on hover or focus. */
.trek-dash .place-tag-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.trek-dash .place-tag-chip {
height: 28px;
padding: 0 11px;
}
.trek-dash .place-tag-x {
width: 0;
margin-inline-start: -4px;
overflow: hidden;
display: grid;
place-items: center;
height: 16px;
border-radius: 999px;
color: var(--ink-3);
opacity: 0;
transition:
width 0.12s,
opacity 0.12s,
margin 0.12s;
}
.trek-dash .place-tag-chip:hover .place-tag-x,
.trek-dash .place-tag-x:focus-visible {
width: 16px;
margin-inline-start: 0;
opacity: 1;
}
.trek-dash .place-tag-x:hover {
color: var(--ink);
background: color-mix(in oklch, var(--tag, var(--accent)) 22%, transparent);
}
.trek-dash .place-tag-add {
display: inline-flex;
align-items: center;
gap: 5px;
height: 28px;
padding: 0 11px;
border-radius: 999px;
font-size: 12px;
font-weight: 600;
color: var(--ink-3);
border: 1px dashed var(--line-2);
transition:
color 0.12s,
border-color 0.12s,
background 0.12s;
}
.trek-dash .place-tag-add:hover,
.trek-dash .place-tag-add.on {
color: var(--ink);
border-color: var(--ink-3);
background: var(--surface-2);
}
.trek-dash .place-tag-add + .place-picker,
.trek-dash .relative > .place-picker {
inset-inline-end: auto;
inset-inline-start: 0;
}
/* An empty pictures card: one wide dashed button to add the first picture or file. */
.trek-dash .place-dropzone {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
width: 100%;
padding: 22px 16px;
border-radius: 14px;
border: 1.5px dashed var(--line-2);
color: var(--ink-3);
font-size: 12.5px;
text-align: center;
transition:
border-color 0.12s,
background 0.12s,
color 0.12s;
}
.trek-dash .place-dropzone:hover {
border-color: var(--ink-3);
background: var(--surface-2);
color: var(--ink-2);
}
/* The votes, as one bar across the column: the same in a list's place and in All places. */
.trek-dash .place-rating {
display: flex;
align-items: center;
width: 100%;
min-height: 46px;
padding: 8px 12px;
border-radius: 14px;
background: var(--surface-2);
border: 1px solid var(--line);
}
.trek-dash .place-rating > div {
flex: 1 1 auto;
}
/* Notes: each one a card that reads as written (markdown), a field that opens
the editor, and the editor itself with its toolbar, write or preview, save. */
.trek-dash .place-note {
display: flex;
flex-direction: column;
gap: 6px;
padding: 10px 12px 12px;
border-radius: 12px;
background: var(--surface-2);
border: 1px solid var(--line);
}
.trek-dash .place-note-head {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
font-size: 11.5px;
font-weight: 600;
color: var(--ink-3);
}
.trek-dash .place-note-edit {
width: 26px;
height: 26px;
display: grid;
place-items: center;
border-radius: 8px;
color: var(--ink-3);
transition:
background 0.12s,
color 0.12s;
}
.trek-dash .place-note-edit:hover {
background: var(--surface);
color: var(--ink);
}
.trek-dash .place-note-body {
font-size: 13.5px;
line-height: 1.55;
color: var(--ink);
}
.trek-dash .place-composer {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 12px 14px;
border-radius: 12px;
border: 1px solid var(--line);
background: var(--surface-2);
font-size: 13px;
color: var(--ink-3);
text-align: start;
cursor: text;
transition:
border-color 0.12s,
color 0.12s;
}
.trek-dash .place-composer:hover {
border-color: var(--line-2);
color: var(--ink-2);
}
.trek-dash .place-editor {
display: flex;
flex-direction: column;
gap: 8px;
padding: 10px 12px 12px;
border-radius: 12px;
background: var(--surface-2);
border: 1px solid var(--line);
}
.trek-dash .place-editor-for {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
font-size: 11.5px;
font-weight: 600;
color: var(--ink-3);
}
.trek-dash .place-for-chip {
display: inline-flex;
align-items: center;
gap: 5px;
height: 26px;
padding: 0 10px;
border-radius: 999px;
font-size: 12px;
font-weight: 600;
color: var(--ink-2);
background: var(--surface);
border: 1px solid var(--line);
box-sizing: border-box;
}
.trek-dash .place-for-chip.on {
color: var(--ink);
background: color-mix(in oklch, var(--accent) 14%, var(--surface));
border-color: color-mix(in oklch, var(--accent) 55%, transparent);
}
.trek-dash .place-editor-bar {
display: flex;
align-items: center;
gap: 8px;
min-height: 30px;
}
.trek-dash .place-seg {
display: inline-flex;
gap: 2px;
padding: 2px;
border-radius: 9px;
background: var(--surface);
border: 1px solid var(--line);
}
.trek-dash .place-seg button {
display: inline-flex;
align-items: center;
gap: 5px;
height: 24px;
padding: 0 9px;
border-radius: 7px;
font-size: 11.5px;
font-weight: 600;
color: var(--ink-3);
}
.trek-dash .place-seg button[aria-pressed='true'] {
background: var(--surface-2);
color: var(--ink);
box-shadow: var(--sh-xs);
}
.trek-dash .place-editor-text {
width: 100%;
min-height: 132px;
padding: 10px 12px;
border-radius: 10px;
border: 1px solid var(--line);
background: var(--surface);
color: var(--ink);
font: inherit;
font-size: 13.5px;
line-height: 1.55;
resize: vertical;
outline: none;
}
.trek-dash .place-editor-text:focus {
border-color: var(--accent);
}
.trek-dash .place-editor-preview {
min-height: 132px;
padding: 10px 12px;
border-radius: 10px;
background: var(--surface);
border: 1px solid var(--line);
font-size: 13.5px;
line-height: 1.55;
}
.trek-dash .place-editor-foot {
display: flex;
align-items: center;
gap: 8px;
}
/* .trek-dash resets every button to padding 0 and the inherited font, which
outweighs the utility classes of menus drawn inside the dialog (the category
menu of the edit form). The dialog gets the page's body size, and those menu
rows their own padding and size back. */
.trek-dash.place-sheet {
font-size: 13.5px;
}
.trek-dash.place-sheet [role='listbox'] > button[role='option'] {
padding: 7px 9px;
gap: 9px;
font-size: 13px;
line-height: 1.3;
}
.trek-dash .place-for-sep {
width: 1px;
height: 16px;
background: var(--line-2);
margin-inline: 2px;
}
/* Where a new note goes: its own box above the editor, like the editor's. */
.trek-dash .place-editor-for {
padding: 6px 6px 6px 12px;
border-radius: 12px;
background: var(--surface-2);
border: 1px solid var(--line);
font-size: 12px;
}
/* The head of the link picker, set off from the suggestions below it. */
.trek-dash .place-pick-head {
display: flex;
align-items: center;
gap: 8px;
margin: -2px -12px 2px;
padding: 0 8px 8px 12px;
border-bottom: 1px solid var(--line);
font-size: 12.5px;
font-weight: 700;
color: var(--ink);
}
/* Rows of one block, the way a settings card lists its rows: one white block,
a line between rows, the rows themselves flat. */
.trek-dash .place-rows {
display: flex;
flex-direction: column;
overflow: hidden;
border-radius: 12px;
border: 1px solid var(--line);
background: var(--bg);
}
.trek-dash .place-rows > * + * {
border-top: 1px solid var(--line);
}
.trek-dash .place-card-body .place-rows > .col-origin {
border: 0;
border-radius: 0;
background: transparent;
padding: 12px 14px;
}
.trek-dash .place-card-body .place-rows > * + .col-origin {
border-top: 1px solid var(--line);
}
.trek-dash .place-card-body .place-rows > .col-origin:hover {
background: color-mix(in srgb, var(--ink) 4%, transparent);
}
.trek-dash .place-rows > .place-tag-group {
padding: 12px 14px;
}
.trek-dash .place-rows > .place-tag-group + .place-tag-group {
padding-top: 12px;
border-top: 1px solid var(--line);
}
.trek-dash .place-rows .place-tag-src {
font-size: 13px;
font-weight: 600;
color: var(--ink);
}
.trek-dash .place-rows > .col-origin-sub,
.trek-dash .place-rows > p {
margin: 0;
padding: 12px 14px;
}
.trek-dash .place-panel > *,
.trek-dash .place-aside-body > * {
flex-shrink: 0;
}
/* Changes as a timeline: a dot on a line per change, the field and when, the old
value struck through beside the new one, then who did it and where. */
.trek-dash .place-timeline {
position: relative;
margin: 0;
padding: 0 0 0 4px;
list-style: none;
display: flex;
flex-direction: column;
gap: 14px;
}
.trek-dash .place-timeline::before {
content: '';
position: absolute;
inset-inline-start: 8px;
top: 8px;
bottom: 8px;
width: 1.5px;
border-radius: 2px;
background: var(--line);
}
.trek-dash .place-tl-item {
position: relative;
display: flex;
flex-direction: column;
gap: 6px;
padding-inline-start: 22px;
}
.trek-dash .place-tl-dot {
position: absolute;
inset-inline-start: 0;
top: 4px;
width: 10px;
height: 10px;
border-radius: 999px;
background: var(--surface);
border: 2px solid var(--ink-3);
}
.trek-dash .place-tl-item:first-child .place-tl-dot {
border-color: var(--accent);
background: var(--accent);
}
.trek-dash .place-tl-head {
display: flex;
align-items: baseline;
gap: 10px;
font-size: 13.5px;
color: var(--ink);
}
.trek-dash .place-tl-when {
margin-inline-start: auto;
font-size: 11.5px;
color: var(--ink-3);
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.trek-dash .place-tl-diff {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.trek-dash .place-tl-from {
padding: 4px 9px;
border-radius: 8px;
font-size: 12.5px;
color: var(--ink-3);
text-decoration: line-through;
background: var(--bg);
border: 1px solid var(--line);
overflow-wrap: anywhere;
}
.trek-dash .place-tl-to {
padding: 4px 9px;
border-radius: 8px;
font-size: 12.5px;
color: var(--ink);
background: var(--surface-2);
border: 1px solid var(--line-2);
overflow-wrap: anywhere;
}
.trek-dash .place-tl-arrow {
color: var(--ink-3);
flex-shrink: 0;
}
[dir='rtl'] .trek-dash .place-tl-arrow {
transform: scaleX(-1);
}
.trek-dash .place-tl-meta {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
font-size: 11.5px;
color: var(--ink-3);
}
.trek-dash .place-tl-src {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 999px;
background: var(--bg);
border: 1px solid var(--line);
}
/* A photo tile: opens the lightbox; on hover a round button sets it as the
place's picture, and the one that already is says so in a small badge. */
.trek-dash .place-photo {
position: relative;
aspect-ratio: 1;
overflow: hidden;
border-radius: 10px;
background: var(--surface-2);
}
.trek-dash .place-photo-badge {
position: absolute;
inset-inline-start: 6px;
bottom: 6px;
padding: 2px 7px;
border-radius: 999px;
font-size: 10.5px;
font-weight: 700;
color: #fff;
background: rgb(0 0 0 / 0.55);
backdrop-filter: blur(6px);
pointer-events: none;
}
.trek-dash .place-photo-cover {
position: absolute;
inset-inline-end: 6px;
top: 6px;
width: 28px;
height: 28px;
display: grid;
place-items: center;
border-radius: 999px;
color: #fff;
background: rgb(0 0 0 / 0.5);
border: 1px solid rgb(255 255 255 / 0.25);
backdrop-filter: blur(6px);
opacity: 0;
transition: opacity 0.12s;
}
.trek-dash .place-photo:hover .place-photo-cover,
.trek-dash .place-photo-cover:focus-visible {
opacity: 1;
}
@@ -0,0 +1,7 @@
/** A vote average as the badge on a place's picture shows it: whole stars bare, the rest to one place. */
export const ratingLabel = (rating: number): string => (Number.isInteger(rating) ? String(rating) : rating.toFixed(1));
/** The badge text of an average, or null when there is no vote to show. */
export function ratingBadge(average: number | null | undefined): string | null {
return typeof average === 'number' && average > 0 ? ratingLabel(average) : null;
}
@@ -1,112 +0,0 @@
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,40 @@
import type { PlacesLibraryDetailResponse, PlacesLibraryKind } from '@trek/shared';
import { useCallback, useEffect, useState } from 'react';
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
/**
* One place as All places reads it (every trip and list it sits in, what each
* keeps of it), for a view that opens from somewhere else: a list's place opens
* the same place view as All places, so it reads the same thing. Offline or on an
* error the view keeps its own part and the tabs stay empty.
*
* `revision` is the view's own copy of the place: whenever it changes (a status,
* a vote, an edit, a remote change) the place is read again, so the tabs follow.
* What was read for another place is never shown for this one.
*/
export function useLibraryPlace(kind: PlacesLibraryKind, id: number | null, revision?: unknown) {
const [held, setHeld] = useState<{ key: string; data: PlacesLibraryDetailResponse | null } | null>(null);
const [seq, setSeq] = useState(0);
const key = id == null ? null : `${kind}:${id}`;
useEffect(() => {
if (id == null) return;
const ctrl = new AbortController();
const readKey = `${kind}:${id}`;
placesLibraryRepo
.detail(kind, id, ctrl.signal)
.then((res) => {
if (!ctrl.signal.aborted) setHeld({ key: readKey, data: res });
})
.catch(() => {
// Nothing to show beside the list's own part; the tabs read as empty.
if (!ctrl.signal.aborted) setHeld({ key: readKey, data: null });
});
return () => ctrl.abort();
}, [kind, id, seq, revision]);
const reload = useCallback(() => setSeq((n) => n + 1), []);
const data = held !== null && held.key === key ? held.data : null;
return { data, reload };
}
@@ -73,13 +73,40 @@ export function useOriginNotes({
const targets = all.filter((n) => n.canEdit && !n.text.trim() && n.key !== editing);
const [draft, setDraft] = useState('');
const [busy, setBusy] = useState(false);
const [preview, setPreview] = useState(false);
/** A new note written for every trip and list that has none yet. */
const [everywhere, setEverywhere] = useState(false);
/** The note being written is a new one: it may still be moved to another trip or list. */
const isNew = !!editing && !all.find((n) => n.key === editing)?.text.trim();
/** Where a new note may go: the open one and every other empty one the reader may write. */
const composeTargets = isNew ? all.filter((n) => n.canEdit && !n.text.trim()) : [];
const edit = (note: OriginNote) => {
setChoosing(false);
setEditing(note.key);
setDraft(note.text);
setPreview(false);
setEverywhere(false);
};
const cancel = () => {
setEditing(null);
setPreview(false);
setEverywhere(false);
};
/** The new note goes to another trip or list; what is written so far stays. */
const retarget = (key: string | 'all') => {
if (key === 'all') {
setEverywhere(true);
return;
}
if (!all.some((n) => n.key === key && n.canEdit && !n.text.trim())) return;
setEverywhere(false);
setEditing(key);
};
/** The composer: straight into writing, for the first place a note can go (the chips switch it). */
const compose = () => {
if (targets[0]) edit(targets[0]);
};
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]);
@@ -91,8 +118,12 @@ export function useOriginNotes({
if (!note || busy) return;
setBusy(true);
try {
await note.save(draft.trim() ? draft : null);
const text = draft.trim() ? draft : null;
// Everywhere: the same note in each trip and list that had none, one after another.
const into = everywhere && isNew ? composeTargets : [note];
for (const target of into) await target.save(text);
setEditing(null);
setPreview(false);
onSaved();
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')));
@@ -101,5 +132,24 @@ export function useOriginNotes({
}
};
return { notes, targets, choosing, add, editing, draft, setDraft, busy, edit, cancel, save };
return {
notes,
targets,
choosing,
add,
compose,
editing,
isNew,
composeTargets,
everywhere,
retarget,
draft,
setDraft,
preview,
setPreview,
busy,
edit,
cancel,
save,
};
}
@@ -0,0 +1,138 @@
import type { PlacesLibraryDetailResponse, PlacesLibraryInfo } from '@trek/shared';
import { useMemo, useState } from 'react';
import { placesLibraryRepo, type PlaceDetailsPatch } 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';
/** A trip or list of the place whose copy the reader may change. */
export interface EditTarget {
key: string;
kind: 'trip' | 'list';
source: string;
ref: { kind: 'trip'; trip_id: number; place_id: number } | { kind: 'list'; collection_place_id: number };
info: PlacesLibraryInfo;
}
/** Every copy of the place the reader may edit: its lists first, then its trips; an edit starts from the first. */
export function editTargets(data: PlacesLibraryDetailResponse | null): EditTarget[] {
const { trips, lists } = originPairs(data);
return [
// A list says whether the reader may change its places; a trip says it is read only.
...lists
.filter((p) => p.origin.can_edit)
.map((p) => ({
key: `list:${p.origin.collection_place_id}`,
kind: 'list' as const,
source: originName(p.origin),
ref: { kind: 'list' as const, collection_place_id: p.origin.collection_place_id },
info: p.detail.info,
})),
...trips
.filter((p) => !p.origin.read_only)
.map((p) => ({
key: `trip:${p.origin.place_id}`,
kind: 'trip' as const,
source: originName(p.origin),
ref: { kind: 'trip' as const, trip_id: p.origin.trip_id, place_id: p.origin.place_id },
info: p.detail.info,
})),
];
}
interface Draft {
name: string;
categoryId: number | null;
address: string;
lat: string;
lng: string;
description: string;
}
function draftOf(info: PlacesLibraryInfo): Draft {
return {
name: info.name,
categoryId: info.category?.id ?? null,
address: info.address ?? '',
lat: info.lat == null ? '' : String(info.lat),
lng: info.lng == null ? '' : String(info.lng),
description: info.description ?? '',
};
}
/** The form as the server takes it; a half-typed position keeps the old one. */
export function patchOf(draft: Draft): PlaceDetailsPatch {
const lat = draft.lat.trim() === '' ? null : Number(draft.lat);
const lng = draft.lng.trim() === '' ? null : Number(draft.lng);
const position = lat != null && lng != null && Number.isFinite(lat) && Number.isFinite(lng);
const cleared = lat == null && lng == null;
return {
name: draft.name.trim(),
category_id: draft.categoryId,
address: draft.address.trim() || null,
description: draft.description.trim() || null,
...(position ? { lat, lng } : cleared ? { lat: null, lng: null } : {}),
};
}
/**
* Editing a place of All places, for the desktop dialog and the phone sheet. A
* place there is the copies its lists and trips keep; the form starts from the
* first one the reader may edit and saves there, and the server makes the same
* change on every other copy they may edit (the copies stay in step). Read-only
* trips are not offered. Saving reads the place again.
*/
export function usePlaceEdit({
data,
onSaved,
t,
}: {
data: PlacesLibraryDetailResponse | null;
onSaved: () => void;
t: TranslationFn;
}) {
const toast = useToast();
const targets = useMemo(() => editTargets(data), [data]);
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState<Draft | null>(null);
const [saving, setSaving] = useState(false);
const target = targets[0] ?? null;
const start = () => {
if (!target) return;
setDraft(draftOf(target.info));
setEditing(true);
};
const cancel = () => {
setEditing(false);
setDraft(null);
};
const set = <K extends keyof Draft>(field: K, value: Draft[K]) => setDraft((d) => (d ? { ...d, [field]: value } : d));
const save = async () => {
if (!target || !draft || saving) return;
if (!draft.name.trim()) {
toast.error(t('places.nameRequired'));
return;
}
setSaving(true);
try {
await placesLibraryRepo.saveDetails(target.ref, patchOf(draft));
setEditing(false);
setDraft(null);
onSaved();
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')));
} finally {
setSaving(false);
}
};
return { canEdit: targets.length > 0, target, editing, draft, set, start, cancel, save, saving };
}
export type PlaceEditState = ReturnType<typeof usePlaceEdit>;
@@ -1,7 +1,43 @@
import type { PlaceMediaFile, PlaceMediaResponse, PlacesLibraryEntry, PlacesLibraryKind } from '@trek/shared';
import { useEffect, useMemo, useState } from 'react';
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
import { placeVisitsRepo } from '../../repo/placeVisitsRepo';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { useToast } from '../shared/Toast';
import { originName } from './originName';
/** Where a picture or file added here goes: a trip's files, or a list's picture of the place. */
export interface MediaTarget {
key: string;
kind: 'trip' | 'list';
source: string;
ref: { kind: 'trip'; trip_id: number; place_id: number } | { kind: 'list'; collection_place_id: number };
}
/** Every trip and list of the place that takes an upload from the reader: trips first, they keep any file. */
export function mediaTargets(entry: PlacesLibraryEntry | null): MediaTarget[] {
const origins = entry?.origins ?? [];
const out: MediaTarget[] = [];
for (const o of origins)
if (o.kind === 'trip' && o.can_edit && !o.read_only)
out.push({
key: `trip:${o.place_id}`,
kind: 'trip',
source: originName(o),
ref: { kind: 'trip', trip_id: o.trip_id, place_id: o.place_id },
});
for (const o of origins)
if (o.kind === 'list' && o.can_edit)
out.push({
key: `list:${o.collection_place_id}`,
kind: 'list',
source: originName(o),
ref: { kind: 'list', collection_place_id: o.collection_place_id },
});
return out;
}
/** One picture of a place, as the strip and the lightbox show it. */
export interface PlacePhoto {
@@ -57,10 +93,16 @@ function originKey(entry: PlacesLibraryEntry | null): string | null {
* 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) {
export function usePlaceMedia(entry: PlacesLibraryEntry | null, t?: TranslationFn, onChanged?: () => void) {
const toast = useToast();
const [media, setMedia] = useState<{ key: string; res: PlaceMediaResponse } | null>(null);
const [open, setOpen] = useState<number | null>(null);
const [seq, setSeq] = useState(0);
const [uploading, setUploading] = useState(false);
/** The target picked when there are several, until the file dialog answers. */
const [choosing, setChoosing] = useState(false);
const key = originKey(entry);
const targets = useMemo(() => mediaTargets(entry), [entry]);
useEffect(() => {
if (!key) return;
@@ -76,10 +118,69 @@ export function usePlaceMedia(entry: PlacesLibraryEntry | null) {
if (!ctrl.signal.aborted) setMedia({ key, res: { images: [], journey_photos: [], files: [] } });
});
return () => ctrl.abort();
}, [key]);
}, [key, seq]);
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) };
/**
* Adds the picked files where each target keeps them: a trip takes every file,
* a list one picture (the first image picked). Several targets ("everywhere")
* get the same files, each as it can keep them.
*/
const upload = async (to: readonly MediaTarget[], picked: readonly File[]) => {
const jobs = to.flatMap((target) =>
(target.kind === 'list' ? picked.filter((f) => f.type.startsWith('image/')).slice(0, 1) : picked).map(
(file) => [target, file] as const
)
);
if (!jobs.length || uploading) return;
setUploading(true);
setChoosing(false);
try {
for (const [target, file] of jobs) await placesLibraryRepo.uploadMedia(target.ref, file);
setSeq((n) => n + 1);
} catch (err) {
toast.error(getApiErrorMessage(err, t ? t('files.uploadError') : 'Upload failed'));
} finally {
setUploading(false);
}
};
/** The place's own picture now, to mark it among the photos. */
const cover = entry?.image_url ?? null;
/** A photo that may become the place's picture: one of the place's own images, not a journey's. */
const canCover = (photo: PlacePhoto) => targets.length > 0 && photo.id.startsWith('img:') && photo.src !== cover;
/** The photo as the place's picture in every list and trip the reader may change it in. */
const setCover = async (photo: PlacePhoto) => {
if (!canCover(photo) || uploading) return;
setUploading(true);
try {
for (const target of targets) await placesLibraryRepo.setImage(target.ref, photo.src);
setSeq((n) => n + 1);
onChanged?.();
} catch (err) {
toast.error(getApiErrorMessage(err, t ? t('common.error') : 'Error'));
} finally {
setUploading(false);
}
};
return {
cover,
canCover,
setCover,
photos,
files,
open,
setOpen,
close: () => setOpen(null),
targets,
choosing,
setChoosing,
upload,
uploading,
};
}
@@ -0,0 +1,60 @@
import type { PlaceRatingVote, PlacesLibraryDetailResponse, PlacesLibraryVote } from '@trek/shared';
import { useState } from 'react';
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { useToast } from '../shared/Toast';
/**
* The votes on a place of All places, for the desktop dialog and the phone sheet.
* A vote belongs to the person: one vote counts for every copy of the place in
* their lists and trips, so the row shows the place's one rating (each person
* once) and casts or takes back the reader's vote for all of those copies.
*/
export function usePlaceRating({
data,
onChanged,
t,
}: {
data: PlacesLibraryDetailResponse | null;
onChanged: () => void;
t: TranslationFn;
}) {
const toast = useToast();
const [busy, setBusy] = useState(false);
const entry = data?.entry ?? null;
const rating = entry ? (entry.rating ?? { average: null, count: 0, mine: null }) : null;
const votes = (rating?.votes ?? []).map(voteOfEntry);
const rate = async (value: number | null) => {
if (!entry || busy) return;
setBusy(true);
try {
await placesLibraryRepo.rateEntry(entry.key, value);
onChanged();
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')));
} finally {
setBusy(false);
}
};
return { rating, votes, rate, busy };
}
export type PlaceRatingState = ReturnType<typeof usePlaceRating>;
/**
* A voter of the entry as the shared rating row reads them: the server hands
* the picture out resolved (`avatar_url`), the row resolves the stored value
* itself (`avatarSrc`), so an uploaded picture goes back to its file name and
* an SSO picture stays the URL it is.
*/
export function voteOfEntry(vote: PlacesLibraryVote): PlaceRatingVote {
const url = vote.avatar_url;
const avatar = url?.startsWith(UPLOADED_AVATAR) ? url.slice(UPLOADED_AVATAR.length) : url;
return { user_id: vote.user_id, username: vote.username, avatar, rating: vote.rating };
}
const UPLOADED_AVATAR = '/uploads/avatars/';
@@ -0,0 +1,88 @@
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import { History, Images, LayoutGrid, NotebookPen, Ticket, type LucideIcon } from 'lucide-react';
import { useCallback, useState } from 'react';
import type { TranslationFn } from '../../types';
import { useOriginNotes } from './useOriginNotes';
import { usePlaceActivities } from './usePlaceActivities';
import { usePlaceHistory } from './usePlaceHistory';
import { usePlaceMedia } from './usePlaceMedia';
import { usePlaceVisits } from './usePlaceVisits';
export type PlaceTab = 'overview' | 'notes' | 'activities' | 'media' | 'history';
export const PLACE_TABS: readonly PlaceTab[] = ['overview', 'notes', 'activities', 'media', 'history'];
/** The key of the word a tab carries, and of what it says when empty (read by lint:i18n-keys as key builders). */
const tabLabelKey = (tab: PlaceTab): string => `placeSheet.tab.${tab}`;
const tabEmptyKey = (tab: PlaceTab): string => `placeSheet.empty.${tab}`;
/** The word each tab carries. */
export const PLACE_TAB_LABEL = Object.fromEntries(PLACE_TABS.map((tab) => [tab, tabLabelKey(tab)])) as Record<
PlaceTab,
string
>;
/** The symbol each tab shows when it is empty, on the desktop and the phone alike. */
export const PLACE_TAB_ICON: Record<PlaceTab, LucideIcon> = {
overview: LayoutGrid,
notes: NotebookPen,
activities: Ticket,
media: Images,
history: History,
};
/** What an empty tab says instead of its part; the overview is never empty. */
export const PLACE_TAB_EMPTY = Object.fromEntries(
PLACE_TABS.map((tab) => [tab, tab === 'overview' ? '' : tabEmptyKey(tab)])
) as Record<PlaceTab, string>;
/**
* Everything the one place view shows beside the place itself, for the desktop
* dialog and the phone sheet, whether it opened from All places or from a list:
* the visits, the notes of every trip and list, the linked tours and bookings,
* the pictures and files, the change history, and which tab is open. Each part
* is read once here, so a tab can show how much it holds before it is opened.
*/
export function usePlaceSheet({
data,
onChanged,
t,
}: {
data: PlacesLibraryDetailResponse | null;
/** Something of the place was saved: read it again. */
onChanged: () => void;
t: TranslationFn;
}) {
const entry = data?.entry ?? null;
const visits = usePlaceVisits({ entry });
const notes = useOriginNotes({ data, onSaved: onChanged, t });
const activities = usePlaceActivities({ entry, t });
const history = usePlaceHistory(entry);
const media = usePlaceMedia(entry, t, onChanged);
// The tab is picked for one place: another place starts on its overview.
const key = entry?.key ?? null;
const [picked, setPicked] = useState<{ key: string | null; tab: PlaceTab }>({ key, tab: 'overview' });
const tab = picked.key === key ? picked.tab : 'overview';
const setTab = useCallback((next: PlaceTab) => setPicked({ key, tab: next }), [key]);
const counts: Record<PlaceTab, number> = {
overview: 0,
notes: notes.notes.length,
activities: activities.activities.length,
media: media.photos.length + media.files.length,
history: history.entries.length,
};
/** A tab with nothing in it and nothing to add shows a quiet empty state instead. */
const empty: Record<PlaceTab, boolean> = {
overview: false,
notes: counts.notes === 0 && notes.targets.length === 0,
activities: counts.activities === 0 && !activities.canLink,
media: counts.media === 0 && media.targets.length === 0,
history: counts.history === 0,
};
return { entry, tab, setTab, counts, empty, visits, notes, activities, history, media };
}
export type PlaceSheetState = ReturnType<typeof usePlaceSheet>;
@@ -0,0 +1,139 @@
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import { useMemo, useState } from 'react';
import { placesLibraryRepo, type OriginTagRef } 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';
export interface PlaceTag {
id: number;
name: string;
color: string | null;
}
/** The tags one list or one trip gives the place, and the ones it could give. */
export interface TagGroup {
key: string;
kind: 'list' | 'trip';
source: string;
ref: OriginTagRef;
assigned: PlaceTag[];
available: PlaceTag[];
canEdit: boolean;
}
const asTag = (x: { id: number; name: string; color?: string | null }): PlaceTag => ({
id: x.id,
name: x.name,
color: x.color ?? null,
});
/** Every list and trip of the place with its tags: the lists first, then the trips. */
export function tagGroups(data: PlacesLibraryDetailResponse | null): TagGroup[] {
const { trips, lists } = originPairs(data);
return [
...lists.map(({ origin, detail }) => ({
key: `list:${origin.collection_place_id}`,
kind: 'list' as const,
source: originName(origin),
ref: {
kind: 'list' as const,
collection_id: origin.collection_id,
collection_place_id: origin.collection_place_id,
},
assigned: detail.labels.map(asTag),
available: detail.available_tags.map(asTag),
canEdit: detail.can_edit_tags,
})),
...trips.map(({ origin, detail }) => ({
key: `trip:${origin.place_id}`,
kind: 'trip' as const,
source: originName(origin),
ref: { kind: 'trip' as const, trip_id: origin.trip_id, place_id: origin.place_id },
assigned: detail.tags.map(asTag),
available: detail.available_tags.map(asTag),
canEdit: detail.can_edit_tags,
})),
];
}
/** Tags whose name holds the trimmed, case-folded query; all of them for an empty one. */
export function matchTags(tags: readonly PlaceTag[], query: string): PlaceTag[] {
const q = query.trim().toLowerCase();
return q ? tags.filter((tag) => tag.name.toLowerCase().includes(q)) : [...tags];
}
/**
* The tags of a place, for the one place view on the desktop and the phone: each
* list and each trip gives the place its own, which everyone in that list or trip
* sees. Putting one on or taking it off, and making a new one from the search,
* happen in the list or trip the group belongs to; one picker is open at a time.
*/
export function usePlaceTags({
data,
onChanged,
t,
}: {
data: PlacesLibraryDetailResponse | null;
onChanged: () => void;
t: TranslationFn;
}) {
const toast = useToast();
const groups = useMemo(() => tagGroups(data), [data]);
const [openKey, setOpenKey] = useState<string | null>(null);
const [query, setQuery] = useState('');
const [busy, setBusy] = useState(false);
const total = useMemo(() => {
const names = new Set<string>();
for (const g of groups) for (const tag of g.assigned) names.add(tag.name.toLowerCase());
return names.size;
}, [groups]);
const open = groups.find((g) => g.key === openKey) ?? null;
const matches = open ? matchTags(open.available, query) : [];
const trimmed = query.trim();
const canCreate =
!!open && trimmed !== '' && !open.available.some((tag) => 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 = (group: TagGroup, tagId: number) =>
run(() => {
const ids = group.assigned.map((tag) => tag.id);
const next = ids.includes(tagId) ? ids.filter((id) => id !== tagId) : [...ids, tagId];
return placesLibraryRepo.setOriginTags(group.ref, next);
});
/** The typed name as a new tag of the open group's list or trip, put straight on the place. */
const createAndAdd = () =>
run(async () => {
if (!open || !trimmed) return;
const tag = await placesLibraryRepo.createOriginTag(open.ref, { name: trimmed });
setQuery('');
await placesLibraryRepo.setOriginTags(open.ref, [...open.assigned.map((x) => x.id), tag.id]);
});
const openPicker = (key: string | null) => {
setOpenKey(key);
setQuery('');
};
return { groups, total, openKey, openPicker, query, setQuery, matches, canCreate, toggle, createAndAdd, busy };
}
export type PlaceTagsState = ReturnType<typeof usePlaceTags>;
@@ -84,10 +84,17 @@ 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])),
// At least this many stars on the average of the votes, as the lists filter; unrated places drop out.
const [minRating, setMinRating] = useState<number | 'all'>('all');
// PLC-21: tag names of the lists and trips, any of which an entry must carry, whatever their case.
const [tagNames, setTagNames] = useState<string[]>([]);
const toggleTagName = useCallback(
(name: string) =>
setTagNames((names) => {
const key = name.trim().toLowerCase();
const kept = names.filter((n) => n.trim().toLowerCase() !== key);
return kept.length < names.length || key === '' ? kept : [...names, name.trim()];
}),
[]
);
@@ -103,20 +110,28 @@ function useLibraryFilters() {
...(kind !== 'all' ? { kind } : {}),
...(categoryId !== 'all' ? { category_id: categoryId } : {}),
...(status !== 'all' ? { status } : {}),
...(tagIds.length > 0 ? { tag_ids: tagIds } : {}),
...(tagNames.length > 0 ? { tags: tagNames } : {}),
...(minRating !== 'all' ? { min_rating: minRating } : {}),
sort,
limit: PAGE,
}),
[query, kind, categoryId, status, tagIds, sort]
[query, kind, categoryId, status, tagNames, minRating, sort]
);
const filtered = query !== '' || kind !== 'all' || categoryId !== 'all' || status !== 'all' || tagIds.length > 0;
const filtered =
query !== '' ||
kind !== 'all' ||
categoryId !== 'all' ||
status !== 'all' ||
tagNames.length > 0 ||
minRating !== 'all';
const resetFilters = useCallback(() => {
setSearch('');
setQuery('');
setKind('all');
setCategoryId('all');
setStatus('all');
setTagIds([]);
setTagNames([]);
setMinRating('all');
}, []);
return {
@@ -132,8 +147,10 @@ function useLibraryFilters() {
setSort,
status,
setStatus,
tagIds,
toggleTag,
tagNames,
toggleTagName,
minRating,
setMinRating,
filtered,
resetFilters,
},
@@ -286,6 +303,44 @@ function useLibraryCover(detail: PlacesLibraryDetailResponse | null): string | n
return entry && photo?.key === entry.key ? photo.url : null;
}
type TagOption = { name: string; color: string | null };
/** The tag names seen so far with those of these entries added, by case-folded name; the same map when none is new. */
function withTagsOf(
seen: ReadonlyMap<string, TagOption>,
entries: readonly PlacesLibraryEntry[]
): ReadonlyMap<string, TagOption> {
let next: Map<string, TagOption> | null = null;
for (const entry of entries)
for (const tag of entry.tags ?? []) {
const key = tag.name.toLowerCase();
if (seen.has(key) || next?.has(key)) continue;
next ??= new Map(seen);
next.set(key, { name: tag.name, color: tag.color ?? null });
}
return next ?? seen;
}
/**
* The tag names the filter offers: every tag seen on a place since the page
* opened (a filter that narrows the list does not take its own options away),
* and every picked one, sorted by name.
*/
export function useTagOptions(entries: readonly PlacesLibraryEntry[], picked: readonly string[]) {
// What was seen is kept beside the entries it was read from, so new entries add to it while rendering.
const [held, setHeld] = useState(() => ({ entries, seen: withTagsOf(new Map(), entries) }));
let seen = held.seen;
if (held.entries !== entries) {
seen = withTagsOf(held.seen, entries);
setHeld({ entries, seen });
}
return useMemo(() => {
const all = new Map(seen);
for (const name of picked) if (!all.has(name.toLowerCase())) all.set(name.toLowerCase(), { name, color: null });
return [...all.values()].sort((x, y) => x.name.localeCompare(y.name));
}, [seen, picked]);
}
/**
* "All places" (PLC-07, PLC-08): every place of the user's trips and lists in one
* overview, behind the desktop view and the phone screen, which render their own
@@ -309,11 +364,13 @@ export function usePlacesLibrary({ active, t }: { active: boolean; t: Translatio
}, []);
const { entries, total, counts, error, offline } = pages.page;
const mappable = useMemo(() => entries.filter(entryHasPosition), [entries]);
const tagOptions = useTagOptions(entries, pages.controls.tagNames);
return {
...pages.controls,
entries,
mappable,
tagOptions,
total,
counts,
hasMore: pages.hasMore,
@@ -20,19 +20,28 @@ export interface CopyResult {
skipped: { id: number; name: string }[];
}
/** A tag the copied places carry: one of the list's tags, or an older tag kept on the saved place. */
export interface CarryTag {
/** `label:<id>` or `tag:<id>`: the two kinds number their ids apart. */
key: string;
name: string;
color?: string | null;
}
/** What the copied places carry that may come along: their notes and their tags (#3168). */
export interface CopyCarryOptions {
hasNotes: boolean;
tags: { id: number; name: string; color?: string | null }[];
/** The reader's own tags on the place (PLC-21), private unless picked here. */
personalTags?: { id: number; name: string; color?: string | null }[];
tags: CarryTag[];
}
/** The carry key of a list tag or of an older tag on a saved place. */
export const carryKey = (source: 'label' | 'tag', id: number) => `${source}:${id}`;
/** 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[];
label_ids?: number[];
}
export interface TripCopyPickerOptions {
@@ -74,13 +83,11 @@ export function useTripCopyPicker({
const [loading, setLoading] = useState(false);
const [search, setSearch] = useState('');
const [busyTripId, setBusyTripId] = useState<number | null>(null);
// A personal note or tag stays in the list unless the reader takes it along on purpose.
// A note or tag stays in the list unless the reader takes it along on purpose.
const [includeNotes, setIncludeNotes] = useState(false);
const [tagIds, setTagIds] = useState<number[]>([]);
const toggleTag = (id: number) => setTagIds((ids) => (ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id]));
const [personalTagIds, setPersonalTagIds] = useState<number[]>([]);
const togglePersonalTag = (id: number) =>
setPersonalTagIds((ids) => (ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id]));
const [tagIds, setTagIds] = useState<string[]>([]);
const toggleTag = (key: string) =>
setTagIds((keys) => (keys.includes(key) ? keys.filter((x) => x !== key) : [...keys, key]));
useEffect(() => {
if (!open) return;
@@ -89,7 +96,6 @@ export function useTripCopyPicker({
setSearch('');
setIncludeNotes(false);
setTagIds([]);
setPersonalTagIds([]);
tripsApi
.list()
.then((res: { trips?: TripOption[] }) => {
@@ -121,12 +127,12 @@ export function useTripCopyPicker({
try {
const carry: CopyCarry = {};
if (includeNotes && carryOptions?.hasNotes) carry.include_notes = true;
const offered = new Set(carryOptions?.tags.map((tag) => tag.id) ?? []);
const tags = tagIds.filter((id) => offered.has(id));
if (tags.length) carry.tag_ids = tags;
const 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 offered = new Set(carryOptions?.tags.map((tag) => tag.key) ?? []);
const picked = tagIds.filter((key) => offered.has(key));
const idsOf = (source: string) =>
picked.filter((key) => key.startsWith(`${source}:`)).map((key) => Number(key.slice(source.length + 1)));
if (idsOf('label').length) carry.label_ids = idsOf('label');
if (idsOf('tag').length) carry.tag_ids = idsOf('tag');
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 }));
@@ -139,8 +145,7 @@ export function useTripCopyPicker({
}
};
const offersCarry =
!!carryOptions && (carryOptions.hasNotes || carryOptions.tags.length > 0 || !!carryOptions.personalTags?.length);
const offersCarry = !!carryOptions && (carryOptions.hasNotes || carryOptions.tags.length > 0);
return {
loading,
@@ -155,7 +160,5 @@ export function useTripCopyPicker({
setIncludeNotes,
tagIds,
toggleTag,
personalTagIds,
togglePersonalTag,
};
}