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 -1
View File
@@ -8,7 +8,7 @@
"trek/no-swallowed-catch": 124,
"max-params": 31,
"trek/store-without-selector": 65,
"react-hooks/refs": 522,
"react-hooks/refs": 391,
"react-hooks/set-state-in-effect": 188,
"@typescript-eslint/no-floating-promises": 162,
"react-hooks/exhaustive-deps": 112,
+8 -2
View File
@@ -305,13 +305,19 @@
},
{
"feature": "Places: a place of all places",
"hooks": ["src/components/Collections/libraryDates.ts"],
"hooks": ["src/components/Collections/libraryDates.ts", "src/components/Collections/libraryPairs.ts"],
"desktop": ["src/components/Collections/LibraryPlaceDetail.tsx"],
"mobile": ["src/mobile/screens/collections/MLibraryPlaceSheet.tsx"]
},
{
"feature": "Places: possible duplicates",
"hooks": ["src/components/Collections/DuplicatePairCard.tsx"],
"desktop": ["src/components/Collections/DuplicatesDialog.tsx"],
"mobile": ["src/mobile/screens/collections/MDuplicatesSheet.tsx"]
},
{
"feature": "Places: all places",
"hooks": ["src/components/Collections/usePlacesLibrary.ts"],
"hooks": ["src/components/Collections/usePlacesLibrary.ts", "src/components/Collections/usePlaceDuplicates.ts"],
"desktop": ["src/components/Collections/PlacesLibraryView.tsx"],
"mobile": ["src/mobile/screens/collections/MPlacesLibrary.tsx"]
},
-1
View File
@@ -6,7 +6,6 @@
"components/Collab/CollabChatEmojiPicker.tsx": 3,
"components/Collab/CollabChatReactionBadge.tsx": 3,
"components/Collab/CollabChatReactionMenu.tsx": 1,
"components/Collections/CollectionPlaceDetail.tsx": 2,
"components/Files/FileManagerAvatarChip.tsx": 3,
"components/Journey/JourneyDayJump.tsx": 1,
"components/Journey/JourneyDetailPageDatePicker.tsx": 1,
+1 -1
View File
@@ -1,6 +1,7 @@
{
"components/AtlasGlobe/atlasGlobe.css": 1,
"components/Collections/CollectionMap.tsx": 1,
"components/Collections/detailDock.ts": 2,
"components/Packing/PackingItemDetail.tsx": 1,
"components/Studio/LineHandles.tsx": 1,
"components/Studio/StudioSelectionChrome.tsx": 2,
@@ -8,7 +9,6 @@
"mobile/components/trek3d/MascotClip.tsx": 1,
"mobile/screens/trip/MTripShell.tsx": 1,
"mobile/screens/vacay/MVacay.tsx": 1,
"pages/CollectionsPage.tsx": 1,
"pages/atlas/AtlasGlobeView.tsx": 1,
"pages/tripPlanner/PlanMapStage.tsx": 4
}
@@ -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); }
+32
View File
@@ -1,6 +1,8 @@
import type {
PlacesLibraryDetail,
PlacesLibraryDetailResponse,
PlacesLibraryDuplicate,
PlacesLibraryDuplicateSide,
PlacesLibraryEntry,
PlacesLibraryInfo,
PlacesLibraryListDetail,
@@ -190,3 +192,33 @@ export function threeEntries(): PlacesLibraryEntry[] {
}),
];
}
/** One side of a suggested pair: the Colosseum as one trip place, with its provider ids unset. */
export function duplicateSide(over: Partial<PlacesLibraryDuplicateSide> = {}): PlacesLibraryDuplicateSide {
return {
key: 'trip:42',
identity_id: null,
name: 'Colosseum',
address: 'Piazza del Colosseo',
lat: 41.89,
lng: 12.49,
category: null,
google_place_id: null,
google_ftid: null,
osm_id: null,
origins: [tripOrigin()],
...over,
};
}
/** A suggested pair: the trip's Colosseum and a saved "Colosseo", the same name nearby, mergeable. */
export function duplicatePair(over: Partial<PlacesLibraryDuplicate> = {}): PlacesLibraryDuplicate {
return {
a: duplicateSide(),
b: duplicateSide({ key: 'list:900', name: 'Colosseo', origins: [listOrigin()] }),
reasons: ['name_nearby'],
differing: ['name'],
can_merge: true,
...over,
};
}
+3
View File
@@ -14,6 +14,7 @@ import { useTourMapViewportStore } from '../../src/store/tourMapViewportStore';
import { useTourMapVisibilityStore } from '../../src/store/tourMapVisibilityStore';
import { useTrackMarkToolStore } from '../../src/store/trackMarkToolStore';
import { useTripAddonsStore } from '../../src/store/tripAddonsStore';
import { useTripCollectionsStore } from '../../src/store/tripCollectionsStore';
import { useTripStore } from '../../src/store/tripStore';
import { useVacayStore } from '../../src/store/vacayStore';
@@ -57,6 +58,8 @@ export const RESET_STORES: Record<string, ResettableStore> = {
useMailIngestStore,
// The trip addons per trip, which every trip view reads: a list one test loaded must not decide the next one's tabs.
useTripAddonsStore,
// The lists linked to each trip: one test's links must not show on the next test's trip.
useTripCollectionsStore,
};
/** Not reset so far; moving one into RESET_STORES changes what every file that resets starts from. */
+2 -2
View File
@@ -95,7 +95,7 @@ describe('MBottomNav', () => {
expect(screen.queryByRole('button', { name: 'Atlas' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { expanded: false }));
expect(screen.getByRole('button', { name: /Atlas/ })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Collections/ })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Places/ })).toBeInTheDocument();
});
it('FE-MOB-NAV-006b: the dock keeps Journey next to Vacay when both are enabled', () => {
@@ -214,7 +214,7 @@ describe('MBottomNav', () => {
nav('/dashboard');
fireEvent.click(screen.getByRole('button', { name: 'More' }));
fireEvent.click(screen.getByRole('button', { name: /Collections/ }));
fireEvent.click(screen.getByRole('button', { name: /Places/ }));
expect(at()).toBe('/places');
});
@@ -117,6 +117,7 @@ describe('MCollEditSheet', () => {
name: 'Kopenhagen',
color: SWATCH_COLORS[2],
description: 'Kanaltour',
icon: 'Bookmark',
links: [{ label: 'Tips', url: 'https://visitcopenhagen.com' }],
})
expect(props.onCreated).toHaveBeenCalledWith(11)
@@ -0,0 +1,130 @@
import userEvent from '@testing-library/user-event';
import type { ComponentProps } from 'react';
import { describe, expect, it, vi } from 'vitest';
import { pairKey } from '../../../../src/components/Collections/usePlaceDuplicates';
import { useTranslation } from '../../../../src/i18n';
import MDuplicatesSheet from '../../../../src/mobile/screens/collections/MDuplicatesSheet';
import { duplicatePair, duplicateSide } from '../../../helpers/placesLibrary';
import { render, screen } from '../../../helpers/render';
// FE-MOB-DUPESHEET-001 to FE-MOB-DUPESHEET-012
type Props = ComponentProps<typeof MDuplicatesSheet>;
type Dupes = Props['d'];
const PAIR = duplicatePair();
const OTHER = duplicatePair({
a: duplicateSide({ key: 'trip:7', name: 'Pantheon' }),
b: duplicateSide({ key: 'trip:8', name: 'Pantheon Rome' }),
});
function dupes(over: Partial<Dupes> = {}): Dupes {
return {
pairs: [PAIR, OTHER],
hasMore: false,
loading: false,
busy: null,
lastMerge: null,
merge: vi.fn(() => Promise.resolve()),
dismiss: vi.fn(() => Promise.resolve()),
undo: vi.fn(() => Promise.resolve()),
reload: vi.fn(),
...over,
};
}
function Harness(props: Omit<Props, 't'>) {
const { t } = useTranslation();
return <MDuplicatesSheet {...props} t={t} />;
}
function setup(over: Partial<Dupes> = {}, open = true) {
const onClose = vi.fn();
const d = dupes(over);
const view = render(<Harness open={open} d={d} onClose={onClose} />);
return { ...view, d, onClose };
}
describe('MDuplicatesSheet', () => {
it('FE-MOB-DUPESHEET-001: renders nothing while closed', () => {
setup({}, false);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it('FE-MOB-DUPESHEET-002: opens as a dialog with the title and 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-MOB-DUPESHEET-003: lists a phone-styled card per pair', () => {
setup();
const cards = screen.getAllByRole('article');
expect(cards).toHaveLength(2);
expect(cards[0].className).toContain('bg-m-sheet');
expect(screen.getByText('Pantheon Rome')).toBeInTheDocument();
});
it('FE-MOB-DUPESHEET-004: with no pairs it says there are none', () => {
setup({ pairs: [] });
expect(screen.getByText('No possible duplicates.')).toBeInTheDocument();
expect(screen.queryByRole('article')).not.toBeInTheDocument();
});
it('FE-MOB-DUPESHEET-005: while loading with nothing yet it shows a spinner, not the empty note', () => {
setup({ pairs: [], loading: true });
expect(screen.queryByText('No possible duplicates.')).not.toBeInTheDocument();
expect(document.querySelector('.animate-spin')).not.toBeNull();
});
it('FE-MOB-DUPESHEET-006: tells that more 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-MOB-DUPESHEET-007: keeping a side merges that pair with that side leading', async () => {
const user = userEvent.setup();
const { d } = setup();
await user.click(screen.getAllByRole('button', { name: /Keep this one/ })[3]);
expect(d.merge).toHaveBeenCalledWith(OTHER, 'b');
});
it('FE-MOB-DUPESHEET-008: "Not the same place" dismisses that pair', async () => {
const user = userEvent.setup();
const { d } = setup();
await user.click(screen.getAllByRole('button', { name: 'Not the same place' })[0]);
expect(d.dismiss).toHaveBeenCalledWith(PAIR);
});
it('FE-MOB-DUPESHEET-009: only the pair being worked on is busy', () => {
setup({ busy: pairKey(OTHER) });
const [first, second] = screen.getAllByRole('article');
for (const button of first.querySelectorAll('button')) expect(button).toBeEnabled();
for (const button of second.querySelectorAll('button')) expect(button).toBeDisabled();
});
it('FE-MOB-DUPESHEET-010: 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 { d } = setup({ lastMerge: { id: 4, name: 'Colosseo' } });
await user.click(screen.getByRole('button', { name: 'Separate Colosseo again' }));
expect(d.undo).toHaveBeenCalledTimes(1);
});
it('FE-MOB-DUPESHEET-011: the undo button is disabled while the undo runs', () => {
setup({ lastMerge: { id: 4, name: 'Colosseo' }, busy: 'undo' });
expect(screen.getByRole('button', { name: 'Separate Colosseo again' })).toBeDisabled();
});
it('FE-MOB-DUPESHEET-012: the close button closes the sheet', async () => {
const user = userEvent.setup();
const { onClose } = setup();
await user.click(screen.getByRole('button', { name: 'Close' }));
expect(onClose).toHaveBeenCalledTimes(1);
});
});
@@ -40,6 +40,21 @@ vi.mock('../../../../src/components/Collections/usePlacesLibrary', () => ({
}));
// Keep the map stack out of jsdom; what the screen hands it is the contract.
// The review of possible duplicates has its own tests; here it has none to offer.
vi.mock('../../../../src/components/Collections/usePlaceDuplicates', () => ({
usePlaceDuplicates: () => ({
pairs: [],
hasMore: false,
loading: false,
busy: null,
lastMerge: null,
merge: vi.fn(),
dismiss: vi.fn(),
undo: vi.fn(),
reload: vi.fn(),
}),
}));
vi.mock('../../../../src/components/Collections/CollectionMap', () => ({
default: (props: MapProps) => {
seen.map = props;
+18
View File
@@ -152,6 +152,24 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'بمتوسط تقييم {rating}',
'collections.allSaved': 'كل المحفوظات',
'collections.myLists': 'قوائمي',
'collections.duplicates.title': 'تكرارات محتملة',
'collections.duplicates.sub':
'تبدو هذه الأماكن مكانًا واحدًا. احتفظ بأحد الجانبين لدمجهما في مكان واحد لك؛ تبقى رحلاتك وقوائمك كما هي.',
'collections.duplicates.button': '{count} تكرار',
'collections.duplicates.button.zero': 'لا تكرارات',
'collections.duplicates.button.one': 'تكرار واحد',
'collections.duplicates.button.two': 'تكراران',
'collections.duplicates.button.few': '{count} تكرارات',
'collections.duplicates.button.many': '{count} تكرارًا',
'collections.duplicates.keepThis': 'احتفظ بهذا',
'collections.duplicates.sameProvider': 'المكان نفسه لدى مزوّد الخريطة',
'collections.duplicates.sameNameNearby': 'الاسم نفسه في الموقع نفسه',
'collections.duplicates.cannotMerge': 'أحد الجانبين في رحلة أو قائمة لم يعد بإمكانك فتحها، لذا لا يمكن دمجهما.',
'collections.duplicates.notSame': 'ليس المكان نفسه',
'collections.duplicates.noAddress': 'بلا عنوان',
'collections.duplicates.undo': 'افصل {name} مرة أخرى',
'collections.duplicates.none': 'لا توجد تكرارات محتملة.',
'collections.duplicates.more': 'ستظهر المزيد بعد أن تنتهي من هذه.',
'collections.allSavedSubtitle': 'كل مكان حفظته، من جميع قوائمك معًا.',
'collections.library.title': 'كل الأماكن',
'collections.library.eyebrow': 'أماكني',
+15
View File
@@ -104,6 +104,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Orta qiymət: {rating}',
'collections.allSaved': 'Bütün saxlanılanlar',
'collections.myLists': 'Siyahılarım',
'collections.duplicates.title': 'Mümkün təkrarlar',
'collections.duplicates.sub':
'Bu yerlər eyni görünür. Bir tərəfi saxla, onda hər ikisi sənin üçün tək yer sayılacaq; səyahətlərin və siyahıların olduğu kimi qalır.',
'collections.duplicates.button': '{count} təkrar',
'collections.duplicates.button.one': '{count} təkrar',
'collections.duplicates.keepThis': 'Bunu saxla',
'collections.duplicates.sameProvider': 'Xəritə provayderində eyni yer',
'collections.duplicates.sameNameNearby': 'Eyni yerdə eyni ad',
'collections.duplicates.cannotMerge':
'Tərəflərdən biri artıq aça bilmədiyin bir səyahətdə və ya siyahıdadır, buna görə birləşdirmək olmur.',
'collections.duplicates.notSame': 'Eyni yer deyil',
'collections.duplicates.noAddress': 'Ünvan yoxdur',
'collections.duplicates.undo': '{name} yenidən ayrılsın',
'collections.duplicates.none': 'Mümkün təkrar yoxdur.',
'collections.duplicates.more': 'Bunları bitirdikdən sonra daha çoxu görünəcək.',
'collections.allSavedSubtitle': 'Saxladığınız hər məkan, bütün siyahılarınızdan birlikdə.',
'collections.library.title': 'Bütün məkanlar',
'collections.library.eyebrow': 'Məkanlarım',
+15
View File
@@ -104,6 +104,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Nota média {rating}',
'collections.allSaved': 'Todos os salvos',
'collections.myLists': 'Minhas listas',
'collections.duplicates.title': 'Possíveis duplicados',
'collections.duplicates.sub':
'Estes lugares parecem ser um só. Mantenha um dos lados para agrupar os dois como um único lugar seu; suas viagens e listas continuam como estão.',
'collections.duplicates.button': '{count} duplicados',
'collections.duplicates.button.one': '{count} duplicado',
'collections.duplicates.keepThis': 'Manter este',
'collections.duplicates.sameProvider': 'O mesmo lugar no provedor de mapas',
'collections.duplicates.sameNameNearby': 'O mesmo nome no mesmo ponto',
'collections.duplicates.cannotMerge':
'Um dos lados está em uma viagem ou lista que você não consegue mais abrir, então não dá para agrupá-los.',
'collections.duplicates.notSame': 'Não é o mesmo lugar',
'collections.duplicates.noAddress': 'Sem endereço',
'collections.duplicates.undo': 'Separar {name} novamente',
'collections.duplicates.none': 'Nenhum possível duplicado.',
'collections.duplicates.more': 'Mais aparecem quando você terminar estes.',
'collections.allSavedSubtitle': 'Todos os lugares que você salvou, de todas as suas listas juntas.',
'collections.library.title': 'Todos os lugares',
'collections.library.eyebrow': 'Meus lugares',
+15
View File
@@ -103,6 +103,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Valoració mitjana de {rating}',
'collections.allSaved': 'Tot el desat',
'collections.myLists': 'Les meves llistes',
'collections.duplicates.title': 'Possibles duplicats',
'collections.duplicates.sub':
'Aquests llocs semblen un de sol. Conserva un dels dos costats per agrupar-los com un únic lloc teu; els teus viatges i llistes es queden tal com són.',
'collections.duplicates.button': '{count} duplicats',
'collections.duplicates.button.one': '{count} duplicat',
'collections.duplicates.keepThis': 'Conserva aquest',
'collections.duplicates.sameProvider': 'El mateix lloc al proveïdor de mapes',
'collections.duplicates.sameNameNearby': 'El mateix nom al mateix indret',
'collections.duplicates.cannotMerge':
'Un dels costats és en un viatge o una llista que ja no pots obrir, així que no es poden agrupar.',
'collections.duplicates.notSame': 'No és el mateix lloc',
'collections.duplicates.noAddress': 'Sense adreça',
'collections.duplicates.undo': 'Torna a separar {name}',
'collections.duplicates.none': 'No hi ha possibles duplicats.',
'collections.duplicates.more': 'En sortiran més quan acabis amb aquests.',
'collections.allSavedSubtitle': 'Tots els llocs que has desat, de totes les teves llistes junts.',
'collections.library.title': 'Tots els llocs',
'collections.library.eyebrow': 'Els meus llocs',
+16
View File
@@ -115,6 +115,22 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Průměrné hodnocení {rating}',
'collections.allSaved': 'Vše uložené',
'collections.myLists': 'Moje seznamy',
'collections.duplicates.title': 'Možné duplikáty',
'collections.duplicates.sub':
'Tato místa vypadají jako jedno. Ponechte jednu stranu a obě se budou počítat jako jedno vaše místo; vaše cesty a seznamy zůstanou beze změny.',
'collections.duplicates.button': '{count} duplikátů',
'collections.duplicates.button.one': '{count} duplikát',
'collections.duplicates.button.few': '{count} duplikáty',
'collections.duplicates.keepThis': 'Ponechat toto',
'collections.duplicates.sameProvider': 'Stejné místo u poskytovatele map',
'collections.duplicates.sameNameNearby': 'Stejný název na stejném místě',
'collections.duplicates.cannotMerge':
'Jedna strana je v cestě nebo seznamu, který už nemůžete otevřít, proto je nelze sloučit.',
'collections.duplicates.notSame': 'Není to stejné místo',
'collections.duplicates.noAddress': 'Bez adresy',
'collections.duplicates.undo': 'Znovu oddělit {name}',
'collections.duplicates.none': 'Žádné možné duplikáty.',
'collections.duplicates.more': 'Další se objeví, až tyto vyřídíte.',
'collections.allSavedSubtitle': 'Každé místo, které jste uložili, ze všech vašich seznamů dohromady.',
'collections.library.title': 'Všechna místa',
'collections.library.eyebrow': 'Moje místa',
+15
View File
@@ -104,6 +104,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Im Schnitt mit {rating} bewertet',
'collections.allSaved': 'Alle gespeicherten',
'collections.myLists': 'Meine Listen',
'collections.duplicates.title': 'Mögliche Doppelte',
'collections.duplicates.sub':
'Diese Orte sehen nach einem aus. Behalte eine Seite, dann gelten beide als ein Ort für dich; deine Reisen und Listen bleiben, wie sie sind.',
'collections.duplicates.button': '{count} doppelt',
'collections.duplicates.button.one': '{count} doppelt',
'collections.duplicates.keepThis': 'Diesen behalten',
'collections.duplicates.sameProvider': 'Derselbe Ort beim Kartenanbieter',
'collections.duplicates.sameNameNearby': 'Gleicher Name an derselben Stelle',
'collections.duplicates.cannotMerge':
'Eine Seite liegt in einem Trip oder einer Liste, die du nicht mehr öffnen kannst. Deshalb lassen sie sich nicht zusammenführen.',
'collections.duplicates.notSame': 'Nicht derselbe Ort',
'collections.duplicates.noAddress': 'Ohne Adresse',
'collections.duplicates.undo': '{name} wieder trennen',
'collections.duplicates.none': 'Keine möglichen Doppelten.',
'collections.duplicates.more': 'Weitere erscheinen, sobald du diese erledigt hast.',
'collections.allSavedSubtitle': 'Jeder Ort, den du gespeichert hast, aus all deinen Listen zusammen.',
'collections.library.title': 'Alle Orte',
'collections.library.eyebrow': 'Meine Orte',
+15
View File
@@ -104,6 +104,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Rated {rating} on average',
'collections.allSaved': 'All saved',
'collections.myLists': 'My lists',
'collections.duplicates.title': 'Possible duplicates',
'collections.duplicates.sub':
'These places look like one. Keep one side to group both as one place of yours; your trips and lists stay as they are.',
'collections.duplicates.button': '{count} duplicates',
'collections.duplicates.button.one': '{count} duplicate',
'collections.duplicates.keepThis': 'Keep this one',
'collections.duplicates.sameProvider': 'The same place on the map provider',
'collections.duplicates.sameNameNearby': 'The same name at the same spot',
'collections.duplicates.cannotMerge':
'One side is in a trip or list you can no longer open, so these cannot be grouped.',
'collections.duplicates.notSame': 'Not the same place',
'collections.duplicates.noAddress': 'No address',
'collections.duplicates.undo': 'Separate {name} again',
'collections.duplicates.none': 'No possible duplicates.',
'collections.duplicates.more': 'More show up once you are through these.',
'collections.allSavedSubtitle': 'Every place you saved, from all your lists together.',
'collections.library.title': 'All places',
'collections.library.eyebrow': 'Places',
+15
View File
@@ -104,6 +104,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Valoración media de {rating}',
'collections.allSaved': 'Todos los guardados',
'collections.myLists': 'Mis listas',
'collections.duplicates.title': 'Posibles duplicados',
'collections.duplicates.sub':
'Estos lugares parecen ser uno solo. Conserva un lado para agrupar ambos como un único lugar tuyo; tus viajes y listas se quedan como están.',
'collections.duplicates.button': '{count} duplicados',
'collections.duplicates.button.one': '{count} duplicado',
'collections.duplicates.keepThis': 'Conservar este',
'collections.duplicates.sameProvider': 'El mismo lugar en el proveedor de mapas',
'collections.duplicates.sameNameNearby': 'El mismo nombre en el mismo sitio',
'collections.duplicates.cannotMerge':
'Un lado está en un viaje o una lista que ya no puedes abrir, así que no se pueden agrupar.',
'collections.duplicates.notSame': 'No es el mismo lugar',
'collections.duplicates.noAddress': 'Sin dirección',
'collections.duplicates.undo': 'Volver a separar {name}',
'collections.duplicates.none': 'No hay posibles duplicados.',
'collections.duplicates.more': 'Aparecerán más cuando termines con estos.',
'collections.allSavedSubtitle': 'Todos los lugares que guardaste, de todas tus listas juntas.',
'collections.library.title': 'Todos los lugares',
'collections.library.eyebrow': 'Mis lugares',
+15
View File
@@ -104,6 +104,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Keskmine hinne {rating}',
'collections.allSaved': 'Kõik salvestatud',
'collections.myLists': 'Minu nimekirjad',
'collections.duplicates.title': 'Võimalikud duplikaadid',
'collections.duplicates.sub':
'Need kohad paistavad olevat üks ja sama. Jäta üks pool alles, siis loetakse mõlemad sinu jaoks üheks kohaks; sinu reisid ja nimekirjad jäävad nagu on.',
'collections.duplicates.button': '{count} duplikaati',
'collections.duplicates.button.one': '{count} duplikaat',
'collections.duplicates.keepThis': 'Jäta see alles',
'collections.duplicates.sameProvider': 'Sama koht kaardiplatvormil',
'collections.duplicates.sameNameNearby': 'Sama nimi samas kohas',
'collections.duplicates.cannotMerge':
'Üks pool on reisis või nimekirjas, mida sa enam avada ei saa, seega neid ei saa ühendada.',
'collections.duplicates.notSame': 'Pole sama koht',
'collections.duplicates.noAddress': 'Aadress puudub',
'collections.duplicates.undo': 'Eralda {name} uuesti',
'collections.duplicates.none': 'Võimalikke duplikaate pole.',
'collections.duplicates.more': 'Veel ilmub, kui need on tehtud.',
'collections.allSavedSubtitle': 'Iga koht, mille oled salvestanud, kõigist sinu nimekirjadest koos.',
'collections.library.title': 'Kõik kohad',
'collections.library.eyebrow': 'Minu kohad',
+15
View File
@@ -105,6 +105,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Note moyenne de {rating}',
'collections.allSaved': 'Tous les enregistrés',
'collections.myLists': 'Mes listes',
'collections.duplicates.title': 'Doublons possibles',
'collections.duplicates.sub':
"Ces lieux semblent n'en faire qu'un. Gardez un côté pour les regrouper en un seul lieu à vous ; vos voyages et vos listes restent tels quels.",
'collections.duplicates.button': '{count} doublons',
'collections.duplicates.button.one': '{count} doublon',
'collections.duplicates.keepThis': 'Garder celui-ci',
'collections.duplicates.sameProvider': 'Le même lieu chez le fournisseur de cartes',
'collections.duplicates.sameNameNearby': 'Le même nom au même endroit',
'collections.duplicates.cannotMerge':
'Un côté se trouve dans un voyage ou une liste que vous ne pouvez plus ouvrir, ils ne peuvent donc pas être regroupés.',
'collections.duplicates.notSame': 'Pas le même lieu',
'collections.duplicates.noAddress': 'Sans adresse',
'collections.duplicates.undo': 'Séparer à nouveau {name}',
'collections.duplicates.none': 'Aucun doublon possible.',
'collections.duplicates.more': "D'autres apparaîtront une fois ceux-ci traités.",
'collections.allSavedSubtitle': 'Chaque lieu enregistré, toutes vos listes réunies.',
'collections.library.title': 'Tous les lieux',
'collections.library.eyebrow': 'Mes lieux',
+15
View File
@@ -105,6 +105,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Μέση βαθμολογία {rating}',
'collections.allSaved': 'Όλα τα αποθηκευμένα',
'collections.myLists': 'Οι λίστες μου',
'collections.duplicates.title': 'Πιθανά διπλότυπα',
'collections.duplicates.sub':
'Αυτά τα μέρη μοιάζουν να είναι ένα. Κράτησε τη μία πλευρά και τα δύο θα μετράνε ως ένα μέρος σου· τα ταξίδια και οι λίστες σου μένουν όπως είναι.',
'collections.duplicates.button': '{count} διπλότυπα',
'collections.duplicates.button.one': '{count} διπλότυπο',
'collections.duplicates.keepThis': 'Κράτα αυτό',
'collections.duplicates.sameProvider': 'Το ίδιο μέρος στον πάροχο χαρτών',
'collections.duplicates.sameNameNearby': 'Το ίδιο όνομα στο ίδιο σημείο',
'collections.duplicates.cannotMerge':
'Η μία πλευρά βρίσκεται σε ταξίδι ή λίστα που δεν μπορείς πια να ανοίξεις, οπότε δεν μπορούν να ενωθούν.',
'collections.duplicates.notSame': 'Δεν είναι το ίδιο μέρος',
'collections.duplicates.noAddress': 'Χωρίς διεύθυνση',
'collections.duplicates.undo': 'Διαχώρισε ξανά το {name}',
'collections.duplicates.none': 'Δεν υπάρχουν πιθανά διπλότυπα.',
'collections.duplicates.more': 'Θα εμφανιστούν κι άλλα όταν τελειώσεις με αυτά.',
'collections.allSavedSubtitle': 'Κάθε μέρος που έχεις αποθηκεύσει, από όλες τις λίστες σου μαζί.',
'collections.library.title': 'Όλα τα μέρη',
'collections.library.eyebrow': 'Τα μέρη μου',
+15
View File
@@ -113,6 +113,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'דירוג ממוצע {rating}',
'collections.allSaved': 'כל השמורים',
'collections.myLists': 'הרשימות שלי',
'collections.duplicates.title': 'כפילויות אפשריות',
'collections.duplicates.sub':
'המקומות האלה נראים כמו מקום אחד. השאר צד אחד וכך שניהם ייחשבו למקום אחד שלך; הטיולים והרשימות שלך נשארים כפי שהם.',
'collections.duplicates.button': '{count} כפילויות',
'collections.duplicates.button.one': 'כפילות אחת',
'collections.duplicates.button.two': 'שתי כפילויות',
'collections.duplicates.keepThis': 'השאר את זה',
'collections.duplicates.sameProvider': 'אותו מקום אצל ספק המפות',
'collections.duplicates.sameNameNearby': 'אותו שם באותה נקודה',
'collections.duplicates.cannotMerge': 'אחד הצדדים נמצא בטיול או ברשימה שאי אפשר לפתוח יותר, ולכן אי אפשר לאחד אותם.',
'collections.duplicates.notSame': 'לא אותו מקום',
'collections.duplicates.noAddress': 'ללא כתובת',
'collections.duplicates.undo': 'הפרד שוב את {name}',
'collections.duplicates.none': 'אין כפילויות אפשריות.',
'collections.duplicates.more': 'עוד יופיעו אחרי שתסיים עם אלה.',
'collections.allSavedSubtitle': 'כל מקום ששמרתם, מכל הרשימות שלכם יחד.',
'collections.library.title': 'כל המקומות',
'collections.library.eyebrow': 'המקומות שלי',
+15
View File
@@ -104,6 +104,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Átlagos értékelés: {rating}',
'collections.allSaved': 'Összes mentett',
'collections.myLists': 'Listáim',
'collections.duplicates.title': 'Lehetséges duplikátumok',
'collections.duplicates.sub':
'Ezek a helyek egynek tűnnek. Tartsd meg az egyik oldalt, és mindkettő egy helyként számít nálad; az utazásaid és listáid változatlanok maradnak.',
'collections.duplicates.button': '{count} duplikátum',
'collections.duplicates.button.one': '{count} duplikátum',
'collections.duplicates.keepThis': 'Ezt tartom meg',
'collections.duplicates.sameProvider': 'Ugyanaz a hely a térképszolgáltatónál',
'collections.duplicates.sameNameNearby': 'Ugyanaz a név ugyanazon a ponton',
'collections.duplicates.cannotMerge':
'Az egyik oldal olyan utazásban vagy listában van, amelyet már nem tudsz megnyitni, ezért nem vonhatók össze.',
'collections.duplicates.notSame': 'Nem ugyanaz a hely',
'collections.duplicates.noAddress': 'Nincs cím',
'collections.duplicates.undo': '{name} szétválasztása újra',
'collections.duplicates.none': 'Nincs lehetséges duplikátum.',
'collections.duplicates.more': 'Továbbiak jelennek meg, ha ezekkel végeztél.',
'collections.allSavedSubtitle': 'Minden elmentett hely, az összes listádból együtt.',
'collections.library.title': 'Minden hely',
'collections.library.eyebrow': 'Helyeim',
+14
View File
@@ -92,6 +92,20 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Rata-rata dinilai {rating}',
'collections.allSaved': 'Semua tersimpan',
'collections.myLists': 'Daftarku',
'collections.duplicates.title': 'Kemungkinan duplikat',
'collections.duplicates.sub':
'Tempat-tempat ini tampak sama. Pertahankan salah satu sisi agar keduanya dianggap satu tempat milikmu; perjalanan dan daftarmu tetap seperti semula.',
'collections.duplicates.button': '{count} duplikat',
'collections.duplicates.keepThis': 'Pertahankan yang ini',
'collections.duplicates.sameProvider': 'Tempat yang sama di penyedia peta',
'collections.duplicates.sameNameNearby': 'Nama yang sama di lokasi yang sama',
'collections.duplicates.cannotMerge':
'Salah satu sisi ada di perjalanan atau daftar yang tidak bisa lagi kamu buka, jadi keduanya tidak bisa digabungkan.',
'collections.duplicates.notSame': 'Bukan tempat yang sama',
'collections.duplicates.noAddress': 'Tanpa alamat',
'collections.duplicates.undo': 'Pisahkan {name} lagi',
'collections.duplicates.none': 'Tidak ada kemungkinan duplikat.',
'collections.duplicates.more': 'Akan muncul lebih banyak setelah kamu selesai dengan ini.',
'collections.allSavedSubtitle': 'Semua tempat yang kamu simpan, dari seluruh daftarmu sekaligus.',
'collections.library.title': 'Semua tempat',
'collections.library.eyebrow': 'Tempatku',
+15
View File
@@ -104,6 +104,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Valutazione media di {rating}',
'collections.allSaved': 'Tutti i salvati',
'collections.myLists': 'Le mie liste',
'collections.duplicates.title': 'Possibili duplicati',
'collections.duplicates.sub':
'Questi luoghi sembrano uno solo. Tieni un lato per raggrupparli come un unico luogo tuo; i tuoi viaggi e le tue liste restano come sono.',
'collections.duplicates.button': '{count} duplicati',
'collections.duplicates.button.one': '{count} duplicato',
'collections.duplicates.keepThis': 'Tieni questo',
'collections.duplicates.sameProvider': 'Lo stesso luogo presso il fornitore di mappe',
'collections.duplicates.sameNameNearby': 'Lo stesso nome nello stesso punto',
'collections.duplicates.cannotMerge':
'Un lato si trova in un viaggio o in una lista che non puoi più aprire, quindi non possono essere raggruppati.',
'collections.duplicates.notSame': 'Non è lo stesso luogo',
'collections.duplicates.noAddress': 'Senza indirizzo',
'collections.duplicates.undo': 'Separa di nuovo {name}',
'collections.duplicates.none': 'Nessun possibile duplicato.',
'collections.duplicates.more': 'Ne compariranno altri quando avrai finito con questi.',
'collections.allSavedSubtitle': 'Ogni luogo che hai salvato, da tutte le tue liste insieme.',
'collections.library.title': 'Tutti i luoghi',
'collections.library.eyebrow': 'I miei luoghi',
+13
View File
@@ -90,6 +90,19 @@ const collection: TranslationStrings = {
'collections.ratingBadge': '平均評価 {rating}',
'collections.allSaved': 'すべての保存済み',
'collections.myLists': 'マイリスト',
'collections.duplicates.title': '重複の可能性',
'collections.duplicates.sub':
'これらの場所は同じ場所のようです。片方を残すと、2つをまとめて1つの場所として扱います。旅行やリストはそのままです。',
'collections.duplicates.button': '{count}件の重複',
'collections.duplicates.keepThis': 'こちらを残す',
'collections.duplicates.sameProvider': '地図プロバイダ上の同じ場所',
'collections.duplicates.sameNameNearby': '同じ地点の同じ名前',
'collections.duplicates.cannotMerge': '片方が開けなくなった旅行またはリストに入っているため、まとめられません。',
'collections.duplicates.notSame': '同じ場所ではない',
'collections.duplicates.noAddress': '住所なし',
'collections.duplicates.undo': '{name}を再び分ける',
'collections.duplicates.none': '重複の可能性はありません。',
'collections.duplicates.more': 'これらを片付けると、さらに表示されます。',
'collections.allSavedSubtitle': '保存したすべての場所を、すべてのリストをまとめて表示します。',
'collections.library.title': 'すべての場所',
'collections.library.eyebrow': 'マイプレイス',
+13
View File
@@ -91,6 +91,19 @@ const collection: TranslationStrings = {
'collections.ratingBadge': '평균 평점 {rating}',
'collections.allSaved': '모든 저장 항목',
'collections.myLists': '내 목록',
'collections.duplicates.title': '중복 가능성',
'collections.duplicates.sub':
'이 장소들은 같은 곳으로 보입니다. 한쪽을 남기면 둘이 하나의 장소로 묶입니다. 여행과 목록은 그대로 유지됩니다.',
'collections.duplicates.button': '중복 {count}개',
'collections.duplicates.keepThis': '이것 남기기',
'collections.duplicates.sameProvider': '지도 제공업체의 같은 장소',
'collections.duplicates.sameNameNearby': '같은 위치의 같은 이름',
'collections.duplicates.cannotMerge': '한쪽이 더 이상 열 수 없는 여행이나 목록에 있어서 묶을 수 없습니다.',
'collections.duplicates.notSame': '같은 장소 아님',
'collections.duplicates.noAddress': '주소 없음',
'collections.duplicates.undo': '{name} 다시 분리',
'collections.duplicates.none': '중복 가능성이 없습니다.',
'collections.duplicates.more': '이 항목들을 처리하면 더 표시됩니다.',
'collections.allSavedSubtitle': '저장한 모든 장소를 모든 목록에서 한데 모아 보여 줍니다.',
'collections.library.title': '모든 장소',
'collections.library.eyebrow': '내 장소',
+15
View File
@@ -104,6 +104,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Gemiddeld beoordeeld met {rating}',
'collections.allSaved': 'Alle opgeslagen',
'collections.myLists': 'Mijn lijsten',
'collections.duplicates.title': 'Mogelijke dubbele plaatsen',
'collections.duplicates.sub':
'Deze plaatsen lijken één en dezelfde. Houd één kant aan, dan tellen beide als één plaats van jou; je reizen en lijsten blijven zoals ze zijn.',
'collections.duplicates.button': '{count} dubbel',
'collections.duplicates.button.one': '{count} dubbel',
'collections.duplicates.keepThis': 'Deze houden',
'collections.duplicates.sameProvider': 'Dezelfde plaats bij de kaartaanbieder',
'collections.duplicates.sameNameNearby': 'Dezelfde naam op dezelfde plek',
'collections.duplicates.cannotMerge':
'Eén kant staat in een reis of lijst die je niet meer kunt openen, dus ze kunnen niet worden samengevoegd.',
'collections.duplicates.notSame': 'Niet dezelfde plaats',
'collections.duplicates.noAddress': 'Geen adres',
'collections.duplicates.undo': '{name} weer splitsen',
'collections.duplicates.none': 'Geen mogelijke dubbele plaatsen.',
'collections.duplicates.more': 'Er komen er meer bij zodra je deze hebt afgehandeld.',
'collections.allSavedSubtitle': 'Elke plek die je hebt opgeslagen, uit al je lijsten samen.',
'collections.library.title': 'Alle plekken',
'collections.library.eyebrow': 'Mijn plekken',
+17
View File
@@ -128,6 +128,23 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Średnia ocena {rating}',
'collections.allSaved': 'Wszystkie zapisane',
'collections.myLists': 'Moje listy',
'collections.duplicates.title': 'Możliwe duplikaty',
'collections.duplicates.sub':
'Te miejsca wyglądają na jedno. Zachowaj jedną stronę, a obie będą liczyć się jako jedno Twoje miejsce; Twoje podróże i listy pozostają bez zmian.',
'collections.duplicates.button': '{count} duplikatu',
'collections.duplicates.button.one': '{count} duplikat',
'collections.duplicates.button.few': '{count} duplikaty',
'collections.duplicates.button.many': '{count} duplikatów',
'collections.duplicates.keepThis': 'Zachowaj to',
'collections.duplicates.sameProvider': 'To samo miejsce u dostawcy map',
'collections.duplicates.sameNameNearby': 'Ta sama nazwa w tym samym miejscu',
'collections.duplicates.cannotMerge':
'Jedna strona jest w podróży lub na liście, której już nie możesz otworzyć, więc nie można ich połączyć.',
'collections.duplicates.notSame': 'To nie to samo miejsce',
'collections.duplicates.noAddress': 'Brak adresu',
'collections.duplicates.undo': 'Rozdziel {name} ponownie',
'collections.duplicates.none': 'Brak możliwych duplikatów.',
'collections.duplicates.more': 'Kolejne pojawią się, gdy skończysz z tymi.',
'collections.allSavedSubtitle': 'Każde zapisane miejsce, ze wszystkich Twoich list razem.',
'collections.library.title': 'Wszystkie miejsca',
'collections.library.eyebrow': 'Moje miejsca',
+17
View File
@@ -127,6 +127,23 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Средняя оценка {rating}',
'collections.allSaved': 'Все сохранённые',
'collections.myLists': 'Мои списки',
'collections.duplicates.title': 'Возможные дубликаты',
'collections.duplicates.sub':
'Эти места похожи на одно. Оставьте одну сторону, и оба будут считаться одним вашим местом; ваши поездки и списки останутся как есть.',
'collections.duplicates.button': '{count} дубликата',
'collections.duplicates.button.one': '{count} дубликат',
'collections.duplicates.button.few': '{count} дубликата',
'collections.duplicates.button.many': '{count} дубликатов',
'collections.duplicates.keepThis': 'Оставить это',
'collections.duplicates.sameProvider': 'То же место у поставщика карт',
'collections.duplicates.sameNameNearby': 'То же название в том же месте',
'collections.duplicates.cannotMerge':
'Одна сторона находится в поездке или списке, которые вы больше не можете открыть, поэтому их нельзя объединить.',
'collections.duplicates.notSame': 'Это не одно и то же место',
'collections.duplicates.noAddress': 'Без адреса',
'collections.duplicates.undo': 'Снова разделить {name}',
'collections.duplicates.none': 'Возможных дубликатов нет.',
'collections.duplicates.more': 'Появятся другие, когда вы разберётесь с этими.',
'collections.allSavedSubtitle': 'Каждое сохранённое место из всех ваших списков вместе.',
'collections.library.title': 'Все места',
'collections.library.eyebrow': 'Мои места',
+16
View File
@@ -116,6 +116,22 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Priemerné hodnotenie {rating}',
'collections.allSaved': 'Všetko uložené',
'collections.myLists': 'Moje zoznamy',
'collections.duplicates.title': 'Možné duplikáty',
'collections.duplicates.sub':
'Tieto miesta vyzerajú ako jedno. Ponechajte jednu stranu a obe sa budú počítať ako jedno vaše miesto; vaše cesty a zoznamy zostanú bez zmeny.',
'collections.duplicates.button': '{count} duplikátov',
'collections.duplicates.button.one': '{count} duplikát',
'collections.duplicates.button.few': '{count} duplikáty',
'collections.duplicates.keepThis': 'Ponechať toto',
'collections.duplicates.sameProvider': 'Rovnaké miesto u poskytovateľa máp',
'collections.duplicates.sameNameNearby': 'Rovnaký názov na rovnakom mieste',
'collections.duplicates.cannotMerge':
'Jedna strana je v ceste alebo zozname, ktorý už nemôžete otvoriť, preto ich nemožno zlúčiť.',
'collections.duplicates.notSame': 'Nie je to to isté miesto',
'collections.duplicates.noAddress': 'Bez adresy',
'collections.duplicates.undo': 'Znova oddeliť {name}',
'collections.duplicates.none': 'Žiadne možné duplikáty.',
'collections.duplicates.more': 'Ďalšie sa zobrazia, keď tieto vybavíte.',
'collections.allSavedSubtitle': 'Každé uložené miesto zo všetkých vašich zoznamov dokopy.',
'collections.library.title': 'Všetky miesta',
'collections.library.eyebrow': 'Moje miesta',
+15
View File
@@ -103,6 +103,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Betyg {rating} i snitt',
'collections.allSaved': 'Alla sparade',
'collections.myLists': 'Mina listor',
'collections.duplicates.title': 'Möjliga dubbletter',
'collections.duplicates.sub':
'De här platserna ser ut som en och samma. Behåll en sida, så räknas båda som en plats hos dig; dina resor och listor förblir som de är.',
'collections.duplicates.button': '{count} dubbletter',
'collections.duplicates.button.one': '{count} dubblett',
'collections.duplicates.keepThis': 'Behåll den här',
'collections.duplicates.sameProvider': 'Samma plats hos kartleverantören',
'collections.duplicates.sameNameNearby': 'Samma namn på samma ställe',
'collections.duplicates.cannotMerge':
'Den ena sidan finns i en resa eller lista som du inte längre kan öppna, så de kan inte slås ihop.',
'collections.duplicates.notSame': 'Inte samma plats',
'collections.duplicates.noAddress': 'Ingen adress',
'collections.duplicates.undo': 'Separera {name} igen',
'collections.duplicates.none': 'Inga möjliga dubbletter.',
'collections.duplicates.more': 'Fler dyker upp när du är klar med de här.',
'collections.allSavedSubtitle': 'Varje plats du har sparat, från alla dina listor samlade.',
'collections.library.title': 'Alla platser',
'collections.library.eyebrow': 'Mina platser',
+13
View File
@@ -89,6 +89,19 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'คะแนนเฉลี่ย {rating}',
'collections.allSaved': 'บันทึกทั้งหมดแล้ว',
'collections.myLists': 'รายการของฉัน',
'collections.duplicates.title': 'สถานที่ที่อาจซ้ำกัน',
'collections.duplicates.sub':
'สถานที่เหล่านี้ดูเหมือนที่เดียวกัน เก็บไว้ฝั่งใดฝั่งหนึ่ง แล้วทั้งสองจะถูกรวมเป็นสถานที่เดียวของคุณ ส่วนทริปและรายการของคุณยังคงเหมือนเดิม',
'collections.duplicates.button': 'ซ้ำกัน {count} รายการ',
'collections.duplicates.keepThis': 'เก็บอันนี้ไว้',
'collections.duplicates.sameProvider': 'สถานที่เดียวกันบนผู้ให้บริการแผนที่',
'collections.duplicates.sameNameNearby': 'ชื่อเดียวกันในตำแหน่งเดียวกัน',
'collections.duplicates.cannotMerge': 'ฝั่งหนึ่งอยู่ในทริปหรือรายการที่คุณเปิดไม่ได้แล้ว จึงรวมกันไม่ได้',
'collections.duplicates.notSame': 'ไม่ใช่สถานที่เดียวกัน',
'collections.duplicates.noAddress': 'ไม่มีที่อยู่',
'collections.duplicates.undo': 'แยก {name} ออกอีกครั้ง',
'collections.duplicates.none': 'ไม่มีสถานที่ที่อาจซ้ำกัน',
'collections.duplicates.more': 'จะมีเพิ่มเมื่อคุณจัดการรายการเหล่านี้เสร็จแล้ว',
'collections.allSavedSubtitle': 'ทุกสถานที่ที่คุณบันทึกไว้ จากทุกรายการรวมกัน',
'collections.library.title': 'สถานที่ทั้งหมด',
'collections.library.eyebrow': 'สถานที่ของฉัน',
+15
View File
@@ -104,6 +104,21 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Ortalama puan {rating}',
'collections.allSaved': 'Tüm kayıtlılar',
'collections.myLists': 'Listelerim',
'collections.duplicates.title': 'Olası yinelenenler',
'collections.duplicates.sub':
'Bu yerler tek bir yer gibi görünüyor. Bir tarafı koru, ikisi senin için tek yer sayılsın; gezilerin ve listelerin olduğu gibi kalır.',
'collections.duplicates.button': '{count} yinelenen',
'collections.duplicates.button.one': '{count} yinelenen',
'collections.duplicates.keepThis': 'Bunu koru',
'collections.duplicates.sameProvider': 'Harita sağlayıcısında aynı yer',
'collections.duplicates.sameNameNearby': 'Aynı noktada aynı ad',
'collections.duplicates.cannotMerge':
'Taraflardan biri artık açamadığın bir gezide veya listede olduğu için birleştirilemiyor.',
'collections.duplicates.notSame': 'Aynı yer değil',
'collections.duplicates.noAddress': 'Adres yok',
'collections.duplicates.undo': '{name} yeniden ayrılsın',
'collections.duplicates.none': 'Olası yinelenen yok.',
'collections.duplicates.more': 'Bunları bitirdiğinde daha fazlası görünür.',
'collections.allSavedSubtitle': 'Kaydettiğin her yer, tüm listelerinden bir arada.',
'collections.library.title': 'Tüm yerler',
'collections.library.eyebrow': 'Yerlerim',
+17
View File
@@ -127,6 +127,23 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Середня оцінка {rating}',
'collections.allSaved': 'Усі збережені',
'collections.myLists': 'Мої списки',
'collections.duplicates.title': 'Можливі дублікати',
'collections.duplicates.sub':
'Ці місця схожі на одне. Залиште одну сторону, і обидва вважатимуться одним вашим місцем; ваші поїздки та списки залишаться як є.',
'collections.duplicates.button': '{count} дубліката',
'collections.duplicates.button.one': '{count} дублікат',
'collections.duplicates.button.few': '{count} дублікати',
'collections.duplicates.button.many': '{count} дублікатів',
'collections.duplicates.keepThis': 'Залишити це',
'collections.duplicates.sameProvider': 'Те саме місце в постачальника карт',
'collections.duplicates.sameNameNearby': 'Та сама назва в тому самому місці',
'collections.duplicates.cannotMerge':
"Одна сторона в поїздці або списку, які ви більше не можете відкрити, тому їх не можна об'єднати.",
'collections.duplicates.notSame': 'Це не те саме місце',
'collections.duplicates.noAddress': 'Без адреси',
'collections.duplicates.undo': 'Знову розділити {name}',
'collections.duplicates.none': 'Можливих дублікатів немає.',
'collections.duplicates.more': "З'являться інші, коли ви впораєтеся з цими.",
'collections.allSavedSubtitle': 'Кожне збережене місце з усіх ваших списків разом.',
'collections.library.title': 'Усі місця',
'collections.library.eyebrow': 'Мої місця',
+14
View File
@@ -92,6 +92,20 @@ const collection: TranslationStrings = {
'collections.ratingBadge': 'Đánh giá trung bình {rating}',
'collections.allSaved': 'Tất cả đã lưu',
'collections.myLists': 'Danh sách của tôi',
'collections.duplicates.title': 'Có thể trùng lặp',
'collections.duplicates.sub':
'Những địa điểm này trông như một. Giữ một bên để gộp cả hai thành một địa điểm của bạn; chuyến đi và danh sách của bạn vẫn giữ nguyên.',
'collections.duplicates.button': '{count} trùng lặp',
'collections.duplicates.keepThis': 'Giữ cái này',
'collections.duplicates.sameProvider': 'Cùng một địa điểm trên nhà cung cấp bản đồ',
'collections.duplicates.sameNameNearby': 'Cùng tên tại cùng một vị trí',
'collections.duplicates.cannotMerge':
'Một bên nằm trong chuyến đi hoặc danh sách mà bạn không còn mở được, nên không thể gộp.',
'collections.duplicates.notSame': 'Không phải cùng một địa điểm',
'collections.duplicates.noAddress': 'Không có địa chỉ',
'collections.duplicates.undo': 'Tách {name} ra lại',
'collections.duplicates.none': 'Không có trùng lặp nào.',
'collections.duplicates.more': 'Sẽ có thêm khi bạn xử lý xong những mục này.',
'collections.allSavedSubtitle': 'Mọi địa điểm bạn đã lưu, từ tất cả danh sách gộp lại.',
'collections.library.title': 'Tất cả địa điểm',
'collections.library.eyebrow': 'Địa điểm của tôi',
+13
View File
@@ -89,6 +89,19 @@ const collection: TranslationStrings = {
'collections.ratingBadge': '平均評分 {rating}',
'collections.allSaved': '全部已儲存',
'collections.myLists': '我的清單',
'collections.duplicates.title': '可能重複',
'collections.duplicates.sub':
'這些地點看起來是同一個。保留其中一邊,兩者就會合併為你的一個地點;你的行程和清單維持不變。',
'collections.duplicates.button': '{count} 個重複',
'collections.duplicates.keepThis': '保留這個',
'collections.duplicates.sameProvider': '地圖服務商上的同一地點',
'collections.duplicates.sameNameNearby': '同一位置的同名地點',
'collections.duplicates.cannotMerge': '其中一邊位於你已無法開啟的行程或清單中,因此無法合併。',
'collections.duplicates.notSame': '不是同一地點',
'collections.duplicates.noAddress': '無地址',
'collections.duplicates.undo': '重新拆分 {name}',
'collections.duplicates.none': '沒有可能重複的地點。',
'collections.duplicates.more': '處理完這些後會出現更多。',
'collections.allSavedSubtitle': '你儲存的所有地點,來自全部清單的彙整。',
'collections.library.title': '全部地點',
'collections.library.eyebrow': '我的地點',
+13
View File
@@ -89,6 +89,19 @@ const collection: TranslationStrings = {
'collections.ratingBadge': '平均评分 {rating}',
'collections.allSaved': '全部已保存',
'collections.myLists': '我的清单',
'collections.duplicates.title': '可能重复',
'collections.duplicates.sub':
'这些地点看起来是同一个。保留其中一边,两者就会合并为你的一个地点;你的行程和清单保持不变。',
'collections.duplicates.button': '{count} 个重复',
'collections.duplicates.keepThis': '保留这个',
'collections.duplicates.sameProvider': '地图服务商上的同一地点',
'collections.duplicates.sameNameNearby': '同一位置的同名地点',
'collections.duplicates.cannotMerge': '其中一边位于你已无法打开的行程或清单中,因此无法合并。',
'collections.duplicates.notSame': '不是同一地点',
'collections.duplicates.noAddress': '无地址',
'collections.duplicates.undo': '重新拆分 {name}',
'collections.duplicates.none': '没有可能重复的地点。',
'collections.duplicates.more': '处理完这些后会出现更多。',
'collections.allSavedSubtitle': '你保存的所有地点,来自全部清单的汇总。',
'collections.library.title': '全部地点',
'collections.library.eyebrow': '我的地点',