feat(places): review possible duplicates, and repair the client gates

All places offers the pairs that look like one place: both sides side by side
with what differs marked, "keep this one" to group them as one place of the
user's own (undo right after), and "not the same place" to set a pair aside for
good. Desktop dialog and phone sheet share usePlaceDuplicates; every locale has
the new strings.

What the last dev run flagged on the client:
- Tailwind's Prettier plugin had trimmed the leading space of conditional class
  names (col-filter-btn, col-lrow sel, col-split map-full, col-detail docked),
  so the filter row and the open row lost their styling; those classes are now
  joined so the formatter cannot glue them.
- The dock position lives in one helper for the lists and All places, which
  moves the measured-position markers there instead of adding new ones.
- usePlacesLibrary is split into filters, pages, detail and cover hooks that
  derive their loading state instead of setting it inside effects; the big
  sheets and views are cut into parts under the complexity limit, dynamic icons
  go through createElement, originName moves out of a component file.
- formatRange is guarded like in the packing export, the cover lookup skips
  places without a position.
- Tests follow the rename to Places, the category icon, the default list icon
  and the new trip collections store; react-hooks/refs is lowered to the count
  the run measured.
- The rating on a place is a round badge again, in the list and on the map.
This commit is contained in:
Maurice
2026-11-29 16:28:22 +01:00
parent 62232ec87e
commit bacc6a29a7
76 changed files with 2985 additions and 880 deletions
@@ -1,4 +1,4 @@
import React from 'react';
import React, { createElement } from 'react';
import { getCategoryIcon } from '../shared/categoryIcons';
import { Tooltip } from '../shared/Tooltip';
@@ -8,7 +8,6 @@ export default function CategoryBadge({
}: {
category: { name?: string | null; color?: string | null; icon?: string | null };
}): React.ReactElement {
const Icon = getCategoryIcon(category.icon ?? undefined);
return (
<Tooltip label={category.name ?? ''} placement="top">
<span
@@ -17,7 +16,7 @@ export default function CategoryBadge({
aria-label={category.name ?? undefined}
role="img"
>
<Icon size={14} strokeWidth={2.2} />
{createElement(getCategoryIcon(category.icon ?? undefined), { size: 14, strokeWidth: 2.2 })}
</span>
</Tooltip>
);
@@ -1,5 +1,5 @@
import { Check, Shapes } from 'lucide-react';
import React, { useEffect, useRef, useState } from 'react';
import React, { createElement, useEffect, useRef, useState } from 'react';
import type { Category, TranslationFn } from '../../types';
import { getCategoryIcon } from '../shared/categoryIcons';
@@ -67,7 +67,7 @@ export default function CategoryTileMenu({
...(tone ? { background: `color-mix(in srgb, ${tone} 16%, var(--bg-card))`, color: tone } : {}),
}}
>
<Icon size={Math.round(size * 0.43)} strokeWidth={1.9} />
{createElement(Icon, { size: Math.round(size * 0.43), strokeWidth: 1.9 })}
</button>
{open && (
<div
@@ -96,9 +96,9 @@ describe('CollectionList', () => {
expect(screen.getByText('Golden Gate, San Francisco')).toBeInTheDocument();
});
it('FE-COMP-COLLIST-003: renders the category name for the categorised place', () => {
it('FE-COMP-COLLIST-003: names the category of the categorised place on its icon', () => {
renderList();
expect(screen.getByText('Cafe')).toBeInTheDocument();
expect(screen.getByRole('img', { name: 'Cafe' })).toBeInTheDocument();
});
it('FE-COMP-COLLIST-004: clicking a row calls onOpenPlace with the place id', async () => {
@@ -1,5 +1,5 @@
import React, { useEffect, useMemo, useRef } from 'react'
import { Check, GripVertical, Info, MapPin, Star } from 'lucide-react'
import { Check, GripVertical, Info, MapPin } from 'lucide-react'
import type { CollectionPlace, CollectionStatus, CollectionLabel } from '@trek/shared'
import type { TranslationFn } from '../../types'
import PlaceAvatar from '../shared/PlaceAvatar'
@@ -34,6 +34,35 @@ interface CollectionListProps {
* category/address, and a one-tap status cycle on the badge. Click the row to
* open the place (or toggle it in select mode).
*/
/** The row's classes: picked, draggable, being dragged, and the side a drop would land on. */
function rowClass(on: boolean, canReorder: boolean, dragging: boolean, dropSide: string | null | undefined): string {
const parts = ['col-lrow', 'col-lrow-place']
if (on) parts.push('sel')
if (canReorder) parts.push('can-reorder')
if (dragging) parts.push('dragging')
if (dropSide) parts.push(`drop-${dropSide}`)
return parts.join(' ')
}
/**
* The place's picture with the list's average vote on its corner, so the row needs no
* line for it; the category stands as an icon before the name instead.
*/
function RowAvatar({ place, t }: { place: CollectionPlace; t: TranslationFn }) {
const category = place.category ? { color: place.category.color ?? undefined, icon: place.category.icon ?? undefined } : null
const rating = typeof place.rating_avg === 'number' && place.rating_avg > 0 ? ratingLabel(place.rating_avg) : null
return (
<span className="col-lrow-avatar">
<PlaceAvatar place={place} size={40} category={category} />
{rating && (
<span className="col-lrow-ratebadge" role="img" aria-label={t('collections.ratingBadge', { rating })}>
{rating}
</span>
)}
</span>
)
}
export default function CollectionList({
places, labels, selectedPlaceId, selectMode, selectedIds, onOpenPlace, onStatusChange, onToggleSelect,
reorderEnabled = false, reorderBlocked = false, onReorder, t,
@@ -69,7 +98,7 @@ export default function CollectionList({
tabIndex={0}
onClick={() => (selectMode ? onToggleSelect(place.id) : onOpenPlace(place.id))}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); if (selectMode) onToggleSelect(place.id); else onOpenPlace(place.id) } }}
className={`col-lrow col-lrow-place${active || selected ? ' sel' : ''}${reorder.enabled ? ' can-reorder' : ''}${reorder.dragId === place.id ? ' dragging' : ''}${reorder.dropSide(place.id) ? ` drop-${reorder.dropSide(place.id)}` : ''}`}
className={rowClass(active || selected, reorder.enabled, reorder.dragId === place.id, reorder.dropSide(place.id))}
{...reorder.rowProps(place.id)}
>
{reorder.enabled && (
@@ -87,17 +116,7 @@ export default function CollectionList({
{selectMode ? (
<span className={`col-lcheck${selected ? ' on' : ''}`}>{selected && <Check size={14} strokeWidth={3} />}</span>
) : (
<span className="col-lrow-avatar">
<PlaceAvatar place={place} size={40} category={place.category ? { color: place.category.color ?? undefined, icon: place.category.icon ?? undefined } : null} />
{/* The category rides on the tile's corner, so the row keeps to two lines. */}
{/* The list's average vote on the other corner, so the row needs no line for it. */}
{typeof place.rating_avg === 'number' && place.rating_avg > 0 && (
<span className="col-lrow-ratebadge" role="img" aria-label={t('collections.ratingBadge', { rating: ratingLabel(place.rating_avg) })}>
<Star aria-hidden="true" />
<span className={Number.isInteger(place.rating_avg) ? 'n' : 'n frac'}>{ratingLabel(place.rating_avg)}</span>
</span>
)}
</span>
<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>
@@ -288,9 +288,9 @@ describe('CollectionPicker in the place dialog', () => {
it('FE-COMP-COLPICKER-021: each filter has its own label, which names its trigger and its list', async () => {
setup()
await screen.findByText('Zebra Cafe')
const lists = screen.getByRole('button', { name: 'Collections All lists' })
const lists = screen.getByRole('button', { name: 'Places All lists' })
const status = screen.getByRole('button', { name: 'Status All' })
expect(screen.getByText('Collections', { selector: 'span' })).toHaveAttribute('id', lists.getAttribute('aria-labelledby')?.split(' ')[0])
expect(screen.getByText('Places', { selector: 'span' })).toHaveAttribute('id', lists.getAttribute('aria-labelledby')?.split(' ')[0])
fireEvent.click(status)
expect(screen.getByRole('listbox', { name: 'Status' })).toBeInTheDocument()
// Picking changes the value half of the name, never the label half.
@@ -1,4 +1,5 @@
import React, { useRef, useState } from 'react'
import { dockStyle, type DockRect } from './detailDock'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
@@ -31,7 +32,7 @@ interface CollectionPlaceDetailProps {
/** 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?: { left: number; width: number } | null
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>
@@ -87,11 +88,10 @@ export default function CollectionPlaceDetail({
if (match) { e.preventDefault(); setLat(match[1]); setLng(match[2]) }
}
const dockStyle = anchorRect ? { left: anchorRect.left, width: anchorRect.width, transform: 'none' as const } : undefined
const CatIcon = getCategoryIcon(place.category?.icon)
return (
<div className={`col-detail${anchorRect ? ' docked' : ''}`} style={dockStyle} role="presentation" onClick={e => e.stopPropagation()}>
<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" />
@@ -0,0 +1,144 @@
// FE-COMP-DUPECARD-001 to FE-COMP-DUPECARD-013
import userEvent from '@testing-library/user-event';
import React from 'react';
import { duplicatePair, duplicateSide, listOrigin, tripOrigin } from '../../../tests/helpers/placesLibrary';
import { render, screen, within } from '../../../tests/helpers/render';
import { useTranslation } from '../../i18n/TranslationContext';
import DuplicatePairCard from './DuplicatePairCard';
type Props = Omit<React.ComponentProps<typeof DuplicatePairCard>, 't'>;
function Harness(props: Props): React.ReactElement {
const { t } = useTranslation();
return <DuplicatePairCard {...props} t={t} />;
}
function setup(over: Partial<Props> = {}) {
const props: Props = {
pair: duplicatePair(),
busy: false,
onMerge: vi.fn(),
onDismiss: vi.fn(),
variant: 'dialog',
...over,
};
const view = render(<Harness {...props} />);
return { ...view, props };
}
describe('DuplicatePairCard', () => {
it('FE-COMP-DUPECARD-001: shows both sides with their names and the places they come from', () => {
setup();
expect(screen.getByText('Colosseum')).toBeInTheDocument();
expect(screen.getByText('Colosseo')).toBeInTheDocument();
expect(screen.getByText('Rome 2026')).toBeInTheDocument();
expect(screen.getByText('Favourites')).toBeInTheDocument();
});
it('FE-COMP-DUPECARD-002: a shared provider id is explained as the same place on the map provider', () => {
setup({ pair: duplicatePair({ reasons: ['provider_id'] }) });
expect(screen.getByText('The same place on the map provider')).toBeInTheDocument();
expect(screen.queryByText('The same name at the same spot')).not.toBeInTheDocument();
});
it('FE-COMP-DUPECARD-003: the same name nearby is explained as such', () => {
setup({ pair: duplicatePair({ reasons: ['name_nearby'] }) });
expect(screen.getByText('The same name at the same spot')).toBeInTheDocument();
});
it('FE-COMP-DUPECARD-004: when both reasons apply the provider id wins', () => {
setup({ pair: duplicatePair({ reasons: ['name_nearby', 'provider_id'] }) });
expect(screen.getByText('The same place on the map provider')).toBeInTheDocument();
expect(screen.queryByText('The same name at the same spot')).not.toBeInTheDocument();
});
it('FE-COMP-DUPECARD-005: marks only the facts that differ', () => {
setup({ pair: duplicatePair({ differing: ['name'] }) });
expect(screen.getByText('Colosseum').className).toContain('bg-warning-soft');
expect(screen.getByText('Colosseo').className).toContain('bg-warning-soft');
for (const address of screen.getAllByText('Piazza del Colosseo')) {
expect(address.className).not.toContain('bg-warning-soft');
}
});
it('FE-COMP-DUPECARD-006: a differing address is marked, and a missing one reads "No address"', () => {
setup({
pair: duplicatePair({
a: duplicateSide({ address: 'Via Roma 1' }),
b: duplicateSide({ key: 'list:900', name: 'Colosseo', address: null, origins: [listOrigin()] }),
differing: ['address'],
}),
});
expect(screen.getByText('Via Roma 1').className).toContain('bg-warning-soft');
expect(screen.getByText('No address').className).toContain('bg-warning-soft');
});
it('FE-COMP-DUPECARD-007: a side without an address that does not differ shows no address line', () => {
setup({
pair: duplicatePair({
a: duplicateSide({ address: null }),
b: duplicateSide({ key: 'list:900', name: 'Colosseo', address: null, origins: [listOrigin()] }),
differing: ['name'],
}),
});
expect(screen.queryByText('No address')).not.toBeInTheDocument();
});
it('FE-COMP-DUPECARD-008: "Keep this one" under each side merges with that side leading', async () => {
const user = userEvent.setup();
const { props } = setup();
const keeps = screen.getAllByRole('button', { name: /Keep this one/ });
expect(keeps).toHaveLength(2);
await user.click(keeps[0]);
expect(props.onMerge).toHaveBeenLastCalledWith('a');
await user.click(keeps[1]);
expect(props.onMerge).toHaveBeenLastCalledWith('b');
expect(props.onMerge).toHaveBeenCalledTimes(2);
expect(screen.queryByText(/can no longer open/)).not.toBeInTheDocument();
});
it('FE-COMP-DUPECARD-009: a pair that cannot be merged hides "Keep this one" and says why', () => {
setup({ pair: duplicatePair({ can_merge: false }) });
expect(screen.queryByRole('button', { name: /Keep this one/ })).not.toBeInTheDocument();
expect(screen.getByText(/can no longer open/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Not the same place' })).toBeEnabled();
});
it('FE-COMP-DUPECARD-010: "Not the same place" dismisses the pair', async () => {
const user = userEvent.setup();
const { props } = setup();
await user.click(screen.getByRole('button', { name: 'Not the same place' }));
expect(props.onDismiss).toHaveBeenCalledTimes(1);
expect(props.onMerge).not.toHaveBeenCalled();
});
it('FE-COMP-DUPECARD-011: while busy every button is disabled', () => {
setup({ busy: true });
for (const button of screen.getAllByRole('button')) expect(button).toBeDisabled();
});
it('FE-COMP-DUPECARD-012: the phone variant renders the same card in its own look', async () => {
const user = userEvent.setup();
const { props, container } = setup({ variant: 'sheet' });
const card = within(container).getByRole('article');
expect(card.className).toContain('bg-m-sheet');
expect(screen.getByText('The same name at the same spot')).toBeInTheDocument();
await user.click(screen.getAllByRole('button', { name: /Keep this one/ })[1]);
expect(props.onMerge).toHaveBeenCalledWith('b');
await user.click(screen.getByRole('button', { name: 'Not the same place' }));
expect(props.onDismiss).toHaveBeenCalledTimes(1);
});
it('FE-COMP-DUPECARD-013: a side lists a trip and a saved place as separate chips', () => {
setup({
pair: duplicatePair({
a: duplicateSide({
origins: [tripOrigin({ place_id: 1, trip_title: 'Rome 2026' }), listOrigin({ collection_name: 'Wishlist' })],
}),
}),
});
expect(screen.getByText('Wishlist')).toBeInTheDocument();
expect(screen.getAllByText('Rome 2026')).toHaveLength(1);
});
});
@@ -0,0 +1,141 @@
import type { PlacesLibraryDuplicate, PlacesLibraryDuplicateSide } from '@trek/shared';
import { Bookmark, Check, Loader2, Luggage, MapPin } from 'lucide-react';
import React from 'react';
import type { TranslationFn } from '../../types';
import { originName } from './originName';
const LOOK = {
dialog: {
card: 'rounded-xl border border-edge-faint bg-surface-secondary p-3',
side: 'flex min-w-0 flex-col gap-1.5 rounded-lg bg-surface-card p-2.5',
name: 'text-body font-semibold text-content',
sub: 'text-caption text-content-faint',
diff: 'rounded bg-warning-soft px-1 text-content',
chip: 'inline-flex max-w-full items-center gap-1 rounded-full border border-edge-faint px-2 py-0.5 text-caption text-content-muted',
keep: 'inline-flex items-center justify-center gap-1.5 rounded-lg border border-edge-faint bg-surface-secondary px-2.5 py-1.5 text-caption font-semibold text-content hover:bg-surface-hover disabled:opacity-50',
reason: 'text-caption font-semibold text-content-muted',
note: 'text-caption text-content-faint',
link: 'text-caption font-semibold text-content-muted hover:text-content disabled:opacity-50',
},
sheet: {
card: 'rounded-2xl border border-m-rowbr bg-m-sheet p-3',
side: 'flex min-w-0 flex-col gap-1.5 rounded-xl bg-m-sheetop p-2.5',
name: 'text-body font-bold text-m-ink',
sub: 'text-caption text-m-muted',
diff: 'rounded bg-warning-soft px-1 text-m-ink',
chip: 'inline-flex max-w-full items-center gap-1 rounded-full border border-m-rowbr bg-m-ic px-2 py-0.5 text-caption text-m-muted',
keep: 'inline-flex items-center justify-center gap-1.5 rounded-full border border-m-rowbr bg-m-ic px-2.5 py-[7px] text-caption font-semibold text-m-ink disabled:opacity-50',
reason: 'text-caption font-semibold text-m-muted',
note: 'text-caption text-m-faint',
link: 'text-caption font-semibold text-m-muted disabled:opacity-50',
},
} as const;
type Look = (typeof LOOK)[keyof typeof LOOK];
function Side({
side,
differing,
canMerge,
busy,
onKeep,
look,
t,
}: {
side: PlacesLibraryDuplicateSide;
differing: readonly string[];
canMerge: boolean;
busy: boolean;
onKeep: () => void;
look: Look;
t: TranslationFn;
}) {
const mark = (field: string, text: React.ReactNode) =>
differing.includes(field) ? <span className={look.diff}>{text}</span> : text;
return (
<div className={look.side}>
<span dir="auto" className={`${look.name} truncate`}>
{mark('name', side.name)}
</span>
{(side.address || differing.includes('address')) && (
<span dir="auto" className={`${look.sub} flex items-start gap-1`}>
<MapPin size={11} className="mt-0.5 flex-none" />{' '}
{mark('address', side.address || t('collections.duplicates.noAddress'))}
</span>
)}
<span className="flex flex-wrap gap-1">
{side.origins.map((o) => (
<span key={o.kind === 'trip' ? `t${o.place_id}` : `l${o.collection_place_id}`} className={look.chip}>
{o.kind === 'trip' ? (
<Luggage size={10} className="flex-none" />
) : (
<Bookmark size={10} className="flex-none" />
)}
<span className="truncate">{originName(o)}</span>
</span>
))}
</span>
{canMerge && (
<button type="button" onClick={onKeep} disabled={busy} className={`mt-auto ${look.keep}`}>
{busy ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />}{' '}
{t('collections.duplicates.keepThis')}
</button>
)}
</div>
);
}
/**
* One suggested pair (PLC-13): both sides with what tells them apart marked, why they
* look alike, a "keep this one" under each side and "not the same place" below. The
* dialog and the phone sheet show the same card in their own colours.
*/
export default function DuplicatePairCard({
pair,
busy,
onMerge,
onDismiss,
variant,
t,
}: {
pair: PlacesLibraryDuplicate;
busy: boolean;
onMerge: (leading: 'a' | 'b') => void;
onDismiss: () => void;
variant: 'dialog' | 'sheet';
t: TranslationFn;
}): React.ReactElement {
const look = LOOK[variant];
const reason = pair.reasons.includes('provider_id')
? t('collections.duplicates.sameProvider')
: t('collections.duplicates.sameNameNearby');
return (
<article className={`flex flex-col gap-2.5 ${look.card}`}>
<span className={look.reason}>{reason}</span>
<div className="grid grid-cols-2 gap-2">
<Side
side={pair.a}
differing={pair.differing}
canMerge={pair.can_merge}
busy={busy}
onKeep={() => onMerge('a')}
look={look}
t={t}
/>
<Side
side={pair.b}
differing={pair.differing}
canMerge={pair.can_merge}
busy={busy}
onKeep={() => onMerge('b')}
look={look}
t={t}
/>
</div>
{!pair.can_merge && <span className={look.note}>{t('collections.duplicates.cannotMerge')}</span>}
<button type="button" onClick={onDismiss} disabled={busy} className={`self-start ${look.link}`}>
{t('collections.duplicates.notSame')}
</button>
</article>
);
}
@@ -0,0 +1,119 @@
// FE-COMP-DUPEDIALOG-001 to FE-COMP-DUPEDIALOG-011
import userEvent from '@testing-library/user-event';
import React from 'react';
import { duplicatePair, duplicateSide } from '../../../tests/helpers/placesLibrary';
import { render, screen } from '../../../tests/helpers/render';
import { useTranslation } from '../../i18n/TranslationContext';
import DuplicatesDialog from './DuplicatesDialog';
import { pairKey } from './usePlaceDuplicates';
type Props = Omit<React.ComponentProps<typeof DuplicatesDialog>, 't'>;
const PAIR = duplicatePair();
const OTHER = duplicatePair({
a: duplicateSide({ key: 'trip:7', name: 'Pantheon' }),
b: duplicateSide({ key: 'trip:8', name: 'Pantheon Rome' }),
});
function Harness(props: Props): React.ReactElement {
const { t } = useTranslation();
return <DuplicatesDialog {...props} t={t} />;
}
function setup(over: Partial<Props> = {}) {
const props: Props = {
pairs: [PAIR, OTHER],
hasMore: false,
loading: false,
busy: null,
lastMerge: null,
onMerge: vi.fn(),
onDismiss: vi.fn(),
onUndo: vi.fn(),
onClose: vi.fn(),
...over,
};
const view = render(<Harness {...props} />);
return { ...view, props };
}
describe('DuplicatesDialog', () => {
it('FE-COMP-DUPEDIALOG-001: names itself and explains what keeping a side does', () => {
setup();
expect(screen.getByRole('dialog', { name: 'Possible duplicates' })).toBeInTheDocument();
expect(screen.getByText(/Keep one side to group both as one place of yours/)).toBeInTheDocument();
});
it('FE-COMP-DUPEDIALOG-002: lists a card per pair', () => {
setup();
expect(screen.getAllByRole('article')).toHaveLength(2);
expect(screen.getByText('Colosseum')).toBeInTheDocument();
expect(screen.getByText('Pantheon Rome')).toBeInTheDocument();
});
it('FE-COMP-DUPEDIALOG-003: with no pairs it says there are none', () => {
setup({ pairs: [] });
expect(screen.getByText('No possible duplicates.')).toBeInTheDocument();
expect(screen.queryByRole('article')).not.toBeInTheDocument();
expect(screen.queryByText(/Keep one side/)).not.toBeInTheDocument();
});
it('FE-COMP-DUPEDIALOG-004: while loading with nothing yet it shows a spinner instead of the empty note', () => {
setup({ pairs: [], loading: true });
expect(screen.queryByText('No possible duplicates.')).not.toBeInTheDocument();
expect(document.querySelector('.animate-spin')).not.toBeNull();
});
it('FE-COMP-DUPEDIALOG-005: pairs already loaded stay visible while it reloads', () => {
setup({ loading: true });
expect(screen.getAllByRole('article')).toHaveLength(2);
});
it('FE-COMP-DUPEDIALOG-006: tells that more pairs show up once these are done', () => {
const more = setup({ hasMore: true });
expect(screen.getByText('More show up once you are through these.')).toBeInTheDocument();
more.unmount();
setup({ hasMore: false });
expect(screen.queryByText('More show up once you are through these.')).not.toBeInTheDocument();
});
it('FE-COMP-DUPEDIALOG-007: keeping a side and "not the same place" report the pair they belong to', async () => {
const user = userEvent.setup();
const { props } = setup();
await user.click(screen.getAllByRole('button', { name: /Keep this one/ })[1]);
expect(props.onMerge).toHaveBeenCalledWith(PAIR, 'b');
await user.click(screen.getAllByRole('button', { name: 'Not the same place' })[1]);
expect(props.onDismiss).toHaveBeenCalledWith(OTHER);
});
it('FE-COMP-DUPEDIALOG-008: only the pair being worked on is busy', () => {
setup({ busy: pairKey(PAIR) });
const [first, second] = screen.getAllByRole('article');
for (const button of first.querySelectorAll('button')) expect(button).toBeDisabled();
for (const button of second.querySelectorAll('button')) expect(button).toBeEnabled();
});
it('FE-COMP-DUPEDIALOG-009: the undo button appears only after a merge and takes it back', async () => {
const user = userEvent.setup();
const none = setup();
expect(screen.queryByRole('button', { name: /Separate/ })).not.toBeInTheDocument();
none.unmount();
const { props } = setup({ lastMerge: { id: 3, name: 'Colosseum' } });
await user.click(screen.getByRole('button', { name: 'Separate Colosseum again' }));
expect(props.onUndo).toHaveBeenCalledTimes(1);
});
it('FE-COMP-DUPEDIALOG-010: the undo button is disabled while the undo runs', () => {
setup({ lastMerge: { id: 3, name: 'Colosseum' }, busy: 'undo' });
expect(screen.getByRole('button', { name: 'Separate Colosseum again' })).toBeDisabled();
});
it('FE-COMP-DUPEDIALOG-011: Close closes the dialog', async () => {
const user = userEvent.setup();
const { props } = setup();
const closes = screen.getAllByRole('button', { name: 'Close' });
await user.click(closes[closes.length - 1]);
expect(props.onClose).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,103 @@
import type { PlacesLibraryDuplicate } from '@trek/shared';
import { CopyCheck, Loader2, Undo2 } from 'lucide-react';
import React, { useId } from 'react';
import type { TranslationFn } from '../../types';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
NEUTRAL_TINT,
} from '../shared/DialogShell';
import DuplicatePairCard from './DuplicatePairCard';
import { pairKey } from './usePlaceDuplicates';
interface DuplicatesDialogProps {
pairs: PlacesLibraryDuplicate[];
hasMore: boolean;
loading: boolean;
busy: string | null;
lastMerge: { id: number; name: string } | null;
onMerge: (pair: PlacesLibraryDuplicate, leading: 'a' | 'b') => void;
onDismiss: (pair: PlacesLibraryDuplicate) => void;
onUndo: () => void;
onClose: () => void;
t: TranslationFn;
}
/** The places that look like one another (PLC-13), to merge or to set apart for good. */
export default function DuplicatesDialog({
pairs,
hasMore,
loading,
busy,
lastMerge,
onMerge,
onDismiss,
onUndo,
onClose,
t,
}: DuplicatesDialogProps): React.ReactElement {
const labelId = useId();
return (
<DialogShell
onClose={onClose}
labelledBy={labelId}
width="detail"
header={
<DialogHeader
tile={
<DialogTile>
<CopyCheck size={20} strokeWidth={1.9} className="text-content-muted" />
</DialogTile>
}
tint={NEUTRAL_TINT}
labelId={labelId}
onClose={onClose}
title={t('collections.duplicates.title')}
/>
}
footer={
<DialogFooter>
{lastMerge && (
<DialogButton onClick={onUndo} disabled={busy === 'undo'} icon={<Undo2 size={14} />}>
{t('collections.duplicates.undo', { name: lastMerge.name })}
</DialogButton>
)}
<FooterSpacer />
<DialogButton onClick={onClose}>{t('common.close')}</DialogButton>
</DialogFooter>
}
>
{loading && pairs.length === 0 ? (
<div className="flex justify-center py-10 text-content-faint">
<Loader2 size={20} className="animate-spin" />
</div>
) : pairs.length === 0 ? (
<p className="m-0 rounded-xl bg-surface-secondary px-4 py-8 text-center text-body text-content-faint">
{t('collections.duplicates.none')}
</p>
) : (
<div className="flex flex-col gap-2.5">
<p className="m-0 text-caption leading-normal text-content-muted">{t('collections.duplicates.sub')}</p>
{pairs.map((pair) => (
<DuplicatePairCard
key={pairKey(pair)}
pair={pair}
busy={busy === pairKey(pair)}
onMerge={(leading) => onMerge(pair, leading)}
onDismiss={() => onDismiss(pair)}
variant="dialog"
t={t}
/>
))}
{hasMore && (
<p className="m-0 text-center text-caption text-content-faint">{t('collections.duplicates.more')}</p>
)}
</div>
)}
</DialogShell>
);
}
@@ -43,7 +43,9 @@ export default function FilterDropdown({
<div className="col-filter" ref={ref}>
<button
type="button"
className={`col-filter-btn${open ? 'open' : ''}${cur.key === options[0]?.key ? 'is-default' : ''}`}
className={['col-filter-btn', open && 'open', cur.key === options[0]?.key && 'is-default']
.filter(Boolean)
.join(' ')}
onClick={() => setOpen((o) => !o)}
aria-haspopup="listbox"
aria-expanded={open}
@@ -61,7 +63,7 @@ export default function FilterDropdown({
type="button"
role="option"
aria-selected={o.key === current}
className={`col-filter-opt${o.key === current ? 'on' : ''}`}
className={['col-filter-opt', o.key === current && 'on'].filter(Boolean).join(' ')}
onClick={() => {
onSelect(o.key);
setOpen(false);
@@ -1,5 +1,5 @@
import type { CollectionStatus, PlacesLibraryCounts, PlacesLibrarySort } from '@trek/shared';
import { ArrowDownUp, Bookmark, Globe2, Layers, Luggage, Tag } from 'lucide-react';
import { ArrowDownUp, Bookmark, CopyCheck, Globe2, Layers, Luggage, Tag } from 'lucide-react';
import React from 'react';
import { STATUS_META, STATUS_ORDER } from '../../pages/collections/collectionsModel';
import type { Category, TranslationFn } from '../../types';
@@ -18,6 +18,10 @@ interface LibraryFilterBarProps {
onCategory: (id: number | 'all') => void;
sort: PlacesLibrarySort;
onSort: (sort: PlacesLibrarySort) => void;
/** How many pairs look like one place (PLC-13); the button shows while there are any. */
duplicates?: number;
duplicatesMore?: boolean;
onDuplicates?: () => void;
t: TranslationFn;
}
@@ -37,6 +41,9 @@ export default function LibraryFilterBar({
onCategory,
sort,
onSort,
duplicates = 0,
duplicatesMore = false,
onDuplicates,
t,
}: LibraryFilterBarProps): React.ReactElement {
const kindOpts: FilterOption[] = [
@@ -94,6 +101,20 @@ export default function LibraryFilterBar({
onSelect={(k) => onSort(k as PlacesLibrarySort)}
lead={<ArrowDownUp size={13} />}
/>
{duplicates > 0 && onDuplicates && (
<button
type="button"
onClick={onDuplicates}
className="col-filter-btn ms-auto"
title={t('collections.duplicates.title')}
>
<CopyCheck size={13} />
<span className="col-filter-lbl">
{t('collections.duplicates.button', { count: duplicates })}
{duplicatesMore ? '+' : ''}
</span>
</button>
)}
</div>
);
}
@@ -4,7 +4,8 @@ import React from 'react';
import { listOrigin, tripOrigin } from '../../../tests/helpers/placesLibrary';
import { render, screen } from '../../../tests/helpers/render';
import { useTranslation } from '../../i18n/TranslationContext';
import LibraryOrigins, { originName } from './LibraryOrigins';
import LibraryOrigins from './LibraryOrigins';
import { originName } from './originName';
type Props = Omit<React.ComponentProps<typeof LibraryOrigins>, 't'>;
@@ -2,15 +2,11 @@ import type { PlacesLibraryOrigin } from '@trek/shared';
import { Bookmark, Luggage } from 'lucide-react';
import React from 'react';
import type { TranslationFn } from '../../types';
import { originName } from './originName';
/** How many origins a row names before it counts the rest. */
const SHOWN = 2;
/** The name an origin goes by: the list's or the trip's. */
export function originName(origin: PlacesLibraryOrigin): string {
return origin.kind === 'list' ? origin.collection_name : origin.trip_title;
}
/**
* Where an entry of "All places" comes from (PLC-07): a chip per list and per trip,
* trips first because they are what was actually planned, the rest counted.
@@ -1,4 +1,4 @@
import type { PlacesLibraryDetail, PlacesLibraryDetailResponse, PlacesLibraryOrigin } from '@trek/shared';
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import {
Bookmark,
BookmarkPlus,
@@ -15,21 +15,26 @@ import {
Ticket,
X,
} from 'lucide-react';
import React, { useRef, useState } from 'react';
import React, { createElement, useRef, useState } from 'react';
import type { TranslationFn } from '../../types';
import { entityGradient } from '../../utils/gradients';
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation';
import { getCategoryIcon } from '../shared/categoryIcons';
import { NavigationMenu } from '../shared/NavigationMenu';
import { dockStyle, type DockRect } from './detailDock';
import { tripLine } from './libraryDates';
import { originName } from './LibraryOrigins';
import {
originPairs,
type ListDetail,
type ListOrigin,
type ListPair,
type TripDetail,
type TripOrigin,
type TripPair,
} from './libraryPairs';
import { originName } from './originName';
import StatusBadge from './StatusBadge';
type TripOrigin = Extract<PlacesLibraryOrigin, { kind: 'trip' }>;
type ListOrigin = Extract<PlacesLibraryOrigin, { kind: 'list' }>;
type TripDetail = Extract<PlacesLibraryDetail, { kind: 'trip' }>;
type ListDetail = Extract<PlacesLibraryDetail, { kind: 'list' }>;
interface LibraryPlaceDetailProps {
data: PlacesLibraryDetailResponse | null;
loading: boolean;
@@ -37,7 +42,7 @@ interface LibraryPlaceDetailProps {
cover: string | null;
language: string;
/** Where the sheet docks: over the list column in the split, centred otherwise. */
anchorRect?: { left: number; width: number } | null;
anchorRect?: DockRect | null;
onClose: () => void;
onOpenList: (collectionId: number, collectionPlaceId: number) => void;
onOpenTrip: (tripId: number, placeId: number) => void;
@@ -178,6 +183,181 @@ function ListCard({
);
}
type Entry = NonNullable<PlacesLibraryDetailResponse['entry']>;
/** The cover band: the picture or a gradient, the category, the close button and the name. */
function DetailCover({
entry,
cover,
onClose,
t,
}: {
entry: Entry | null;
cover: string | null;
onClose: () => void;
t: TranslationFn;
}) {
const gradient = entry ? entry.key.length + entry.name.length : 0;
return (
<div className="col-detail-cover" style={cover ? undefined : { backgroundImage: entityGradient(gradient) }}>
{cover && <img src={cover} alt="" />}
<div className="col-detail-cover-scrim" />
<div className="absolute end-[12px] start-[14px] top-[12px] z-[2] flex items-center gap-[8px]">
{entry?.category && (
<span
className="col-detail-cover-cat min-w-0"
style={{ ['--cat' as string]: entry.category.color || 'var(--accent)' }}
>
{createElement(getCategoryIcon(entry.category.icon ?? undefined), { size: 12, className: 'flex-none' })}
<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>
</div>
)}
</div>
);
}
/** Where the place is, or that it has no position yet. */
function DetailMeta({ entry, t }: { entry: Entry; t: TranslationFn }) {
const unplaced = entry.lat == null || entry.lng == null;
if (!entry.address && !unplaced) return null;
return (
<div className="col-detail-meta">
{entry.address && (
<span className="col-detail-addr">
<MapPin size={13} /> {entry.address}
</span>
)}
{unplaced && (
<span className="col-detail-addr">
<MapPinOff size={13} className="text-warning" /> {t('places.noCoordinates')}
</span>
)}
</div>
);
}
/** The body: where it is, its description, then every trip and every list it sits in. */
function DetailBody({
entry,
trips,
lists,
description,
language,
onOpenTrip,
onOpenList,
t,
}: {
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;
}) {
return (
<>
<DetailMeta entry={entry} t={t} />
{description && <div className="col-detail-md whitespace-pre-wrap">{description}</div>}
{trips.length > 0 && (
<section className="col-detail-field">
<div className="col-detail-label">
<Luggage size={12} /> {t('collections.library.inTrips')}
</div>
{trips.map(({ origin, detail }) => (
<TripCard
key={origin.place_id}
origin={origin}
detail={detail}
entryName={entry.name}
language={language}
onOpen={() => onOpenTrip(origin.trip_id, origin.place_id)}
t={t}
/>
))}
</section>
)}
{lists.length > 0 && (
<section className="col-detail-field">
<div className="col-detail-label">
<Bookmark size={12} /> {t('collections.library.inLists')}
</div>
{lists.map(({ origin, detail }) => (
<ListCard
key={origin.collection_place_id}
origin={origin}
detail={detail}
entryName={entry.name}
onOpen={() => onOpenList(origin.collection_id, origin.collection_place_id)}
t={t}
/>
))}
</section>
)}
</>
);
}
/** The footer: navigate there, save the trip's place to a list, copy the list's place to a trip. */
function DetailFooter({
entry,
trip,
list,
onSaveToList,
onCopyToTrip,
t,
}: {
entry: Entry;
trip: TripPair | undefined;
list: ListPair | undefined;
onSaveToList: (origin: TripOrigin, detail: TripDetail) => void;
onCopyToTrip: (collectionPlaceId: number) => void;
t: TranslationFn;
}) {
const [navOpen, setNavOpen] = useState(false);
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;
return (
<div className="col-detail-footer">
{targets.length > 0 && (
<>
<button
ref={navRef}
type="button"
className="col-detail-btn"
onClick={() => (single ? openNavigationTarget(single) : setNavOpen((o) => !o))}
>
<Navigation size={14} /> {single ? navigationTargetLabel(single, t) : t('inspector.navigation')}
</button>
{navOpen && <NavigationMenu targets={targets} anchor={navRef.current} onClose={() => setNavOpen(false)} />}
</>
)}
<div className="col-detail-footer-spacer" />
{trip && (
<button type="button" className="col-detail-btn" onClick={() => onSaveToList(trip.origin, trip.detail)}>
<BookmarkPlus size={14} /> {t('inspector.saveToCollection')}
</button>
)}
{list && (
<button type="button" className="col-detail-btn" onClick={() => onCopyToTrip(list.origin.collection_place_id)}>
<Copy size={14} /> {t('collections.copyToTrip')}
</button>
)}
</div>
);
}
/**
* 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
@@ -197,165 +377,45 @@ export default function LibraryPlaceDetail({
onCopyToTrip,
t,
}: LibraryPlaceDetailProps): React.ReactElement {
const [navOpen, setNavOpen] = useState(false);
const navRef = useRef<HTMLButtonElement>(null);
const entry = data?.entry ?? null;
const CatIcon = getCategoryIcon(entry?.category?.icon ?? undefined);
const targets = entry
? getNavigationTargets({ name: entry.name, address: entry.address, lat: entry.lat, lng: entry.lng })
: [];
const pairs =
entry && data
? entry.origins.map((origin, i) => ({ origin, detail: data.details[i] })).filter((p) => p.detail)
: [];
const trips = pairs.filter(
(p): p is { origin: TripOrigin; detail: TripDetail } => p.origin.kind === 'trip' && p.detail.kind === 'trip'
);
const lists = pairs.filter(
(p): p is { origin: ListOrigin; detail: ListDetail } => p.origin.kind === 'list' && p.detail.kind === 'list'
);
const description = pairs.map((p) => p.detail.info.description).find((d) => d?.trim());
const dockStyle = anchorRect
? { left: anchorRect.left, width: anchorRect.width, transform: 'none' as const }
: undefined;
const { trips, lists, description } = originPairs(data);
return (
<div
className={`col-detail${anchorRect ? 'docked' : ''}`}
style={dockStyle}
className={anchorRect ? 'col-detail docked' : 'col-detail'}
style={dockStyle(anchorRect)}
role="dialog"
aria-label={entry?.name ?? t('collections.library.title')}
>
<div
className="col-detail-cover"
style={
cover ? undefined : { backgroundImage: entityGradient(entry ? entry.key.length + entry.name.length : 0) }
}
>
{cover && <img src={cover} alt="" />}
<div className="col-detail-cover-scrim" />
<div className="absolute end-[12px] start-[14px] top-[12px] z-[2] flex items-center gap-[8px]">
{entry?.category && (
<span
className="col-detail-cover-cat min-w-0"
style={{ ['--cat' as string]: entry.category.color || 'var(--accent)' }}
>
<CatIcon size={12} className="flex-none" />
<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>
</div>
)}
</div>
<DetailCover entry={entry} cover={cover} onClose={onClose} t={t} />
<div className="col-detail-body">
{loading && !entry ? (
{loading && !entry && (
<div className="flex justify-center py-6 text-content-faint">
<Loader2 size={20} className="animate-spin" />
</div>
) : (
entry && (
<>
{(entry.address || entry.lat == null || entry.lng == null) && (
<div className="col-detail-meta">
{entry.address && (
<span className="col-detail-addr">
<MapPin size={13} /> {entry.address}
</span>
)}
{(entry.lat == null || entry.lng == null) && (
<span className="col-detail-addr">
<MapPinOff size={13} className="text-warning" /> {t('places.noCoordinates')}
</span>
)}
</div>
)}
{description && <div className="col-detail-md whitespace-pre-wrap">{description}</div>}
{trips.length > 0 && (
<section className="col-detail-field">
<div className="col-detail-label">
<Luggage size={12} /> {t('collections.library.inTrips')}
</div>
{trips.map(({ origin, detail }) => (
<TripCard
key={origin.place_id}
origin={origin}
detail={detail}
entryName={entry.name}
language={language}
onOpen={() => onOpenTrip(origin.trip_id, origin.place_id)}
t={t}
/>
))}
</section>
)}
{lists.length > 0 && (
<section className="col-detail-field">
<div className="col-detail-label">
<Bookmark size={12} /> {t('collections.library.inLists')}
</div>
{lists.map(({ origin, detail }) => (
<ListCard
key={origin.collection_place_id}
origin={origin}
detail={detail}
entryName={entry.name}
onOpen={() => onOpenList(origin.collection_id, origin.collection_place_id)}
t={t}
/>
))}
</section>
)}
</>
)
)}
{entry && (
<DetailBody
entry={entry}
trips={trips}
lists={lists}
description={description}
language={language}
onOpenTrip={onOpenTrip}
onOpenList={onOpenList}
t={t}
/>
)}
</div>
{entry && (
<div className="col-detail-footer">
{targets.length > 0 && (
<>
<button
ref={navRef}
type="button"
className="col-detail-btn"
onClick={() => (targets.length === 1 ? openNavigationTarget(targets[0]) : setNavOpen((o) => !o))}
>
<Navigation size={14} />{' '}
{targets.length === 1 ? navigationTargetLabel(targets[0], t) : t('inspector.navigation')}
</button>
{navOpen && (
<NavigationMenu targets={targets} anchor={navRef.current} onClose={() => setNavOpen(false)} />
)}
</>
)}
<div className="col-detail-footer-spacer" />
{trips[0] && (
<button
type="button"
className="col-detail-btn"
onClick={() => onSaveToList(trips[0].origin, trips[0].detail)}
>
<BookmarkPlus size={14} /> {t('inspector.saveToCollection')}
</button>
)}
{lists[0] && (
<button
type="button"
className="col-detail-btn"
onClick={() => onCopyToTrip(lists[0].origin.collection_place_id)}
>
<Copy size={14} /> {t('collections.copyToTrip')}
</button>
)}
</div>
<DetailFooter
entry={entry}
trip={trips[0]}
list={lists[0]}
onSaveToList={onSaveToList}
onCopyToTrip={onCopyToTrip}
t={t}
/>
)}
</div>
);
@@ -1,4 +1,4 @@
import React, { useId } from 'react'
import React, { createElement, useId } from 'react'
import { ImagePlus, Trash2, Search, Loader2 } from 'lucide-react'
import { DeleteButton, DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, fs } from '../shared/DialogShell'
import { AddRowButton, EditorField, INPUT, TEXTAREA } from '../shared/dialogParts'
@@ -43,7 +43,7 @@ export default function ListEditorModal({ target, onClose, onCreated, onRequestD
// The list's own colour runs through the dialog: the head band, its tile and the cover.
const header = (
<DialogHeader
tile={<DialogTile><TileIcon size={20} strokeWidth={1.9} style={{ color }} /></DialogTile>}
tile={<DialogTile>{createElement(TileIcon, { size: 20, strokeWidth: 1.9, style: { color } })}</DialogTile>}
tint={`color-mix(in srgb, ${color} 12%, transparent)`}
labelId={labelId}
onClose={onClose}
@@ -1,4 +1,4 @@
import React from 'react'
import React, { createElement } from 'react'
import { Plus, Layers, Users, Upload, Globe2 } from 'lucide-react'
import type { Collection } from '@trek/shared'
import type { TranslationFn } from '../../types'
@@ -33,7 +33,7 @@ function ListRow({ list, active, onSelect }: { list: Collection; active: boolean
<div className="col-row">
<button type="button" onClick={() => onSelect(list.id)} className={`col-row-btn${active ? ' on' : ''}`}>
{/* The list's own symbol in its own colour (the default one without a colour). */}
<span className="ico tile list" style={{ ['--list' as string]: list.color || '#6366f1' }}><ListIcon size={15} /></span>
<span className="ico tile list" style={{ ['--list' as string]: list.color || '#6366f1' }}>{createElement(ListIcon, { size: 15 })}</span>
<span className="nm">{list.name}</span>
<span className="ct">{list.place_count ?? 0}</span>
</button>
@@ -38,6 +38,21 @@ vi.mock('./usePlacesLibrary', () => ({
usePlacesLibrary: () => seen.lib,
}));
// The review of possible duplicates has its own tests; here it has none to offer.
vi.mock('./usePlaceDuplicates', () => ({
usePlaceDuplicates: () => ({
pairs: [],
hasMore: false,
loading: false,
busy: null,
lastMerge: null,
merge: vi.fn(),
dismiss: vi.fn(),
undo: vi.fn(),
reload: vi.fn(),
}),
}));
// The map stack does not render in jsdom; the panel's contract is what the view hands it.
vi.mock('./CollectionMapPanel', () => ({
default: (props: MapProps) => {
@@ -11,9 +11,12 @@ import PlaceAvatar from '../shared/PlaceAvatar';
import CategoryBadge from './CategoryBadge';
import CollectionMapPanel from './CollectionMapPanel';
import CopyToTripModal from './CopyToTripModal';
import DuplicatesDialog from './DuplicatesDialog';
import LibraryFilterBar from './LibraryFilterBar';
import LibraryOrigins from './LibraryOrigins';
import LibraryPlaceDetail from './LibraryPlaceDetail';
import { detailDock } from './detailDock';
import { usePlaceDuplicates } from './usePlaceDuplicates';
import { usePlacesLibrary } from './usePlacesLibrary';
interface PlacesLibraryViewProps {
@@ -56,6 +59,111 @@ function toMapPlaces(entries: PlacesLibraryEntry[]) {
return { places, keyOf, idOf };
}
/** The rows of "All places": offline, an error, loading, empty, or the places with "more". */
function LibraryRows({
lib,
idOf,
t,
}: {
lib: ReturnType<typeof usePlacesLibrary>;
idOf: ReadonlyMap<string, number>;
t: TranslationFn;
}): React.ReactElement {
if (lib.offline) return <EmptyState scene="search" title={t('collections.library.offline')} />;
if (lib.error)
return (
<p role="alert" className="m-0 rounded-xl bg-danger-soft px-3 py-2 text-body text-danger">
{lib.error}
</p>
);
if (lib.loading && lib.entries.length === 0)
return (
<div className="col-loading">
<div className="col-spinner" />
</div>
);
if (lib.entries.length === 0) {
return (
<div className="flex flex-col items-center">
<EmptyState
scene={lib.filtered ? 'search' : 'collections'}
title={t(lib.filtered ? 'collections.empty.noMatchTitle' : 'collections.library.emptyTitle')}
className={lib.filtered ? 'pb-4' : undefined}
/>
{lib.filtered && (
<button type="button" onClick={lib.resetFilters} className="col-cta col-cta-ghost">
{t('collections.library.resetFilters')}
</button>
)}
</div>
);
}
return (
<div className="col-listview">
{lib.entries.map((entry) => (
<div
key={entry.key}
role="button"
tabIndex={0}
data-no-press
onClick={() => lib.open(entry.key)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
lib.open(entry.key);
}
}}
className={lib.selectedKey === entry.key ? 'col-lrow sel' : 'col-lrow'}
>
<span className="col-lrow-avatar">
<PlaceAvatar
place={{
id: idOf.get(entry.key) ?? 0,
name: entry.name,
image_url: entry.image_url,
google_place_id: null,
osm_id: null,
lat: entry.lat,
lng: entry.lng,
}}
size={40}
category={
entry.category
? ({ color: entry.category.color ?? undefined, icon: entry.category.icon ?? undefined } as Category)
: null
}
/>
</span>
<div className="li">
<div className="t">
{entry.category?.name && <CategoryBadge category={entry.category} />}
<span className="nm">{entry.name}</span>
</div>
{entry.address && (
<div className="s">
<MapPin size={11} />
<span>{entry.address}</span>
</div>
)}
</div>
<LibraryOrigins origins={entry.origins} t={t} />
</div>
))}
{lib.hasMore && (
<button
type="button"
onClick={() => void lib.loadMore()}
disabled={lib.loadingMore}
className="col-cta col-cta-ghost self-center"
>
{lib.loadingMore && <Loader2 size={15} className="animate-spin" />}{' '}
{t('collections.library.more', { count: lib.total - lib.entries.length })}
</button>
)}
</div>
);
}
/**
* "All places" on the desktop (PLC-07): every place of the user's trips and lists,
* one row each with where it comes from, beside a map of them, with the same filter
@@ -75,6 +183,8 @@ export default function PlacesLibraryView({
t,
}: PlacesLibraryViewProps): React.ReactElement {
const lib = usePlacesLibrary({ active: true, t });
const dup = usePlaceDuplicates({ active: true, onChanged: lib.reload, t });
const [showDup, setShowDup] = useState(false);
const openSave = useSaveToCollectionStore((s) => s.open);
const copyToTrip = useCollectionStore((s) => s.copyToTrip);
const [copyId, setCopyId] = useState<number | null>(null);
@@ -96,105 +206,14 @@ export default function PlacesLibraryView({
onCategory={lib.setCategoryId}
sort={lib.sort}
onSort={lib.setSort}
duplicates={dup.pairs.length}
duplicatesMore={dup.hasMore}
onDuplicates={() => setShowDup(true)}
t={t}
/>
);
let rows: React.ReactNode;
if (lib.offline) rows = <EmptyState scene="search" title={t('collections.library.offline')} />;
else if (lib.error)
rows = (
<p role="alert" className="m-0 rounded-xl bg-danger-soft px-3 py-2 text-body text-danger">
{lib.error}
</p>
);
else if (lib.loading && lib.entries.length === 0)
rows = (
<div className="col-loading">
<div className="col-spinner" />
</div>
);
else if (lib.entries.length === 0) {
rows = (
<div className="flex flex-col items-center">
<EmptyState
scene={lib.filtered ? 'search' : 'collections'}
title={t(lib.filtered ? 'collections.empty.noMatchTitle' : 'collections.library.emptyTitle')}
className={lib.filtered ? 'pb-4' : undefined}
/>
{lib.filtered && (
<button type="button" onClick={lib.resetFilters} className="col-cta col-cta-ghost">
{t('collections.library.resetFilters')}
</button>
)}
</div>
);
} else {
rows = (
<div className="col-listview">
{lib.entries.map((entry) => (
<div
key={entry.key}
role="button"
tabIndex={0}
data-no-press
onClick={() => lib.open(entry.key)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
lib.open(entry.key);
}
}}
className={`col-lrow${lib.selectedKey === entry.key ? 'sel' : ''}`}
>
<span className="col-lrow-avatar">
<PlaceAvatar
place={{
id: map.idOf.get(entry.key) ?? 0,
name: entry.name,
image_url: entry.image_url,
google_place_id: null,
osm_id: null,
lat: entry.lat,
lng: entry.lng,
}}
size={40}
category={
entry.category
? ({ color: entry.category.color ?? undefined, icon: entry.category.icon ?? undefined } as Category)
: null
}
/>
</span>
<div className="li">
<div className="t">
{entry.category?.name && <CategoryBadge category={entry.category} />}
<span className="nm">{entry.name}</span>
</div>
{entry.address && (
<div className="s">
<MapPin size={11} />
<span>{entry.address}</span>
</div>
)}
</div>
<LibraryOrigins origins={entry.origins} t={t} />
</div>
))}
{lib.hasMore && (
<button
type="button"
onClick={() => void lib.loadMore()}
disabled={lib.loadingMore}
className="col-cta col-cta-ghost self-center"
>
{lib.loadingMore && <Loader2 size={15} className="animate-spin" />}{' '}
{t('collections.library.more', { count: lib.total - lib.entries.length })}
</button>
)}
</div>
);
}
const rows = <LibraryRows lib={lib} idOf={map.idOf} t={t} />;
// The map carries the search on a wide screen, as it does for a list; without it the row above the places does.
const listColumn = (
@@ -218,18 +237,12 @@ export default function PlacesLibraryView({
</>
);
const anchor = !split
? null
: view === 'map'
? mapCol.rect
? { left: mapCol.rect.left + 12, width: Math.min(420, mapCol.rect.width - 24) }
: null // rtl-lint-disable: a measured viewport position, like the list dock
: listCol.rect;
const anchor = detailDock(split, view, mapCol.rect, listCol.rect);
return (
<>
{split ? (
<div className={`col-split${view === 'map' ? 'map-full' : ''}`}>
<div className={view === 'map' ? 'col-split map-full' : 'col-split'}>
<div className="col-split-list" ref={listCol.ref}>
{listColumn}
</div>
@@ -291,6 +304,21 @@ export default function PlacesLibraryView({
/>
)}
{showDup && (
<DuplicatesDialog
pairs={dup.pairs}
hasMore={dup.hasMore}
loading={dup.loading}
busy={dup.busy}
lastMerge={dup.lastMerge}
onMerge={(pair, leading) => void dup.merge(pair, leading)}
onDismiss={(pair) => void dup.dismiss(pair)}
onUndo={() => void dup.undo()}
onClose={() => setShowDup(false)}
t={t}
/>
)}
{copyId != null && (
<CopyToTripModal
isOpen
@@ -0,0 +1,50 @@
// FE-COMP-DETAILDOCK-001 to FE-COMP-DETAILDOCK-009
import { detailDock, dockStyle } from './detailDock';
const MAP = { left: 300, width: 900 };
const LIST = { left: 0, width: 360 };
describe('detailDock', () => {
it('FE-COMP-DETAILDOCK-001: without a split the sheet is centred', () => {
expect(detailDock(false, 'map', MAP, LIST)).toBeNull();
expect(detailDock(false, 'list', MAP, LIST)).toBeNull();
});
it('FE-COMP-DETAILDOCK-002: in the list view it docks over the list column', () => {
expect(detailDock(true, 'list', MAP, LIST)).toBe(LIST);
});
it('FE-COMP-DETAILDOCK-003: the list view with no measured column has no dock', () => {
expect(detailDock(true, 'list', MAP, null)).toBeNull();
expect(detailDock(true, 'list', MAP, undefined)).toBeNull();
});
it('FE-COMP-DETAILDOCK-004: any view other than the map counts as the list view', () => {
expect(detailDock(true, 'grid', MAP, LIST)).toBe(LIST);
});
it('FE-COMP-DETAILDOCK-005: on the map it docks on the map start edge, inset by 12 and capped at 420 wide', () => {
expect(detailDock(true, 'map', MAP, LIST)).toEqual({ left: 312, width: 420 });
});
it('FE-COMP-DETAILDOCK-006: a map narrower than the cap leaves 12 on each side', () => {
expect(detailDock(true, 'map', { left: 10, width: 300 }, LIST)).toEqual({ left: 22, width: 276 });
});
it('FE-COMP-DETAILDOCK-007: a map exactly at the cap plus margins keeps 420', () => {
expect(detailDock(true, 'map', { left: 0, width: 444 }, LIST)).toEqual({ left: 12, width: 420 });
});
it('FE-COMP-DETAILDOCK-008: the map view with no measured map has no dock', () => {
expect(detailDock(true, 'map', null, LIST)).toBeNull();
expect(detailDock(true, 'map', undefined, LIST)).toBeNull();
});
});
describe('dockStyle', () => {
it('FE-COMP-DETAILDOCK-009: turns a column into a style without the centring transform, nothing when centred', () => {
expect(dockStyle({ left: 12, width: 420 })).toEqual({ left: 12, width: 420, transform: 'none' });
expect(dockStyle(null)).toBeUndefined();
expect(dockStyle(undefined)).toBeUndefined();
});
});
@@ -0,0 +1,27 @@
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
}
@@ -20,7 +20,14 @@ export function tripRange(
): string | null {
const a = asDate(start);
const b = asDate(end);
if (a && b) return new Intl.DateTimeFormat(language, SHORT).formatRange(a, b);
if (a && b) {
// ES2020's lib does not know formatRange yet; every browser TREK runs in has it.
const range = new Intl.DateTimeFormat(language, SHORT) as Intl.DateTimeFormat & {
formatRange?: (from: Date, to: Date) => string;
};
if (range.formatRange) return range.formatRange(a, b);
return `${range.format(a)} – ${range.format(b)}`;
}
const one = a ?? b;
return one ? new Intl.DateTimeFormat(language, SHORT).format(one) : null;
}
@@ -0,0 +1,74 @@
// FE-COMP-LIBPAIRS-001 to FE-COMP-LIBPAIRS-008
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import {
bothOrigins,
libraryDetail,
libraryEntry,
libraryInfo,
listDetail,
listOrigin,
tripDetail,
tripOrigin,
} from '../../../tests/helpers/placesLibrary';
import { originPairs } from './libraryPairs';
describe('originPairs', () => {
it('FE-COMP-LIBPAIRS-001: nothing open gives nothing', () => {
expect(originPairs(null)).toEqual({ trips: [], lists: [], description: undefined });
});
it('FE-COMP-LIBPAIRS-002: a response with no entry gives nothing', () => {
const data = { entry: null, details: [] } as unknown as PlacesLibraryDetailResponse;
expect(originPairs(data)).toEqual({ trips: [], lists: [], description: undefined });
});
it('FE-COMP-LIBPAIRS-003: splits the origins into trips and lists, each beside its detail', () => {
const data = bothOrigins();
const { trips, lists } = originPairs(data);
expect(trips).toEqual([{ origin: data.entry?.origins[0], detail: data.details[0] }]);
expect(lists).toEqual([{ origin: data.entry?.origins[1], detail: data.details[1] }]);
});
it('FE-COMP-LIBPAIRS-004: keeps several of one kind in the order of the origins', () => {
const entry = libraryEntry({
origins: [tripOrigin({ place_id: 1 }), listOrigin({ collection_place_id: 20 }), tripOrigin({ place_id: 2 })],
});
const data = libraryDetail(entry, [
tripDetail({ place_id: 1 }),
listDetail({ collection_place_id: 20 }),
tripDetail({ place_id: 2 }),
]);
const { trips, lists } = originPairs(data);
expect(trips.map((p) => p.origin.place_id)).toEqual([1, 2]);
expect(lists.map((p) => p.origin.collection_place_id)).toEqual([20]);
});
it('FE-COMP-LIBPAIRS-005: an origin without a detail is left out', () => {
const entry = libraryEntry({ origins: [tripOrigin(), listOrigin()] });
const { trips, lists } = originPairs(libraryDetail(entry, [tripDetail()]));
expect(trips).toHaveLength(1);
expect(lists).toEqual([]);
});
it('FE-COMP-LIBPAIRS-006: an origin whose detail is of the other kind is left out', () => {
const entry = libraryEntry({ origins: [tripOrigin()] });
const { trips, lists } = originPairs(libraryDetail(entry, [listDetail()]));
expect(trips).toEqual([]);
expect(lists).toEqual([]);
});
it('FE-COMP-LIBPAIRS-007: the description is the first one that is not empty or blank', () => {
const entry = libraryEntry({ origins: [tripOrigin(), listOrigin(), listOrigin({ collection_place_id: 901 })] });
const data = libraryDetail(entry, [
tripDetail({ info: libraryInfo({ description: ' ' }) }),
listDetail({ info: libraryInfo({ description: 'Ancient arena' }) }),
listDetail({ collection_place_id: 901, info: libraryInfo({ description: 'Another text' }) }),
]);
expect(originPairs(data).description).toBe('Ancient arena');
});
it('FE-COMP-LIBPAIRS-008: no description anywhere leaves it undefined', () => {
expect(originPairs(bothOrigins()).description).toBeUndefined();
});
});
@@ -0,0 +1,28 @@
import type { PlacesLibraryDetail, PlacesLibraryDetailResponse, PlacesLibraryOrigin } from '@trek/shared';
export type TripOrigin = Extract<PlacesLibraryOrigin, { kind: 'trip' }>;
export type ListOrigin = Extract<PlacesLibraryOrigin, { kind: 'list' }>;
export type TripDetail = Extract<PlacesLibraryDetail, { kind: 'trip' }>;
export type ListDetail = Extract<PlacesLibraryDetail, { kind: 'list' }>;
export type TripPair = { origin: TripOrigin; detail: TripDetail };
export type ListPair = { origin: ListOrigin; detail: ListDetail };
/**
* An open entry's origins beside what each keeps of the place, split into its trips
* and its lists, and the first description any of them has. The desktop sheet and the
* phone sheet both read the entry this way.
*/
export function originPairs(data: PlacesLibraryDetailResponse | null): {
trips: TripPair[];
lists: ListPair[];
description: string | undefined;
} {
const entry = data?.entry ?? null;
if (!entry || !data) return { trips: [], lists: [], description: undefined };
const pairs = entry.origins.map((origin, i) => ({ origin, detail: data.details[i] })).filter((p) => p.detail);
return {
trips: pairs.filter((p): p is TripPair => p.origin.kind === 'trip' && p.detail.kind === 'trip'),
lists: pairs.filter((p): p is ListPair => p.origin.kind === 'list' && p.detail.kind === 'list'),
description: pairs.map((p) => p.detail.info.description).find((d) => d?.trim()),
};
}
@@ -0,0 +1,13 @@
// FE-COMP-ORIGINNAME-001 to FE-COMP-ORIGINNAME-002
import { listOrigin, tripOrigin } from '../../../tests/helpers/placesLibrary';
import { originName } from './originName';
describe('originName', () => {
it('FE-COMP-ORIGINNAME-001: a saved place goes by its list name', () => {
expect(originName(listOrigin({ collection_name: 'Favourites' }))).toBe('Favourites');
});
it('FE-COMP-ORIGINNAME-002: a trip place goes by its trip title', () => {
expect(originName(tripOrigin({ trip_title: 'Rome 2026' }))).toBe('Rome 2026');
});
});
@@ -0,0 +1,6 @@
import type { PlacesLibraryOrigin } from '@trek/shared';
/** The name an origin goes by: the list's or the trip's. */
export function originName(origin: PlacesLibraryOrigin): string {
return origin.kind === 'list' ? origin.collection_name : origin.trip_title;
}
@@ -0,0 +1,285 @@
// FE-COMP-PLACEDUPES-001 to FE-COMP-PLACEDUPES-019: the logic behind the duplicates dialog and sheet.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { PlacesLibraryDuplicate } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { duplicatePair, duplicateSide } from '../../../tests/helpers/placesLibrary';
import { OnlineOnlyError } from '../../repo/onlineOnly';
import { placeIdentitiesRepo } from '../../repo/placeIdentitiesRepo';
import { pairKey, usePlaceDuplicates } from './usePlaceDuplicates';
vi.mock('../../repo/placeIdentitiesRepo', () => ({
placeIdentitiesRepo: {
duplicates: vi.fn(),
merge: vi.fn(),
dismiss: vi.fn(),
undoMerge: vi.fn(),
},
}));
const duplicates = vi.mocked(placeIdentitiesRepo.duplicates);
const merge = vi.mocked(placeIdentitiesRepo.merge);
const dismiss = vi.mocked(placeIdentitiesRepo.dismiss);
const undoMerge = vi.mocked(placeIdentitiesRepo.undoMerge);
// A stable function: the hook lists it in an effect's dependencies.
const t = (key: string) => key;
const PAIR = duplicatePair();
const OTHER_PAIR = duplicatePair({
a: duplicateSide({ key: 'trip:7', name: 'Pantheon' }),
b: duplicateSide({ key: 'trip:8', name: 'Pantheon Rome' }),
});
let addToast: ReturnType<typeof vi.fn>;
function page(pairs: PlacesLibraryDuplicate[], next_cursor: string | null = null) {
return { duplicates: pairs, next_cursor };
}
function setup(active = true) {
const onChanged = vi.fn();
const hook = renderHook((p: { active: boolean }) => usePlaceDuplicates({ active: p.active, onChanged, t }), {
initialProps: { active },
});
return { ...hook, onChanged };
}
/** Loads the hook with `pairs` and waits until it has settled. */
async function loaded(pairs: PlacesLibraryDuplicate[] = [PAIR, OTHER_PAIR], next: string | null = null) {
duplicates.mockResolvedValue(page(pairs, next));
const hook = setup();
await waitFor(() => expect(hook.result.current.loading).toBe(false));
return hook;
}
beforeEach(() => {
vi.clearAllMocks();
addToast = vi.fn();
window.__addToast = addToast as unknown as typeof window.__addToast;
});
afterEach(() => {
delete window.__addToast;
});
describe('pairKey', () => {
it('FE-COMP-PLACEDUPES-001: names a pair by its two keys, the same either way round', () => {
const swapped = { a: PAIR.b, b: PAIR.a };
expect(pairKey(PAIR)).toBe('list:900|trip:42');
expect(pairKey(swapped)).toBe(pairKey(PAIR));
expect(pairKey(OTHER_PAIR)).not.toBe(pairKey(PAIR));
});
});
describe('usePlaceDuplicates', () => {
it('FE-COMP-PLACEDUPES-002: loads the suggested pairs and is loading until they arrive', async () => {
duplicates.mockResolvedValue(page([PAIR, OTHER_PAIR]));
const { result } = setup();
expect(result.current.loading).toBe(true);
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.pairs).toEqual([PAIR, OTHER_PAIR]);
expect(result.current.hasMore).toBe(false);
expect(result.current.busy).toBeNull();
expect(result.current.lastMerge).toBeNull();
expect(duplicates).toHaveBeenCalledWith({}, expect.any(AbortSignal));
});
it('FE-COMP-PLACEDUPES-003: a next cursor means more pairs are waiting', async () => {
const { result } = await loaded([PAIR], 'cursor-2');
expect(result.current.hasMore).toBe(true);
});
it('FE-COMP-PLACEDUPES-004: while inactive nothing loads and nothing is loading', () => {
const { result } = setup(false);
expect(duplicates).not.toHaveBeenCalled();
expect(result.current.loading).toBe(false);
expect(result.current.pairs).toEqual([]);
});
it('FE-COMP-PLACEDUPES-005: loads once it becomes active', async () => {
duplicates.mockResolvedValue(page([PAIR]));
const { result, rerender } = setup(false);
expect(duplicates).not.toHaveBeenCalled();
rerender({ active: true });
await waitFor(() => expect(result.current.pairs).toEqual([PAIR]));
expect(duplicates).toHaveBeenCalledTimes(1);
});
it('FE-COMP-PLACEDUPES-006: offline the list stays empty without an error toast', async () => {
duplicates.mockRejectedValue(new OnlineOnlyError());
const { result } = setup();
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.pairs).toEqual([]);
expect(addToast).not.toHaveBeenCalled();
});
it('FE-COMP-PLACEDUPES-007: any other load failure empties the list and says so', async () => {
duplicates.mockRejectedValue(new Error('boom'));
const { result } = setup();
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.pairs).toEqual([]);
expect(addToast).toHaveBeenCalledWith('common.error', 'error', undefined);
});
it('FE-COMP-PLACEDUPES-008: the server message is shown when the load is refused with one', async () => {
duplicates.mockRejectedValue({ response: { data: { error: 'Not allowed' } } });
const { result } = setup();
await waitFor(() => expect(result.current.loading).toBe(false));
expect(addToast).toHaveBeenCalledWith('Not allowed', 'error', undefined);
});
it('FE-COMP-PLACEDUPES-009: keeping side a merges a into b, drops the pair and reports the change', async () => {
merge.mockResolvedValue({ merge_id: 11, entry: null });
const { result, onChanged } = await loaded();
await act(async () => {
await result.current.merge(PAIR, 'a');
});
expect(merge).toHaveBeenCalledWith(PAIR.a.key, PAIR.b.key);
expect(result.current.pairs).toEqual([OTHER_PAIR]);
expect(onChanged).toHaveBeenCalledTimes(1);
expect(result.current.lastMerge).toEqual({ id: 11, name: PAIR.a.name });
expect(result.current.busy).toBeNull();
});
it('FE-COMP-PLACEDUPES-010: keeping side b leads with b and remembers its name for the undo', async () => {
merge.mockResolvedValue({ merge_id: 12, entry: null });
const { result } = await loaded();
await act(async () => {
await result.current.merge(PAIR, 'b');
});
expect(merge).toHaveBeenCalledWith(PAIR.b.key, PAIR.a.key);
expect(result.current.lastMerge).toEqual({ id: 12, name: 'Colosseo' });
});
it('FE-COMP-PLACEDUPES-011: a failed merge keeps the pair, reports nothing changed and toasts', async () => {
merge.mockRejectedValue(new Error('conflict'));
const { result, onChanged } = await loaded();
await act(async () => {
await result.current.merge(PAIR, 'a');
});
expect(result.current.pairs).toEqual([PAIR, OTHER_PAIR]);
expect(result.current.lastMerge).toBeNull();
expect(result.current.busy).toBeNull();
expect(onChanged).not.toHaveBeenCalled();
expect(addToast).toHaveBeenCalledWith('common.error', 'error', undefined);
});
it('FE-COMP-PLACEDUPES-012: marks the pair busy while it merges and ignores a second click', async () => {
let finish: (v: { merge_id: number; entry: null }) => void = () => undefined;
merge.mockReturnValue(
new Promise((resolve) => {
finish = resolve;
})
);
const { result } = await loaded();
act(() => {
void result.current.merge(PAIR, 'a');
});
await waitFor(() => expect(result.current.busy).toBe(pairKey(PAIR)));
await act(async () => {
await result.current.merge(OTHER_PAIR, 'a');
await result.current.dismiss(OTHER_PAIR);
});
expect(merge).toHaveBeenCalledTimes(1);
expect(dismiss).not.toHaveBeenCalled();
await act(async () => {
finish({ merge_id: 1, entry: null });
});
await waitFor(() => expect(result.current.busy).toBeNull());
expect(result.current.pairs).toEqual([OTHER_PAIR]);
});
it('FE-COMP-PLACEDUPES-013: "not the same place" dismisses the pair by both keys and drops it', async () => {
dismiss.mockResolvedValue(undefined);
const { result, onChanged } = await loaded();
await act(async () => {
await result.current.dismiss(OTHER_PAIR);
});
expect(dismiss).toHaveBeenCalledWith('trip:7', 'trip:8');
expect(result.current.pairs).toEqual([PAIR]);
expect(result.current.lastMerge).toBeNull();
expect(onChanged).toHaveBeenCalledTimes(1);
});
it('FE-COMP-PLACEDUPES-014: a failed dismiss keeps the pair and toasts the server message', async () => {
dismiss.mockRejectedValue({ response: { data: { error: 'Gone' } } });
const { result, onChanged } = await loaded();
await act(async () => {
await result.current.dismiss(PAIR);
});
expect(result.current.pairs).toEqual([PAIR, OTHER_PAIR]);
expect(onChanged).not.toHaveBeenCalled();
expect(addToast).toHaveBeenCalledWith('Gone', 'error', undefined);
});
it('FE-COMP-PLACEDUPES-015: undo takes the last merge back, clears it and reloads the pairs', async () => {
merge.mockResolvedValue({ merge_id: 11, entry: null });
undoMerge.mockResolvedValue(undefined);
const { result, onChanged } = await loaded();
await act(async () => {
await result.current.merge(PAIR, 'a');
});
expect(onChanged).toHaveBeenCalledTimes(1);
duplicates.mockResolvedValue(page([PAIR, OTHER_PAIR]));
await act(async () => {
await result.current.undo();
});
expect(undoMerge).toHaveBeenCalledWith(11);
expect(result.current.lastMerge).toBeNull();
expect(onChanged).toHaveBeenCalledTimes(2);
await waitFor(() => expect(result.current.pairs).toEqual([PAIR, OTHER_PAIR]));
expect(duplicates).toHaveBeenCalledTimes(2);
expect(result.current.busy).toBeNull();
});
it('FE-COMP-PLACEDUPES-016: undo without a merge does nothing', async () => {
const { result, onChanged } = await loaded();
await act(async () => {
await result.current.undo();
});
expect(undoMerge).not.toHaveBeenCalled();
expect(onChanged).not.toHaveBeenCalled();
});
it('FE-COMP-PLACEDUPES-017: a failed undo keeps the merge to try again and toasts', async () => {
merge.mockResolvedValue({ merge_id: 11, entry: null });
undoMerge.mockRejectedValue(new Error('nope'));
const { result, onChanged } = await loaded();
await act(async () => {
await result.current.merge(PAIR, 'a');
});
await act(async () => {
await result.current.undo();
});
expect(result.current.lastMerge).toEqual({ id: 11, name: PAIR.a.name });
expect(result.current.busy).toBeNull();
expect(onChanged).toHaveBeenCalledTimes(1);
expect(duplicates).toHaveBeenCalledTimes(1);
expect(addToast).toHaveBeenCalledWith('common.error', 'error', undefined);
});
it('FE-COMP-PLACEDUPES-018: reload asks the server for the pairs again', async () => {
const { result } = await loaded([PAIR]);
duplicates.mockResolvedValue(page([OTHER_PAIR], 'more'));
act(() => result.current.reload());
await waitFor(() => expect(result.current.pairs).toEqual([OTHER_PAIR]));
expect(result.current.hasMore).toBe(true);
expect(duplicates).toHaveBeenCalledTimes(2);
});
it('FE-COMP-PLACEDUPES-019: an answer that arrives after unmounting is ignored', async () => {
let answer: (v: ReturnType<typeof page>) => void = () => undefined;
duplicates.mockReturnValue(
new Promise((resolve) => {
answer = resolve;
})
);
const { result, unmount } = setup();
unmount();
await act(async () => {
answer(page([PAIR]));
});
expect(result.current.pairs).toEqual([]);
});
});
@@ -0,0 +1,106 @@
import type { PlacesLibraryDuplicate } from '@trek/shared';
import { useCallback, useEffect, useState } from 'react';
import { OnlineOnlyError } from '../../repo/onlineOnly';
import { placeIdentitiesRepo } from '../../repo/placeIdentitiesRepo';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { useToast } from '../shared/Toast';
/** A pair's own name: its two keys in a fixed order, so either way round it is one pair. */
export const pairKey = (d: Pick<PlacesLibraryDuplicate, 'a' | 'b'>): string => [d.a.key, d.b.key].sort().join('|');
/**
* Places that look like the same place (PLC-13), behind the desktop dialog and the
* phone sheet: the pairs the server suggests, a merge that keeps the picked side's
* name and position and can be taken back, and "not the same" so a pair stays gone.
* Nothing here writes into a trip or a list; the merge only groups the user's view.
*/
export function usePlaceDuplicates({
active,
onChanged,
t,
}: {
active: boolean;
onChanged: () => void;
t: TranslationFn;
}) {
const toast = useToast();
const [pairs, setPairs] = useState<PlacesLibraryDuplicate[]>([]);
const [hasMore, setHasMore] = useState(false);
const [busy, setBusy] = useState<string | null>(null);
const [lastMerge, setLastMerge] = useState<{ id: number; name: string } | null>(null);
const [seq, setSeq] = useState(0);
// The request that last answered; loading while it is not the current one.
const [settled, setSettled] = useState<number | null>(null);
useEffect(() => {
if (!active) return;
const ctrl = new AbortController();
placeIdentitiesRepo
.duplicates({}, ctrl.signal)
.then((res) => {
if (ctrl.signal.aborted) return;
setPairs(res.duplicates);
setHasMore(res.next_cursor != null);
})
.catch((err: unknown) => {
if (ctrl.signal.aborted) return;
setPairs([]);
// Offline the count is simply not shown; any other failure says so.
if (!(err instanceof OnlineOnlyError)) toast.error(getApiErrorMessage(err, t('common.error')));
})
.finally(() => {
if (!ctrl.signal.aborted) setSettled(seq);
});
return () => ctrl.abort();
}, [active, seq, toast, t]);
const reload = useCallback(() => setSeq((n) => n + 1), []);
const loading = active && settled !== seq;
const run = async (pair: PlacesLibraryDuplicate, action: () => Promise<void>) => {
const key = pairKey(pair);
if (busy) return;
setBusy(key);
try {
await action();
setPairs((prev) => prev.filter((p) => pairKey(p) !== key));
onChanged();
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')));
} finally {
setBusy(null);
}
};
/** Keeps `leading`'s name and position; the other side joins it. */
const merge = (pair: PlacesLibraryDuplicate, leading: 'a' | 'b') =>
run(pair, async () => {
const lead = pair[leading];
const other = leading === 'a' ? pair.b : pair.a;
const res = await placeIdentitiesRepo.merge(lead.key, other.key);
setLastMerge({ id: res.merge_id, name: lead.name });
});
const dismiss = (pair: PlacesLibraryDuplicate) =>
run(pair, () => placeIdentitiesRepo.dismiss(pair.a.key, pair.b.key));
const undo = async () => {
if (!lastMerge || busy) return;
setBusy('undo');
try {
await placeIdentitiesRepo.undoMerge(lastMerge.id);
setLastMerge(null);
onChanged();
reload();
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')));
} finally {
setBusy(null);
}
};
return { pairs, hasMore, loading, busy, lastMerge, merge, dismiss, undo, reload };
}
@@ -1,4 +1,4 @@
// FE-COMP-PLACESLIBHOOK-001 to FE-COMP-PLACESLIBHOOK-025: the "All places" logic behind
// FE-COMP-PLACESLIBHOOK-001 to FE-COMP-PLACESLIBHOOK-026: the "All places" logic behind
// the desktop view and the phone screen (PLC-07, PLC-08).
import { act, renderHook, waitFor } from '@testing-library/react';
import type { PlacesLibraryDetailResponse, PlacesLibraryPageResponse } from '@trek/shared';
@@ -16,7 +16,7 @@ import {
import { OnlineOnlyError } from '../../repo/onlineOnly';
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
import type { TranslationFn } from '../../types';
import { entryHasPosition, parseEntryKey, usePlacesLibrary } from './usePlacesLibrary';
import { entryHasPosition, firstOrigin, parseEntryKey, usePlacesLibrary } from './usePlacesLibrary';
vi.mock('../../repo/placesLibraryRepo', () => ({
placesLibraryRepo: { list: vi.fn(), detail: vi.fn(), coverPhoto: vi.fn() },
@@ -428,4 +428,14 @@ describe('usePlacesLibrary: the cover', () => {
expect(result.current.cover).toBeNull();
expect(result.current.detail).not.toBeNull();
});
it('FE-COMP-PLACESLIBHOOK-026: an own place opens through its first use', () => {
const trip = libraryEntry({ key: 'own:3' });
expect(firstOrigin([trip], 'own:3')).toEqual(
trip.origins[0].kind === 'trip'
? { kind: 'trip', id: trip.origins[0].place_id }
: { kind: 'list', id: trip.origins[0].collection_place_id }
);
expect(firstOrigin([trip], 'own:9')).toBeNull();
});
});
@@ -27,19 +27,56 @@ export function parseEntryKey(key: string): { kind: PlacesLibraryKind; id: numbe
return match ? { kind: match[1] as PlacesLibraryKind, id: Number(match[2]) } : null;
}
/**
* Where an entry of one's own place (`own:<id>`) is opened from: its first use, since
* the detail route reads a trip place or a saved place and lists every use either way.
*/
export function firstOrigin(
entries: readonly PlacesLibraryEntry[],
key: string
): { kind: PlacesLibraryKind; id: number } | null {
const origin = entries.find((e) => e.key === key)?.origins[0];
if (!origin) return null;
return origin.kind === 'trip'
? { kind: 'trip', id: origin.place_id }
: { kind: 'list', id: origin.collection_place_id };
}
/** An entry with coordinates, as a point for the map. */
export function entryHasPosition(entry: Pick<PlacesLibraryEntry, 'lat' | 'lng'>): boolean {
return entry.lat != null && entry.lng != null && Number.isFinite(entry.lat) && Number.isFinite(entry.lng);
}
/**
* "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
* markup over it. Online only like the lists themselves; a filter change starts a
* fresh first page, "more" appends the next one, and opening an entry loads what
* each of its origins keeps.
*/
export function usePlacesLibrary({ active, t }: { active: boolean; t: TranslationFn }) {
interface PageState {
/** The request this state answers; the first page is loading while it is not the current one. */
key: string;
entries: PlacesLibraryEntry[];
total: number;
counts: PlacesLibraryCounts;
cursor: string | null;
error: string | null;
offline: boolean;
}
const EMPTY_PAGE: PageState = {
key: '',
entries: [],
total: 0,
counts: NO_COUNTS,
cursor: null,
error: null,
offline: false,
};
/** A failure as the screen shows it: offline says so, anything else names the error. */
function failureOf(err: unknown, t: TranslationFn): { error: string | null; offline: boolean } {
return err instanceof OnlineOnlyError
? { error: null, offline: true }
: { error: getApiErrorMessage(err, t('common.error')), offline: false };
}
/** The filters of "All places". */
function useLibraryFilters() {
const [search, setSearch] = useState('');
const [query, setQuery] = useState('');
const [kind, setKind] = useState<LibraryKindFilter>('all');
@@ -47,22 +84,6 @@ export function usePlacesLibrary({ active, t }: { active: boolean; t: Translatio
const [sort, setSort] = useState<PlacesLibrarySort>('name');
const [status, setStatus] = useState<CollectionStatus | 'all'>('all');
const [entries, setEntries] = useState<PlacesLibraryEntry[]>([]);
const [total, setTotal] = useState(0);
const [counts, setCounts] = useState<PlacesLibraryCounts>(NO_COUNTS);
const [cursor, setCursor] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState<string | null>(null);
const [offline, setOffline] = useState(false);
const [reloadSeq, setReloadSeq] = useState(0);
const [selectedKey, setSelectedKey] = useState<string | null>(null);
const [detail, setDetail] = useState<PlacesLibraryDetailResponse | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
// The provider's photo for a place without its own, as a list's place sheet shows it.
const [cover, setCover] = useState<string | null>(null);
// Typing settles before it asks.
useEffect(() => {
const timer = setTimeout(() => setQuery(search.trim()), SEARCH_SETTLE_MS);
@@ -80,129 +101,6 @@ export function usePlacesLibrary({ active, t }: { active: boolean; t: Translatio
}),
[query, kind, categoryId, status, sort]
);
const fail = useCallback(
(err: unknown) => {
if (err instanceof OnlineOnlyError) setOffline(true);
else setError(getApiErrorMessage(err, t('common.error')));
},
[t]
);
// The first page, again for every filter change and every reload.
useEffect(() => {
if (!active) return;
const ctrl = new AbortController();
setLoading(true);
setError(null);
setOffline(false);
placesLibraryRepo
.list(filters, ctrl.signal)
.then((page) => {
if (ctrl.signal.aborted) return;
setEntries(page.entries);
setTotal(page.total);
setCounts(page.counts);
setCursor(page.next_cursor);
})
.catch((err: unknown) => {
if (!ctrl.signal.aborted) fail(err);
})
.finally(() => {
if (!ctrl.signal.aborted) setLoading(false);
});
return () => ctrl.abort();
}, [active, filters, reloadSeq, fail]);
const moreRef = useRef<AbortController | null>(null);
const loadMore = useCallback(async () => {
if (!cursor || loadingMore) return;
moreRef.current?.abort();
const ctrl = new AbortController();
moreRef.current = ctrl;
setLoadingMore(true);
try {
const page = await placesLibraryRepo.list({ ...filters, cursor }, ctrl.signal);
if (ctrl.signal.aborted) return;
setEntries((prev) => [...prev, ...page.entries.filter((e) => !prev.some((p) => p.key === e.key))]);
setCursor(page.next_cursor);
} catch (err) {
if (!ctrl.signal.aborted) fail(err);
} finally {
// Only the latest request lets go of the button: an aborted one was replaced or
// dropped by a filter change, which lets go of it itself.
if (moreRef.current === ctrl) setLoadingMore(false);
}
}, [cursor, loadingMore, filters, fail]);
// A filter change starts over, so a page still on its way is dropped and "more" is free again.
useEffect(
() => () => {
moreRef.current?.abort();
moreRef.current = null;
setLoadingMore(false);
},
[filters]
);
// The entry that is open, and what its origins keep.
useEffect(() => {
const ref = selectedKey ? parseEntryKey(selectedKey) : null;
if (!ref) {
setDetail(null);
return;
}
const ctrl = new AbortController();
setDetailLoading(true);
placesLibraryRepo
.detail(ref.kind, ref.id, ctrl.signal)
.then((res) => {
if (!ctrl.signal.aborted) setDetail(res);
})
.catch((err: unknown) => {
if (ctrl.signal.aborted) return;
setDetail(null);
setSelectedKey(null);
fail(err);
})
.finally(() => {
if (!ctrl.signal.aborted) setDetailLoading(false);
});
return () => {
ctrl.abort();
setDetailLoading(false);
};
}, [selectedKey, reloadSeq, fail]);
useEffect(() => {
setCover(null);
const entry = detail?.entry;
if (!entry) return;
const own = entry.image_url ?? detail.details.map((d) => d.info.image_url).find(Boolean) ?? null;
if (own) {
setCover(own);
return;
}
let cancelled = false;
placesLibraryRepo
.coverPhoto(entry)
.then((url) => {
if (!cancelled) setCover(url);
})
// No photo is the gradient, which is what a failed lookup should look like too.
.catch(() => {
if (!cancelled) setCover(null);
});
return () => {
cancelled = true;
};
}, [detail]);
const reload = useCallback(() => setReloadSeq((n) => n + 1), []);
const open = useCallback((key: string | null) => setSelectedKey((cur) => (cur === key ? null : key)), []);
const show = useCallback((key: string) => setSelectedKey(key), []);
const close = useCallback(() => setSelectedKey(null), []);
const filtered = query !== '' || kind !== 'all' || categoryId !== 'all' || status !== 'all';
const resetFilters = useCallback(() => {
setSearch('');
@@ -212,38 +110,206 @@ export function usePlacesLibrary({ active, t }: { active: boolean; t: Translatio
setStatus('all');
}, []);
const mappable = useMemo(() => entries.filter(entryHasPosition), [entries]);
return {
filters,
controls: {
search,
setSearch,
kind,
setKind,
categoryId,
setCategoryId,
sort,
setSort,
status,
setStatus,
filtered,
resetFilters,
},
};
}
/** The first page for the filters and the pages "more" appends. */
function useLibraryPages(active: boolean, reloadSeq: number, t: TranslationFn) {
const { filters, controls } = useLibraryFilters();
const [page, setPage] = useState<PageState>(EMPTY_PAGE);
// The request "more" is loading for; another key means the button is free again.
const [moreFor, setMoreFor] = useState<string | null>(null);
const requestKey = active ? `${JSON.stringify(filters)}#${reloadSeq}` : '';
// The first page, again for every filter change and every reload. What was shown
// stays until the answer comes, so a reload does not blank the list.
useEffect(() => {
if (!requestKey) return;
const ctrl = new AbortController();
placesLibraryRepo
.list(filters, ctrl.signal)
.then((res) => {
if (ctrl.signal.aborted) return;
setPage({
key: requestKey,
entries: res.entries,
total: res.total,
counts: res.counts,
cursor: res.next_cursor,
error: null,
offline: false,
});
})
.catch((err: unknown) => {
if (!ctrl.signal.aborted) setPage((prev) => ({ ...prev, key: requestKey, ...failureOf(err, t) }));
});
return () => ctrl.abort();
}, [requestKey, filters, t]);
const current = page.key === requestKey;
const cursor = current ? page.cursor : null;
const loadingMore = moreFor !== null && moreFor === requestKey;
const moreRef = useRef<AbortController | null>(null);
const loadMore = useCallback(async () => {
if (!cursor || loadingMore) return;
moreRef.current?.abort();
const ctrl = new AbortController();
moreRef.current = ctrl;
const forKey = requestKey;
setMoreFor(forKey);
try {
const res = await placesLibraryRepo.list({ ...filters, cursor }, ctrl.signal);
if (ctrl.signal.aborted) return;
setPage((prev) => {
if (prev.key !== forKey) return prev;
const fresh = res.entries.filter((e) => !prev.entries.some((p) => p.key === e.key));
return { ...prev, entries: [...prev.entries, ...fresh], cursor: res.next_cursor };
});
} catch (err) {
if (!ctrl.signal.aborted) setPage((prev) => (prev.key === forKey ? { ...prev, ...failureOf(err, t) } : prev));
} finally {
if (moreRef.current === ctrl) setMoreFor(null);
}
}, [cursor, loadingMore, filters, requestKey, t]);
// A filter change starts over, so a page still on its way is dropped.
useEffect(() => () => moreRef.current?.abort(), [filters]);
return {
search,
setSearch,
kind,
setKind,
categoryId,
setCategoryId,
sort,
setSort,
status,
setStatus,
filtered,
resetFilters,
entries,
mappable,
total,
counts,
controls,
page,
loading: requestKey !== '' && !current,
hasMore: cursor != null,
loading,
loadingMore,
loadMore,
error,
offline,
reload,
};
}
/** The entry that is open and what its origins keep. */
function useLibraryDetail(entries: readonly PlacesLibraryEntry[], reloadSeq: number, onError: (err: unknown) => void) {
const [selectedKey, setSelectedKey] = useState<string | null>(null);
const [loaded, setLoaded] = useState<{ key: string; detail: PlacesLibraryDetailResponse } | null>(null);
const [settled, setSettled] = useState<string | null>(null);
// Where the open entry is read from, as text so a page arriving later does not ask again.
const origin = selectedKey ? (parseEntryKey(selectedKey) ?? firstOrigin(entries, selectedKey)) : null;
const originKey = origin ? `${origin.kind}:${origin.id}` : null;
const requestKey = selectedKey && originKey ? `${selectedKey}|${originKey}#${reloadSeq}` : null;
useEffect(() => {
if (!selectedKey || !originKey || !requestKey) return;
const [kind, id] = originKey.split(':');
const ctrl = new AbortController();
placesLibraryRepo
.detail(kind as PlacesLibraryKind, Number(id), ctrl.signal)
.then((res) => {
if (!ctrl.signal.aborted) setLoaded({ key: selectedKey, detail: res });
})
.catch((err: unknown) => {
if (ctrl.signal.aborted) return;
setSelectedKey(null);
onError(err);
})
.finally(() => {
if (!ctrl.signal.aborted) setSettled(requestKey);
});
return () => ctrl.abort();
}, [selectedKey, originKey, requestKey, onError]);
const open = useCallback((key: string | null) => setSelectedKey((cur) => (cur === key ? null : key)), []);
const show = useCallback((key: string) => setSelectedKey(key), []);
const close = useCallback(() => setSelectedKey(null), []);
return {
selectedKey,
open,
show,
close,
detail,
detailLoading,
detail: loaded && loaded.key === selectedKey ? loaded.detail : null,
detailLoading: requestKey !== null && settled !== requestKey,
};
}
/** The open place's picture: its own, a list's, or else the provider's photo for it. */
function useLibraryCover(detail: PlacesLibraryDetailResponse | null): string | null {
const [photo, setPhoto] = useState<{ key: string; url: string | null } | null>(null);
const entry = detail?.entry ?? null;
const ownImage = entry
? (entry.image_url ?? detail?.details.map((d) => d.info.image_url).find(Boolean) ?? null)
: null;
useEffect(() => {
if (!entry || ownImage || entry.lat == null || entry.lng == null) return;
let cancelled = false;
const key = entry.key;
placesLibraryRepo
.coverPhoto({ ...entry, lat: entry.lat, lng: entry.lng })
.then((url) => {
if (!cancelled) setPhoto({ key, url });
})
// No photo is the gradient, which is what a failed lookup should look like too.
.catch(() => {
if (!cancelled) setPhoto({ key, url: null });
});
return () => {
cancelled = true;
};
}, [entry, ownImage]);
if (ownImage) return ownImage;
return entry && photo?.key === entry.key ? photo.url : null;
}
/**
* "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
* markup over it. Online only like the lists themselves; a filter change starts a
* fresh first page, "more" appends the next one, and opening an entry loads what
* each of its origins keeps.
*/
export function usePlacesLibrary({ active, t }: { active: boolean; t: TranslationFn }) {
const [reloadSeq, setReloadSeq] = useState(0);
const [detailError, setDetailError] = useState<{ error: string | null; offline: boolean } | null>(null);
const pages = useLibraryPages(active, reloadSeq, t);
const onDetailError = useCallback((err: unknown) => setDetailError(failureOf(err, t)), [t]);
const sel = useLibraryDetail(pages.page.entries, reloadSeq, onDetailError);
const cover = useLibraryCover(sel.detail);
const reload = useCallback(() => {
setDetailError(null);
setReloadSeq((n) => n + 1);
}, []);
const { entries, total, counts, error, offline } = pages.page;
const mappable = useMemo(() => entries.filter(entryHasPosition), [entries]);
return {
...pages.controls,
entries,
mappable,
total,
counts,
hasMore: pages.hasMore,
loading: pages.loading,
loadingMore: pages.loadingMore,
loadMore: pages.loadMore,
error: error ?? detailError?.error ?? null,
offline: offline || (detailError?.offline ?? false),
reload,
...sel,
cover,
};
}
+13 -16
View File
@@ -1,32 +1,29 @@
/** Lucide's star, the one the lists wear. */
const STAR_PATH =
'M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z';
/**
* The rating a place carries, as a star on the corner of its marker.
* The rating a place carries, as a disc on the corner of its marker.
*
* Bottom right, where a trip's day numbers sit — the two never appear together, since
* a numbered stop is one you have already planned and this answers the question you
* ask before that: of all these photos, which did I like. Amber rather than the number
* badge's white, so a glance tells them apart without reading either.
*
* A star like the one the lists put on a place's picture, so the vote reads the same on
* the map and beside it; the figure inside is rounded to one decimal.
* A rounded value and no star: at eighteen pixels a star is a smudge, and "4.5" is
* already the whole sentence.
*/
export function ratingBadgeHtml(rating: number | null | undefined): string {
if (typeof rating !== 'number' || !(rating > 0)) return '';
const label = Number.isInteger(rating) ? String(rating) : rating.toFixed(1);
// A star rather than a disc, as in the lists; its box a little over the old disc,
// since a star fills less of it. Leaflet lifts every svg in a marker to z-index 200,
// so both layers name theirs, or the star covers its own figure.
return `<span style="
position:absolute;bottom:-6px;right:-6px;
width:22px;height:22px;
position:absolute;bottom:-4px;right:-4px;
min-width:18px;height:18px;border-radius:9px;
padding:0 4px;
background:#f59e0b;
border:1.5px solid rgba(255,255,255,0.92);
box-shadow:0 1px 4px rgba(0,0,0,0.25);
display:flex;align-items:center;justify-content:center;
"><svg viewBox="0 0 24 24" width="22" height="22" style="position:absolute;inset:0;z-index:0;overflow:visible"
fill="#fbbf24" stroke="rgba(255,255,255,0.92)" stroke-width="1.3" stroke-linejoin="round"><path d="${STAR_PATH}"/></svg>
<span style="position:relative;z-index:1;margin-top:2px;font-size:${label.length > 1 ? 6.5 : 8.5}px;font-weight:800;line-height:1;
color:#111;font-family:var(--font-system);white-space:nowrap;">${label}</span></span>`;
font-size:9px;font-weight:800;color:#fff;text-shadow:0 1px 1px rgba(0,0,0,.45);
font-family:var(--font-system);line-height:1;
box-sizing:border-box;white-space:nowrap;
">${label}</span>`;
}
/**
@@ -1,12 +1,12 @@
import { Globe2, Layers, Plus } from 'lucide-react';
import { createElement } from 'react';
import { listIcon } from '../../../components/Collections/listIcons';
import { ALL_SAVED } from '../../../store/collectionStore';
/** A list's symbol in its colour, in the slot the dot used to take. */
function ListIcon({ name, color }: { name?: string | null; color: string }) {
const Icon = listIcon(name);
return <Icon size={15} strokeWidth={2.2} className="flex-none" style={{ color }} />;
return createElement(listIcon(name), { size: 15, strokeWidth: 2.2, className: 'flex-none', style: { color } });
}
interface ListEntry {
@@ -243,7 +243,7 @@ export default function MCollections() {
{c.isLibrary ? (
// Every place of the trips and lists (PLC-07); it needs no list of one's own.
<div className={`mt-3 ${c.view === 'map' ? 'flex min-h-0 flex-1 flex-col' : ''}`}>
<MPlacesLibrary categories={c.categories} language={c.language} dark={c.dark} view={c.view} onView={c.setView} navigate={c.navigate} t={t} />
<MPlacesLibrary categories={c.categories} language={c.language} dark={c.dark} view={c.view} onView={c.setView} navigate={to => void c.navigate(to)} t={t} />
</div>
) : c.loading && c.collections.length === 0 ? (
<MSkeleton variant="rows" count={5} className="pt-2" />
@@ -0,0 +1,69 @@
import type { PlacesLibraryDuplicate } from '@trek/shared';
import { CopyCheck, Loader2, Undo2 } from 'lucide-react';
import DuplicatePairCard from '../../../components/Collections/DuplicatePairCard';
import { pairKey, type usePlaceDuplicates } from '../../../components/Collections/usePlaceDuplicates';
import type { TranslationFn } from '../../../types';
import MSheet from '../../components/MSheet';
import { SheetHeader } from './MCollSheetKit';
/** The phone's look at places that seem to be one place (PLC-13); the logic is the dialog's. */
export default function MDuplicatesSheet({
open,
d,
onClose,
t,
}: {
open: boolean;
/** The screen's duplicates, which also drive the count on its chip. */
d: ReturnType<typeof usePlaceDuplicates>;
onClose: () => void;
t: TranslationFn;
}) {
return (
<MSheet open={open} onClose={onClose} ariaLabel={t('collections.duplicates.title')}>
<SheetHeader
icon={<CopyCheck size={19} strokeWidth={1.8} />}
title={t('collections.duplicates.title')}
onClose={onClose}
closeLabel={t('common.close')}
/>
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4 pt-3">
<p className="m-0 mb-3 text-caption text-m-muted">{t('collections.duplicates.sub')}</p>
{d.lastMerge && (
<button
type="button"
onClick={() => void d.undo()}
disabled={d.busy === 'undo'}
className="mb-3 flex w-full items-center justify-center gap-2 rounded-full border border-m-rowbr bg-m-sheetop py-[9px] text-caption font-semibold text-m-ink"
>
<Undo2 size={14} /> {t('collections.duplicates.undo', { name: d.lastMerge.name })}
</button>
)}
{d.loading && d.pairs.length === 0 ? (
<div className="flex justify-center py-10 text-m-faint">
<Loader2 size={20} className="animate-spin" />
</div>
) : d.pairs.length === 0 ? (
<p className="m-0 py-10 text-center text-body text-m-faint">{t('collections.duplicates.none')}</p>
) : (
<div className="flex flex-col gap-2">
{d.pairs.map((pair: PlacesLibraryDuplicate) => (
<DuplicatePairCard
key={pairKey(pair)}
pair={pair}
busy={d.busy === pairKey(pair)}
onMerge={(leading) => void d.merge(pair, leading)}
onDismiss={() => void d.dismiss(pair)}
variant="sheet"
t={t}
/>
))}
{d.hasMore && (
<p className="m-0 text-center text-caption text-m-faint">{t('collections.duplicates.more')}</p>
)}
</div>
)}
</div>
</MSheet>
);
}
@@ -1,4 +1,4 @@
import type { PlacesLibraryDetail, PlacesLibraryDetailResponse, PlacesLibraryOrigin } from '@trek/shared';
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import {
Bookmark,
BookmarkPlus,
@@ -15,9 +15,16 @@ import {
Ticket,
X,
} from 'lucide-react';
import { useRef, useState } from 'react';
import { createElement, useRef, useState } from 'react';
import { tripLine } from '../../../components/Collections/libraryDates';
import { originName } from '../../../components/Collections/LibraryOrigins';
import {
originPairs,
type ListPair,
type TripDetail,
type TripOrigin,
type TripPair,
} from '../../../components/Collections/libraryPairs';
import { originName } from '../../../components/Collections/originName';
import {
getNavigationTargets,
navigationTargetLabel,
@@ -30,11 +37,6 @@ import MSheet from '../../components/MSheet';
import { categoryMeta, STATUS_SPEC, tint, UNCATEGORIZED_META } from './collectionsMobileModel';
import { Eyebrow } from './MCollSheetKit';
type TripOrigin = Extract<PlacesLibraryOrigin, { kind: 'trip' }>;
type ListOrigin = Extract<PlacesLibraryOrigin, { kind: 'list' }>;
type TripDetail = Extract<PlacesLibraryDetail, { kind: 'trip' }>;
type ListDetail = Extract<PlacesLibraryDetail, { kind: 'list' }>;
interface MLibraryPlaceSheetProps {
open: boolean;
data: PlacesLibraryDetailResponse | null;
@@ -70,268 +72,321 @@ function Notes({ text, t }: { text: string | null; t: TranslationFn }) {
);
}
/**
* One place of "All places" on the phone (PLC-08): the sheet a list's place opens
* in, with the cover, then every trip and list the place sits in and what each
* keeps of it, and the things to do with it at the bottom.
*/
export default function MLibraryPlaceSheet({
open,
data,
loading,
type Entry = NonNullable<PlacesLibraryDetailResponse['entry']>;
/** The cover band: the picture or a gradient, the category, the close button and the name. */
function SheetCover({
entry,
cover,
language,
onClose,
t,
}: {
entry: Entry | null;
cover: string | null;
onClose: () => void;
t: TranslationFn;
}) {
const meta = categoryMeta(entry?.category) ?? UNCATEGORIZED_META;
const gradient = entry ? entry.name.length + entry.key.length : 0;
return (
<div
className="relative h-[150px] flex-none overflow-hidden"
style={cover ? undefined : { backgroundImage: entityGradient(gradient) }}
>
{cover && <img src={cover} alt="" className="absolute inset-0 h-full w-full object-cover" />}
<div className="absolute inset-0 bg-gradient-to-b from-transparent to-black/60" />
<div className="absolute inset-x-3 top-3 flex items-center gap-2">
{entry?.category && (
<span
className="inline-flex min-w-0 items-center gap-1 rounded-full bg-m-sheetop px-[10px] py-[3px] text-caption font-bold"
style={{ color: meta.color }}
>
{createElement(meta.icon, { size: 12, className: 'flex-none' })}{' '}
<span className="truncate">{entry.category.name}</span>
</span>
)}
<button
type="button"
onClick={onClose}
aria-label={t('common.close')}
className="ms-auto flex h-8 w-8 items-center justify-center rounded-full bg-black/30 text-white"
>
<X size={16} />
</button>
</div>
{entry && (
<h2 dir="auto" className="absolute inset-x-4 bottom-3 m-0 truncate text-title font-extrabold text-white">
{entry.name}
</h2>
)}
</div>
);
}
/** A trip the place is in: its day or dates, whether it is only readable, and what the trip keeps. */
function TripCard({
pair,
entryName,
language,
onOpen,
t,
}: {
pair: TripPair;
entryName: string;
language: string;
onOpen: () => void;
t: TranslationFn;
}) {
const { origin, detail } = pair;
const line = tripLine(origin, detail, language, t);
const renamed = detail.info.name !== entryName;
return (
<button
type="button"
className={CARD}
onClick={onOpen}
aria-label={`${t('collections.library.openTrip')}: ${originName(origin)}`}
>
<span className="flex items-center gap-[10px]">
<span className={ICO}>
<Luggage size={15} />
</span>
<span className="min-w-0 flex-1">
<span dir="auto" className="block truncate text-body font-bold text-m-ink">
{originName(origin)}
</span>
{line && <span className="block truncate text-caption text-m-muted">{line}</span>}
</span>
{origin.read_only && <span className={CHIP}>{t('collections.library.readOnly')}</span>}
<ChevronRight size={16} className="flex-none text-m-faint rtl:-scale-x-100" />
</span>
{(detail.has_accommodation || detail.has_reservation || renamed) && (
<span className="flex flex-wrap gap-[6px]">
{renamed && <span className={CHIP}>{t('collections.library.calledHere', { name: detail.info.name })}</span>}
{detail.has_accommodation && (
<span className={CHIP}>
<Hotel size={11} /> {t('collections.library.stay')}
</span>
)}
{detail.has_reservation && (
<span className={CHIP}>
<Ticket size={11} /> {t('collections.library.booking')}
</span>
)}
</span>
)}
<Notes text={detail.notes} t={t} />
</button>
);
}
/** A list the place is in: its status there, its labels and the list's vote. */
function ListCard({
pair,
entryName,
onOpen,
t,
}: {
pair: ListPair;
entryName: string;
onOpen: () => void;
t: TranslationFn;
}) {
const { origin, detail } = pair;
const status = STATUS_SPEC[origin.status];
const renamed = detail.info.name !== entryName;
const average = detail.rating.average;
return (
<button
type="button"
className={CARD}
onClick={onOpen}
aria-label={`${t('collections.library.openList')}: ${originName(origin)}`}
>
<span className="flex items-center gap-[10px]">
<span className={ICO}>
<Bookmark size={15} />
</span>
<span dir="auto" className="min-w-0 flex-1 truncate text-body font-bold text-m-ink">
{originName(origin)}
</span>
<span
className="inline-flex flex-none items-center gap-1 rounded-full px-[9px] py-[3px] text-caption font-bold"
style={{ background: tint(status.color, '1f'), color: status.color }}
>
{createElement(status.icon, { size: 11 })} {t(status.labelKey)}
</span>
<ChevronRight size={16} className="flex-none text-m-faint rtl:-scale-x-100" />
</span>
{(detail.labels.length > 0 || average != null || renamed) && (
<span className="flex flex-wrap gap-[6px]">
{renamed && <span className={CHIP}>{t('collections.library.calledHere', { name: detail.info.name })}</span>}
{detail.labels.map((label) => (
<span key={label.id} className={CHIP}>
<span className="h-2 w-2 rounded-full" style={{ background: label.color || 'var(--m-act)' }} />{' '}
{label.name}
</span>
))}
{average != null && (
<span className={CHIP}>
<Star size={11} />{' '}
{t('collections.library.rating', { rating: average.toFixed(1), count: detail.rating.count })}
</span>
)}
</span>
)}
<Notes text={detail.notes} t={t} />
</button>
);
}
/** Navigate there, save the trip's place to a list, copy the list's place to a trip. */
function SheetActions({
entry,
trip,
list,
onSaveToList,
onCopyToTrip,
t,
}: {
entry: Entry;
trip: TripPair | undefined;
list: ListPair | undefined;
onSaveToList: (origin: TripOrigin, detail: TripDetail) => void;
onCopyToTrip: (collectionPlaceId: number) => void;
t: TranslationFn;
}) {
const [navOpen, setNavOpen] = useState(false);
const navRef = useRef<HTMLButtonElement | null>(null);
const targets = getNavigationTargets({ name: entry.name, address: entry.address, lat: entry.lat, lng: entry.lng });
const single = targets.length === 1 ? targets[0] : null;
return (
<div className="mt-4 flex gap-2">
{targets.length > 0 && (
<>
<button
ref={navRef}
type="button"
className={ACTION}
onClick={() => (single ? openNavigationTarget(single) : setNavOpen((o) => !o))}
>
<Navigation size={14} /> {single ? navigationTargetLabel(single, t) : t('inspector.navigation')}
</button>
{navOpen && (
<NavigationMenu
targets={targets}
anchor={navRef.current}
onClose={() => setNavOpen(false)}
title={t('inspector.navigation')}
/>
)}
</>
)}
{trip && (
<button type="button" className={ACTION} onClick={() => onSaveToList(trip.origin, trip.detail)}>
<BookmarkPlus size={14} /> {t('inspector.saveToCollection')}
</button>
)}
{list && (
<button type="button" className={ACTION} onClick={() => onCopyToTrip(list.origin.collection_place_id)}>
<Copy size={14} /> {t('collections.copyToTrip')}
</button>
)}
</div>
);
}
/** Where it is, its description, its trips and lists, and what to do with it. */
function SheetBody({
entry,
data,
language,
onOpenList,
onOpenTrip,
onSaveToList,
onCopyToTrip,
t,
}: MLibraryPlaceSheetProps) {
const [navOpen, setNavOpen] = useState(false);
const navRef = useRef<HTMLButtonElement | null>(null);
const entry = data?.entry ?? null;
const meta = categoryMeta(entry?.category) ?? UNCATEGORIZED_META;
const CatIcon = meta.icon;
const targets = entry
? getNavigationTargets({ name: entry.name, address: entry.address, lat: entry.lat, lng: entry.lng })
: [];
const pairs =
entry && data
? entry.origins.map((origin, i) => ({ origin, detail: data.details[i] })).filter((p) => p.detail)
: [];
const trips = pairs.filter(
(p): p is { origin: TripOrigin; detail: TripDetail } => p.origin.kind === 'trip' && p.detail.kind === 'trip'
);
const lists = pairs.filter(
(p): p is { origin: ListOrigin; detail: ListDetail } => p.origin.kind === 'list' && p.detail.kind === 'list'
);
const description = pairs.map((p) => p.detail.info.description).find((d) => d?.trim());
}: Omit<MLibraryPlaceSheetProps, 'open' | 'loading' | 'cover' | 'onClose'> & { entry: Entry }) {
const { trips, lists, description } = originPairs(data);
return (
<MSheet open={open} onClose={onClose} ariaLabel={entry?.name ?? t('collections.library.title')}>
<div
className="relative h-[150px] flex-none overflow-hidden"
style={
cover ? undefined : { backgroundImage: entityGradient(entry ? entry.name.length + entry.key.length : 0) }
}
>
{cover && <img src={cover} alt="" className="absolute inset-0 h-full w-full object-cover" />}
<div className="absolute inset-0 bg-gradient-to-b from-transparent to-black/60" />
<div className="absolute inset-x-3 top-3 flex items-center gap-2">
{entry?.category && (
<span
className="inline-flex min-w-0 items-center gap-1 rounded-full bg-m-sheetop px-[10px] py-[3px] text-caption font-bold"
style={{ color: meta.color }}
>
<CatIcon size={12} className="flex-none" /> <span className="truncate">{entry.category.name}</span>
</span>
)}
<button
type="button"
onClick={onClose}
aria-label={t('common.close')}
className="ms-auto flex h-8 w-8 items-center justify-center rounded-full bg-black/30 text-white"
>
<X size={16} />
</button>
</div>
{entry && (
<h2 dir="auto" className="absolute inset-x-4 bottom-3 m-0 truncate text-title font-extrabold text-white">
{entry.name}
</h2>
)}
</div>
<>
{entry.address && (
<p dir="auto" className="m-0 flex items-center gap-1 text-caption text-m-muted">
<MapPin size={12} className="flex-none" /> {entry.address}
</p>
)}
{(entry.lat == null || entry.lng == null) && (
<p className="m-0 mt-1 flex items-center gap-1 text-caption text-m-muted">
<MapPinOff size={12} className="flex-none text-warning" /> {t('places.noCoordinates')}
</p>
)}
{description && (
<p dir="auto" className="m-0 mt-3 whitespace-pre-wrap text-body text-m-ink">
{description}
</p>
)}
{trips.length > 0 && (
<>
<Eyebrow className="mb-[6px] mt-4">{t('collections.library.inTrips').toUpperCase()}</Eyebrow>
<div className="flex flex-col gap-2">
{trips.map((pair) => (
<TripCard
key={pair.origin.place_id}
pair={pair}
entryName={entry.name}
language={language}
onOpen={() => onOpenTrip(pair.origin.trip_id, pair.origin.place_id)}
t={t}
/>
))}
</div>
</>
)}
{lists.length > 0 && (
<>
<Eyebrow className="mb-[6px] mt-4">{t('collections.library.inLists').toUpperCase()}</Eyebrow>
<div className="flex flex-col gap-2">
{lists.map((pair) => (
<ListCard
key={pair.origin.collection_place_id}
pair={pair}
entryName={entry.name}
onOpen={() => onOpenList(pair.origin.collection_id, pair.origin.collection_place_id)}
t={t}
/>
))}
</div>
</>
)}
<SheetActions
entry={entry}
trip={trips[0]}
list={lists[0]}
onSaveToList={onSaveToList}
onCopyToTrip={onCopyToTrip}
t={t}
/>
</>
);
}
/**
* One place of "All places" on the phone (PLC-08): the sheet a list's place opens
* in, with the cover, then every trip and list the place sits in and what each
* keeps of it, and the things to do with it at the bottom.
*/
export default function MLibraryPlaceSheet({ open, loading, cover, onClose, ...rest }: MLibraryPlaceSheetProps) {
const entry = rest.data?.entry ?? null;
return (
<MSheet open={open} onClose={onClose} ariaLabel={entry?.name ?? rest.t('collections.library.title')}>
<SheetCover entry={entry} cover={cover} onClose={onClose} t={rest.t} />
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4 pt-3">
{loading && !entry ? (
{loading && !entry && (
<div className="flex justify-center py-10 text-m-faint">
<Loader2 size={20} className="animate-spin" />
</div>
) : (
entry && (
<>
{entry.address && (
<p dir="auto" className="m-0 flex items-center gap-1 text-caption text-m-muted">
<MapPin size={12} className="flex-none" /> {entry.address}
</p>
)}
{(entry.lat == null || entry.lng == null) && (
<p className="m-0 mt-1 flex items-center gap-1 text-caption text-m-muted">
<MapPinOff size={12} className="flex-none text-warning" /> {t('places.noCoordinates')}
</p>
)}
{description && (
<p dir="auto" className="m-0 mt-3 whitespace-pre-wrap text-body text-m-ink">
{description}
</p>
)}
{trips.length > 0 && (
<>
<Eyebrow className="mb-[6px] mt-4">{t('collections.library.inTrips').toUpperCase()}</Eyebrow>
<div className="flex flex-col gap-2">
{trips.map(({ origin, detail }) => {
const line = tripLine(origin, detail, language, t);
return (
<button
key={origin.place_id}
type="button"
className={CARD}
onClick={() => onOpenTrip(origin.trip_id, origin.place_id)}
aria-label={`${t('collections.library.openTrip')}: ${originName(origin)}`}
>
<span className="flex items-center gap-[10px]">
<span className={ICO}>
<Luggage size={15} />
</span>
<span className="min-w-0 flex-1">
<span dir="auto" className="block truncate text-body font-bold text-m-ink">
{originName(origin)}
</span>
{line && <span className="block truncate text-caption text-m-muted">{line}</span>}
</span>
{origin.read_only && <span className={CHIP}>{t('collections.library.readOnly')}</span>}
<ChevronRight size={16} className="flex-none text-m-faint rtl:-scale-x-100" />
</span>
{(detail.has_accommodation || detail.has_reservation || detail.info.name !== entry.name) && (
<span className="flex flex-wrap gap-[6px]">
{detail.info.name !== entry.name && (
<span className={CHIP}>
{t('collections.library.calledHere', { name: detail.info.name })}
</span>
)}
{detail.has_accommodation && (
<span className={CHIP}>
<Hotel size={11} /> {t('collections.library.stay')}
</span>
)}
{detail.has_reservation && (
<span className={CHIP}>
<Ticket size={11} /> {t('collections.library.booking')}
</span>
)}
</span>
)}
<Notes text={detail.notes} t={t} />
</button>
);
})}
</div>
</>
)}
{lists.length > 0 && (
<>
<Eyebrow className="mb-[6px] mt-4">{t('collections.library.inLists').toUpperCase()}</Eyebrow>
<div className="flex flex-col gap-2">
{lists.map(({ origin, detail }) => {
const status = STATUS_SPEC[origin.status];
const StatusIcon = status.icon;
return (
<button
key={origin.collection_place_id}
type="button"
className={CARD}
onClick={() => onOpenList(origin.collection_id, origin.collection_place_id)}
aria-label={`${t('collections.library.openList')}: ${originName(origin)}`}
>
<span className="flex items-center gap-[10px]">
<span className={ICO}>
<Bookmark size={15} />
</span>
<span dir="auto" className="min-w-0 flex-1 truncate text-body font-bold text-m-ink">
{originName(origin)}
</span>
<span
className="inline-flex flex-none items-center gap-1 rounded-full px-[9px] py-[3px] text-caption font-bold"
style={{ background: tint(status.color, '1f'), color: status.color }}
>
<StatusIcon size={11} /> {t(status.labelKey)}
</span>
<ChevronRight size={16} className="flex-none text-m-faint rtl:-scale-x-100" />
</span>
{(detail.labels.length > 0 ||
detail.rating.average != null ||
detail.info.name !== entry.name) && (
<span className="flex flex-wrap gap-[6px]">
{detail.info.name !== entry.name && (
<span className={CHIP}>
{t('collections.library.calledHere', { name: detail.info.name })}
</span>
)}
{detail.labels.map((label) => (
<span key={label.id} className={CHIP}>
<span
className="h-2 w-2 rounded-full"
style={{ background: label.color || 'var(--m-act)' }}
/>{' '}
{label.name}
</span>
))}
{detail.rating.average != null && (
<span className={CHIP}>
<Star size={11} />{' '}
{t('collections.library.rating', {
rating: detail.rating.average.toFixed(1),
count: detail.rating.count,
})}
</span>
)}
</span>
)}
<Notes text={detail.notes} t={t} />
</button>
);
})}
</div>
</>
)}
<div className="mt-4 flex gap-2">
{targets.length > 0 && (
<>
<button
ref={navRef}
type="button"
className={ACTION}
onClick={() => (targets.length === 1 ? openNavigationTarget(targets[0]) : setNavOpen((o) => !o))}
>
<Navigation size={14} />{' '}
{targets.length === 1 ? navigationTargetLabel(targets[0], t) : t('inspector.navigation')}
</button>
{navOpen && (
<NavigationMenu
targets={targets}
anchor={navRef.current}
onClose={() => setNavOpen(false)}
title={t('inspector.navigation')}
/>
)}
</>
)}
{trips[0] && (
<button
type="button"
className={ACTION}
onClick={() => onSaveToList(trips[0].origin, trips[0].detail)}
>
<BookmarkPlus size={14} /> {t('inspector.saveToCollection')}
</button>
)}
{lists[0] && (
<button
type="button"
className={ACTION}
onClick={() => onCopyToTrip(lists[0].origin.collection_place_id)}
>
<Copy size={14} /> {t('collections.copyToTrip')}
</button>
)}
</div>
</>
)
)}
{entry && <SheetBody entry={entry} {...rest} />}
</div>
</MSheet>
);
@@ -3,6 +3,7 @@ import {
ArrowDownUp,
Bookmark,
ChevronDown,
CopyCheck,
Globe2,
Layers,
List,
@@ -15,7 +16,8 @@ import {
} from 'lucide-react';
import { useMemo, useState } from 'react';
import CollectionMap from '../../../components/Collections/CollectionMap';
import { originName } from '../../../components/Collections/LibraryOrigins';
import { originName } from '../../../components/Collections/originName';
import { usePlaceDuplicates } from '../../../components/Collections/usePlaceDuplicates';
import { usePlacesLibrary, type LibraryKindFilter } from '../../../components/Collections/usePlacesLibrary';
import { STATUS_ORDER } from '../../../pages/collections/collectionsModel';
import { useCollectionStore } from '../../../store/collectionStore';
@@ -25,6 +27,7 @@ import { placesPath } from '../../../utils/placesRoutes';
import { categoryMeta, STATUS_SPEC, tint, UNCATEGORIZED_META } from './collectionsMobileModel';
import { CHIP_IDLE, CHIP_ON, DROP_PANEL, DropRow, EmptyNote, FILTER_CHIP } from './MCollFilterKit';
import MCollTripPickerSheet from './MCollTripPickerSheet';
import MDuplicatesSheet from './MDuplicatesSheet';
import MLibraryPlaceSheet from './MLibraryPlaceSheet';
interface MPlacesLibraryProps {
@@ -115,6 +118,166 @@ function Row({ entry, onOpen, t }: { entry: PlacesLibraryEntry; onOpen: () => vo
);
}
type Library = ReturnType<typeof usePlacesLibrary>;
/** The open dropdown's choices: where from, status, category or order. */
function FilterDrop({
drop,
lib,
categories,
kindLabel,
pick,
t,
}: {
drop: Drop;
lib: Library;
categories: Category[];
kindLabel: (k: LibraryKindFilter) => string;
pick: (fn: () => void) => void;
t: TranslationFn;
}) {
return (
<>
{drop === 'kind' &&
(['all', 'trip', 'list'] as const).map((k) => (
<DropRow
key={k}
icon={
k === 'trip' ? (
<Luggage size={15} className="flex-none" />
) : k === 'list' ? (
<Bookmark size={15} className="flex-none" />
) : (
<Globe2 size={15} className="flex-none" />
)
}
label={kindLabel(k)}
count={lib.counts[k]}
on={lib.kind === k}
onPick={() => pick(() => lib.setKind(k))}
/>
))}
{drop === 'status' && (
<>
<DropRow
icon={<Layers size={15} className="flex-none" />}
label={t('collections.status.filterAll')}
on={lib.status === 'all'}
onPick={() => pick(() => lib.setStatus('all'))}
/>
{STATUS_ORDER.map((s: CollectionStatus) => {
const meta = STATUS_SPEC[s];
const Icon = meta.icon;
return (
<DropRow
key={s}
icon={<Icon size={15} className="flex-none" style={{ color: meta.color }} />}
label={t(meta.labelKey)}
on={lib.status === s}
onPick={() => pick(() => lib.setStatus(s))}
/>
);
})}
</>
)}
{drop === 'category' && (
<>
<DropRow
icon={<Shapes size={15} className="flex-none" />}
label={t('collections.status.filterAll')}
on={lib.categoryId === 'all'}
onPick={() => pick(() => lib.setCategoryId('all'))}
/>
{categories.map((c) => {
const meta = categoryMeta(c) ?? UNCATEGORIZED_META;
const Icon = meta.icon;
return (
<DropRow
key={c.id}
icon={<Icon size={15} className="flex-none" style={{ color: meta.color }} />}
label={c.name}
on={lib.categoryId === c.id}
onPick={() => pick(() => lib.setCategoryId(c.id))}
/>
);
})}
</>
)}
{drop === 'sort' &&
(['name', 'updated'] as PlacesLibrarySort[]).map((s) => (
<DropRow
key={s}
icon={<ArrowDownUp size={15} className="flex-none" />}
label={t(s === 'name' ? 'collections.sort.nameAsc' : 'collections.library.sortUpdated')}
on={lib.sort === s}
onPick={() => pick(() => lib.setSort(s))}
/>
))}
</>
);
}
/** What sits under the filters: offline, an error, loading, empty, the map or the rows. */
function Results({
lib,
view,
map,
dark,
t,
}: {
lib: Library;
view: 'list' | 'map';
map: ReturnType<typeof toMapPlaces>;
dark: boolean;
t: TranslationFn;
}) {
return lib.offline ? (
<EmptyNote scene="collections" title={t('collections.library.offline')} />
) : lib.error ? (
<p role="alert" className="mt-3 rounded-xl bg-danger-soft px-3 py-2 text-body text-danger">
{lib.error}
</p>
) : lib.loading && lib.entries.length === 0 ? (
<div className="flex justify-center py-16 text-m-faint">
<Loader2 size={20} className="animate-spin" />
</div>
) : lib.entries.length === 0 ? (
<EmptyNote
scene={lib.filtered ? 'search' : 'collections'}
title={t(lib.filtered ? 'collections.empty.noMatchTitle' : 'collections.library.emptyTitle')}
/>
) : view === 'map' ? (
<div className="mt-3 min-h-0 flex-1 overflow-hidden rounded-2xl border border-m-rowbr">
<CollectionMap
places={map.places}
selectedPlaceId={null}
onOpenPlace={(id) => {
const key = map.keyOf.get(id);
if (key) lib.show(key);
}}
dark={dark}
/>
</div>
) : (
<div className="wide:grid wide:grid-cols-[repeat(auto-fill,minmax(min(100%,380px),1fr))] wide:gap-x-3">
{lib.entries.map((entry) => (
<Row key={entry.key} entry={entry} onOpen={() => lib.show(entry.key)} t={t} />
))}
{lib.hasMore && (
<button
type="button"
onClick={() => void lib.loadMore()}
disabled={lib.loadingMore}
className="mt-3 flex w-full items-center justify-center gap-2 rounded-full border border-m-rowbr bg-m-sheetop py-[10px] text-body font-semibold text-m-ink"
>
{lib.loadingMore && <Loader2 size={15} className="animate-spin" />}
{t('collections.library.more', { count: lib.total - lib.entries.length })}
</button>
)}
</div>
);
}
/**
* "All places" on the phone (PLC-07): every place of the user's trips and lists as
* cards, with the same filter chips as a list (where from, status, category, order),
@@ -122,6 +285,8 @@ function Row({ entry, onOpen, t }: { entry: PlacesLibraryEntry; onOpen: () => vo
*/
export default function MPlacesLibrary({ categories, language, dark, view, onView, navigate, t }: MPlacesLibraryProps) {
const lib = usePlacesLibrary({ active: true, t });
const dup = usePlaceDuplicates({ active: true, onChanged: lib.reload, t });
const [showDup, setShowDup] = useState(false);
const openSave = useSaveToCollectionStore((s) => s.open);
const copyToTrip = useCollectionStore((s) => s.copyToTrip);
const [drop, setDrop] = useState<Drop | null>(null);
@@ -221,6 +386,21 @@ export default function MPlacesLibrary({ categories, language, dark, view, onVie
<ArrowDownUp size={13} strokeWidth={2} className="flex-none" />
</button>
{dup.pairs.length > 0 && (
<button
type="button"
onClick={() => setShowDup(true)}
aria-label={t('collections.duplicates.title')}
className={`${chip(true)} !flex-none px-3`}
>
<CopyCheck size={13} strokeWidth={2} className="flex-none" />
<span>
{dup.pairs.length}
{dup.hasMore ? '+' : ''}
</span>
</button>
)}
{drop && (
<button
type="button"
@@ -233,130 +413,12 @@ export default function MPlacesLibrary({ categories, language, dark, view, onVie
<div
className={`absolute inset-x-0 top-[calc(100%+6px)] z-20 max-h-[300px] overflow-y-auto p-[6px] ${DROP_PANEL}`}
>
{drop === 'kind' &&
(['all', 'trip', 'list'] as const).map((k) => (
<DropRow
key={k}
icon={
k === 'trip' ? (
<Luggage size={15} className="flex-none" />
) : k === 'list' ? (
<Bookmark size={15} className="flex-none" />
) : (
<Globe2 size={15} className="flex-none" />
)
}
label={kindLabel(k)}
count={lib.counts[k]}
on={lib.kind === k}
onPick={() => pick(() => lib.setKind(k))}
/>
))}
{drop === 'status' && (
<>
<DropRow
icon={<Layers size={15} className="flex-none" />}
label={t('collections.status.filterAll')}
on={lib.status === 'all'}
onPick={() => pick(() => lib.setStatus('all'))}
/>
{STATUS_ORDER.map((s: CollectionStatus) => {
const meta = STATUS_SPEC[s];
const Icon = meta.icon;
return (
<DropRow
key={s}
icon={<Icon size={15} className="flex-none" style={{ color: meta.color }} />}
label={t(meta.labelKey)}
on={lib.status === s}
onPick={() => pick(() => lib.setStatus(s))}
/>
);
})}
</>
)}
{drop === 'category' && (
<>
<DropRow
icon={<Shapes size={15} className="flex-none" />}
label={t('collections.status.filterAll')}
on={lib.categoryId === 'all'}
onPick={() => pick(() => lib.setCategoryId('all'))}
/>
{categories.map((c) => {
const meta = categoryMeta(c) ?? UNCATEGORIZED_META;
const Icon = meta.icon;
return (
<DropRow
key={c.id}
icon={<Icon size={15} className="flex-none" style={{ color: meta.color }} />}
label={c.name}
on={lib.categoryId === c.id}
onPick={() => pick(() => lib.setCategoryId(c.id))}
/>
);
})}
</>
)}
{drop === 'sort' &&
(['name', 'updated'] as PlacesLibrarySort[]).map((s) => (
<DropRow
key={s}
icon={<ArrowDownUp size={15} className="flex-none" />}
label={t(s === 'name' ? 'collections.sort.nameAsc' : 'collections.library.sortUpdated')}
on={lib.sort === s}
onPick={() => pick(() => lib.setSort(s))}
/>
))}
<FilterDrop drop={drop} lib={lib} categories={categories} kindLabel={kindLabel} pick={pick} t={t} />
</div>
)}
</div>
{lib.offline ? (
<EmptyNote scene="collections" title={t('collections.library.offline')} />
) : lib.error ? (
<p role="alert" className="mt-3 rounded-xl bg-danger-soft px-3 py-2 text-body text-danger">
{lib.error}
</p>
) : lib.loading && lib.entries.length === 0 ? (
<div className="flex justify-center py-16 text-m-faint">
<Loader2 size={20} className="animate-spin" />
</div>
) : lib.entries.length === 0 ? (
<EmptyNote
scene={lib.filtered ? 'search' : 'collections'}
title={t(lib.filtered ? 'collections.empty.noMatchTitle' : 'collections.library.emptyTitle')}
/>
) : view === 'map' ? (
<div className="mt-3 min-h-0 flex-1 overflow-hidden rounded-2xl border border-m-rowbr">
<CollectionMap
places={map.places}
selectedPlaceId={null}
onOpenPlace={(id) => {
const key = map.keyOf.get(id);
if (key) lib.show(key);
}}
dark={dark}
/>
</div>
) : (
<div className="wide:grid wide:grid-cols-[repeat(auto-fill,minmax(min(100%,380px),1fr))] wide:gap-x-3">
{lib.entries.map((entry) => (
<Row key={entry.key} entry={entry} onOpen={() => lib.show(entry.key)} t={t} />
))}
{lib.hasMore && (
<button
type="button"
onClick={() => void lib.loadMore()}
disabled={lib.loadingMore}
className="mt-3 flex w-full items-center justify-center gap-2 rounded-full border border-m-rowbr bg-m-sheetop py-[10px] text-body font-semibold text-m-ink"
>
{lib.loadingMore && <Loader2 size={15} className="animate-spin" />}
{t('collections.library.more', { count: lib.total - lib.entries.length })}
</button>
)}
</div>
)}
<Results lib={lib} view={view} map={map} dark={dark} t={t} />
<MLibraryPlaceSheet
open={lib.selectedKey != null}
@@ -388,6 +450,7 @@ export default function MPlacesLibrary({ categories, language, dark, view, onVie
}}
t={t}
/>
<MDuplicatesSheet open={showDup} d={dup} onClose={() => setShowDup(false)} t={t} />
<MCollTripPickerSheet
open={copyId != null}
count={1}
+4 -5
View File
@@ -16,6 +16,7 @@ import AddPlaceToCollectionModal from '../components/Collections/AddPlaceToColle
import ImportFromTripModal from '../components/Collections/ImportFromTripModal'
import ImportCollectionModal from '../components/Collections/ImportCollectionModal'
import CollectionPlaceDetail from '../components/Collections/CollectionPlaceDetail'
import { detailDock } from '../components/Collections/detailDock'
import PlacesLibraryView from '../components/Collections/PlacesLibraryView'
import LabelManager from '../components/Collections/LabelManager'
import BulkAssignLabelModal from '../components/Collections/BulkAssignLabelModal'
@@ -83,9 +84,7 @@ function CollectionsPageDesktop(): React.ReactElement {
const desktopSplit = c.isWide && c.hasMappable
// Where the place detail docks: over the list in the split, on the map's start
// edge when the map has the whole width, and as a centred sheet otherwise.
const detailDock = !desktopSplit ? null
: c.view === 'map' ? (c.mapColRect ? { left: c.mapColRect.left + 12, width: Math.min(420, c.mapColRect.width - 24) } : null) // rtl-lint-disable: a measured viewport position, like the list dock
: c.listColRect
const dock = detailDock(desktopSplit, c.view, c.mapColRect, c.listColRect)
const mapShown = c.hasMappable && (c.view === 'map' || c.isWide)
const mapOverlay = c.isWide && mapShown // the map carries the toggle + search
const canAddPlace = typeof c.activeId === 'number' && c.canEdit // a real list you can edit
@@ -277,7 +276,7 @@ function CollectionsPageDesktop(): React.ReactElement {
onView={c.setView}
mapLocked={c.mapLocked}
onToggleMapLocked={c.toggleMapLocked}
navigate={c.navigate}
navigate={(to: string) => void c.navigate(to)}
t={t}
/>
</>
@@ -404,7 +403,7 @@ function CollectionsPageDesktop(): React.ReactElement {
canDelete={c.canDelete}
categories={c.categories}
labels={c.labels}
anchorRect={detailDock}
anchorRect={dock}
onClose={c.handleCloseDetail}
onSetStatus={c.handleDetailStatus}
onSave={patch => c.updatePlace(c.selectedPlace!.id, patch)}
+1 -4
View File
@@ -734,7 +734,4 @@
.trek-dash .col-lrow-caticon { display: inline-flex; flex-shrink: 0; color: var(--cat, var(--accent)); }
.trek-dash .col-lrow-caticon svg { display: block; }
/* The average vote on the tile's other corner: an amber star, as on the map's pins, its figure inside. */
.trek-dash .col-lrow-ratebadge { position: absolute; bottom: -7px; inset-inline-end: -8px; width: 30px; height: 30px; display: grid; place-items: center; }
.trek-dash .col-lrow-ratebadge svg { position: absolute; inset: 0; width: 100%; height: 100%; fill: #fbbf24; stroke: var(--surface); stroke-width: 2; stroke-linejoin: round; }
.trek-dash .col-lrow-ratebadge .n { position: relative; margin-top: 3px; font-size: 10.5px; font-weight: 800; line-height: 1; color: #111; font-variant-numeric: tabular-nums; }
.trek-dash .col-lrow-ratebadge .n.frac { font-size: 8.5px; letter-spacing: -.02em; }
.trek-dash .col-lrow-ratebadge { position: absolute; bottom: -5px; inset-inline-end: -6px; min-width: 20px; height: 20px; padding: 0 4px; border-radius: 10px; display: grid; place-items: center; background: #f59e0b; border: 1.5px solid var(--surface); box-sizing: border-box; font-size: 10px; font-weight: 700; line-height: 1; color: #fff; font-variant-numeric: tabular-nums; white-space: nowrap; text-shadow: 0 1px 1px rgba(0, 0, 0, .45); }