Files
TREK/client/src/components/Collections/CollectionPlaceDetail.tsx
T
Maurice e539860530 fix(quality): resolve reliability findings on dev
The Sonar quality gate rated new code D. Preserve focus and keyboard interaction through native controls and shared dialog behavior. Replace ambiguous regex scans with bounded parsing and make numeric coercion and initialization explicit.
2026-12-01 21:06:05 +01:00

548 lines
18 KiB
TypeScript

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 { focusRevealedEditor } from '../shared/dialogFocus';
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;
}
}
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 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;
/** Cast/clear the current user's star vote (#1435); every member may vote. */
onRate?: (rating: number | null) => Promise<void> | void;
t: TranslationFn;
}
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;
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>
);
}
type Form = ReturnType<typeof useCollectionPlaceForm>;
/** The cover: the picture or a gradient, the category, the picture controls and the name. */
function Cover({
place,
form,
canEdit,
categories,
labelId,
onUploadImage,
t,
}: {
place: CollectionPlace;
form: Form;
canEdit: boolean;
categories: Category[];
labelId: string;
onUploadImage?: (file: File) => Promise<void>;
t: TranslationFn;
}) {
const coverInputRef = useRef<HTMLInputElement>(null);
const CatIcon = getCategoryIcon(place.category?.icon);
const banner = form.cover;
return (
<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"
onClick={form.handleImageRemove}
aria-label={t('places.removeImage')}
>
<Trash2 size={16} />
</button>
</Tooltip>
)}
<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-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}
/>
)}
<input
value={form.name}
onChange={(e) => form.setName(e.target.value)}
className="col-detail-name-input min-w-0 flex-1"
ref={focusRevealedEditor}
aria-label={t('common.name')}
/>
</div>
) : (
<>
<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}
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>
);
}