feat(places): Places replaces Collections, with All places, place sheets and a calmer list

- Collections is Places now: /places opens "All places", every place of the
  trips and lists with where it comes from, the same filter row (where from,
  status, category, order), map bar (search, lock, list toggle) and place sheet
  as a list; /places/saved and /places/:id are the lists, and the old
  /collections links still land there. On the phone the same, with its own
  sheet. A place sheet shows each trip (planned day or trip dates, stay,
  booking, notes) and each list (status, labels, rating, notes) as one row
  that opens it.
- The rail: a calm "New list" with its plus tile, All places and All saved as
  views, a "My lists" heading, every name on one edge. Lists can carry one of
  24 symbols, shown in their colour in the rail and the editor.
- A saved place's row keeps to two lines: its category as an icon before the
  name, its average vote as a star on the picture. Map pins wear the same star.
- The place forms put the category in front of the name as a tile that opens
  the category list, instead of a row of chips.
- All saved gets a subtitle; the import dialog opens centred.
- Fixes: a pasted coordinate pair splits from either field of the place form;
  "more" in All places frees itself when a filter changes mid-load; place
  names on the trip map and the rating badge follow the reading direction.
This commit is contained in:
Maurice
2026-11-29 15:49:35 +01:00
parent 0ecca2b46c
commit 01d327b502
179 changed files with 6206 additions and 541 deletions
@@ -50,7 +50,7 @@ describe('AssistantAskButton', () => {
expect(screen.queryByRole('button')).not.toBeInTheDocument();
unmount();
renderAt('/collections/3');
renderAt('/places/3');
expect(screen.queryByRole('button')).not.toBeInTheDocument();
});
});
@@ -54,7 +54,7 @@ describe('collection answer cards', () => {
expect(within(card).getByText('Idea')).toBeInTheDocument();
expect(within(card).getByText('3')).toBeInTheDocument();
fireEvent.click(within(card).getByRole('button', { name: /Open list/ }));
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12' });
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12' });
});
it('FE-AI-COLL-040: the places to revisit have a pill of their own in the head, in the visited tone (#2567)', () => {
@@ -86,7 +86,7 @@ describe('collection answer cards', () => {
expect(screen.getByText('Spot 4')).toBeInTheDocument();
expect(screen.queryByText('Spot 5')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: '7 more in this list' }));
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12' });
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12' });
});
it('FE-AI-COLL-013: a roomy chat shows eight rows', () => {
@@ -144,7 +144,7 @@ describe('collection answer cards', () => {
expect(screen.queryByText('Paris food')).toBeNull();
expect(screen.getByText('Invite from Maya')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Rome/ }));
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/40' });
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/40' });
});
it('FE-AI-COLL-018: where a place is saved reads as its lists with its status in each', () => {
@@ -94,7 +94,7 @@ describe('collection change cards', () => {
const view = draw([applied(pending('save_place_to_collection', 'Septime', card), 'collection_place', [77])]);
expect(screen.queryByRole('button', { name: 'Show on map' })).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Open in Collections' }));
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12?place=77' });
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12?place=77' });
});
it('FE-AI-COLL-023: a save the place matched already says where it is saved', () => {
@@ -8,6 +8,7 @@ import type {
TrekCard,
} from '@trek/shared';
import { placesPath } from '../../../../utils/placesRoutes';
import type { EntityTarget } from '../cardTypes';
/**
@@ -26,12 +27,12 @@ export const MAX_FACTS = 4;
/** Where a list opens in Collections. */
export function listTarget(listId: number | null): EntityTarget {
return { kind: 'page', path: listId === null ? '/collections' : `/collections/${listId}` };
return { kind: 'page', path: placesPath(listId === null ? 'saved' : listId) };
}
/** Where a saved place opens: its list, with the place selected. */
function placeTarget(listId: number, placeId: number | null): EntityTarget {
const path = `/collections/${listId}`;
const path = placesPath(listId);
return { kind: 'page', path: placeId === null ? path : `${path}?place=${placeId}` };
}
@@ -62,9 +62,9 @@ describe('collection look', () => {
it('FE-AI-COLL-002: an applied list opens in Collections, unless the change deleted it or declined its invite', () => {
const look = ENTITY_LOOK.collection;
expect(look.openLabelKey).toBe('assistant.card.collection.openList');
expect(look.open?.(applied('collection', [12]), null)).toEqual({ kind: 'page', path: '/collections/12' });
expect(look.open?.(applied('collection', [12]), null)).toEqual({ kind: 'page', path: '/places/12' });
const card = listsCard({ lists: [listRow({ id: 13 })] });
expect(look.open?.(applied('collection', []), card)).toEqual({ kind: 'page', path: '/collections/13' });
expect(look.open?.(applied('collection', []), card)).toEqual({ kind: 'page', path: '/places/13' });
for (const change of ['remove', 'decline'] as const) {
expect(look.open?.(applied('collection', [12]), listsCard({ lists: [listRow({ change })] }))).toBeNull();
}
@@ -76,10 +76,10 @@ describe('collection look', () => {
const card = placesCard();
expect(look.open?.(applied('collection_place', [34]), card)).toEqual({
kind: 'page',
path: '/collections/12?place=34',
path: '/places/12?place=34',
});
const removed = placesCard({ places: [savedPlace({ delta: emptyDelta({ removed: true }) })] });
expect(look.open?.(applied('collection_place', [34]), removed)).toEqual({ kind: 'page', path: '/collections/12' });
expect(look.open?.(applied('collection_place', [34]), removed)).toEqual({ kind: 'page', path: '/places/12' });
expect(look.open?.(applied('collection_place', [34]), null)).toBeNull();
});
@@ -308,13 +308,17 @@ describe('AddPlaceToCollectionModal', () => {
it('FE-COMP-ADDPLACECOL-018: a category can be picked and cleared again', async () => {
setup()
typeName('Manual spot')
fireEvent.click(screen.getByRole('button', { name: /Food/ }))
fireEvent.click(screen.getByRole('button', { name: /Museum/ }))
// The category is the tile in front of the name; it opens the list to pick from.
fireEvent.click(screen.getByRole('button', { name: 'Category: No category' }))
fireEvent.click(screen.getByRole('option', { name: 'Food' }))
fireEvent.click(screen.getByRole('button', { name: 'Category: Food' }))
fireEvent.click(screen.getByRole('option', { name: 'Museum' }))
fireEvent.click(screen.getByRole('button', { name: /Add$/ }))
await waitFor(() => expect(savedBodies).toHaveLength(1))
expect(savedBodies[0]).toMatchObject({ category_id: 4 })
fireEvent.click(screen.getByRole('button', { name: 'No category' }))
fireEvent.click(screen.getByRole('button', { name: /^Category: / }))
fireEvent.click(screen.getByRole('option', { name: 'No category' }))
typeName('Second spot')
fireEvent.click(screen.getByRole('button', { name: /Add$/ }))
await waitFor(() => expect(savedBodies).toHaveLength(2))
@@ -323,8 +327,7 @@ describe('AddPlaceToCollectionModal', () => {
it('FE-COMP-ADDPLACECOL-019: without categories the category row is not rendered', () => {
setup({ categories: [] })
expect(screen.queryByText('Category')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'No category' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /^Category: / })).not.toBeInTheDocument()
})
it('FE-COMP-ADDPLACECOL-020: links are normalised and blank rows dropped', async () => {
@@ -7,13 +7,13 @@ import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, D
import { AddRowButton, EditorField, INPUT, Segmented, TEXTAREA } from '../shared/dialogParts'
import NoteFormatToolbar from '../shared/NoteFormatToolbar'
import { Tooltip } from '../shared/Tooltip'
import { getCategoryIcon } from '../shared/categoryIcons'
import { normalizeLinkUrl, STATUS_META, STATUS_ORDER } from '../../pages/collections/collectionsModel'
import type { Category, TranslationFn } from '../../types'
import type { CollectionStatus } from '@trek/shared'
import { str } from './addPlaceModel'
import { useAddPlaceToCollection } from './useAddPlaceToCollection'
import { PlaceFormLocation } from '../Planner/PlaceFormLocation'
import CategoryTileMenu from './CategoryTileMenu'
/**
* The search row, pinned to the top of the scrolling body. The dialog stays open
@@ -22,10 +22,6 @@ import { PlaceFormLocation } from '../Planner/PlaceFormLocation'
* margins let its background cover the body's padding while it is stuck.
*/
const STICKY_SEARCH = 'sticky top-0 z-20 -mx-6 -mt-5 bg-surface-card px-6 pb-4 pt-5'
/** A chip of the category row; the picked one wears the category's own colour. */
const CHIP = 'inline-flex items-center gap-1.5 rounded-full border px-3 py-1 font-semibold'
const CHIP_OFF = 'border-edge-faint bg-surface-card text-content-muted hover:text-content'
const CHIP_NONE_ON = 'border-content bg-surface-card text-content'
const ROW_ACTION = 'grid h-8 w-8 flex-none place-items-center rounded-[9px] text-content-faint hover:bg-surface-secondary'
interface AddPlaceToCollectionModalProps {
@@ -65,7 +61,10 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
const header = (
<DialogHeader
tile={<DialogTile><MapPinned size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>}
// The category is the tile in front of the name: one tap picks it, no chip row below.
tile={categories.length > 0
? <CategoryTileMenu categories={categories} value={categoryId} onChange={setCategoryId} t={t} />
: <DialogTile><MapPinned size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>}
tint={NEUTRAL_TINT}
labelId={labelId}
onClose={onClose}
@@ -178,39 +177,6 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
/>
</EditorField>
{categories.length > 0 && (
<EditorField label={t('collections.category')}>
<div role="group" aria-label={t('collections.category')} className="flex flex-wrap gap-1.5">
<button
type="button"
onClick={() => setCategoryId(null)}
aria-pressed={categoryId == null}
className={`${CHIP} ${categoryId == null ? CHIP_NONE_ON : CHIP_OFF}`}
style={fs(12, 'body')}
>
{t('collections.noCategory')}
</button>
{categories.map(cat => {
const Icon = getCategoryIcon(cat.icon ?? undefined)
const on = categoryId === cat.id
const col = cat.color || '#6366f1' // theme-lint-disable: the category's own colour, and the default one without a colour is drawn in
return (
<button
key={cat.id}
type="button"
onClick={() => setCategoryId(cat.id)}
aria-pressed={on}
className={`${CHIP} ${CHIP_OFF}`}
style={{ ...fs(12, 'body'), ...(on ? { color: col, background: `color-mix(in oklch, ${col} 15%, transparent)`, borderColor: `color-mix(in oklch, ${col} 40%, transparent)` } : {}) }}
>
<Icon size={13} /> {cat.name}
</button>
)
})}
</div>
</EditorField>
)}
<DialogSection
label={<label htmlFor={`${fieldId}-description`}>{t('collections.description')}</label>}
action={<NoteFormatToolbar textareaRef={descRef} onChange={setDescription} compact customTooltips />}
@@ -0,0 +1,24 @@
import React from 'react';
import { getCategoryIcon } from '../shared/categoryIcons';
import { Tooltip } from '../shared/Tooltip';
/** A place's category as its icon in its colour, in front of the name; the tooltip names it. */
export default function CategoryBadge({
category,
}: {
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
className="col-lrow-caticon"
style={{ ['--cat' as string]: category.color || 'var(--accent)' }}
aria-label={category.name ?? undefined}
role="img"
>
<Icon size={14} strokeWidth={2.2} />
</span>
</Tooltip>
);
}
@@ -0,0 +1,102 @@
// FE-COMP-CATTILEMENU-001 to FE-COMP-CATTILEMENU-007
import userEvent from '@testing-library/user-event';
import React from 'react';
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
import { useTranslation } from '../../i18n/TranslationContext';
import type { Category } from '../../types';
import CategoryTileMenu from './CategoryTileMenu';
const CATEGORIES = [
{ id: 3, name: 'Restaurant', color: '#E8843D', icon: 'Utensils' },
{ id: 5, name: 'Museum', color: null, icon: null },
] as unknown as Category[];
type Props = Omit<React.ComponentProps<typeof CategoryTileMenu>, 't' | 'categories' | 'onChange'>;
function Harness(props: Props & { onChange: (id: number | null) => void }): React.ReactElement {
const { t } = useTranslation();
return <CategoryTileMenu categories={CATEGORIES} {...props} t={t} />;
}
function setup(props: Partial<Props> = {}) {
const onChange = vi.fn<(id: number | null) => void>();
render(<Harness value={null} {...props} onChange={onChange} />);
return { onChange };
}
describe('CategoryTileMenu', () => {
it('FE-COMP-CATTILEMENU-001: without a category the tile says so and is closed', () => {
setup();
const tile = screen.getByRole('button', { name: 'Category: No category' });
expect(tile).toHaveAttribute('aria-expanded', 'false');
expect(tile).toHaveAttribute('title', 'Category: No category');
expect(tile).toHaveStyle({ width: '46px', height: '46px' });
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});
it('FE-COMP-CATTILEMENU-002: a category names itself on the tile in the size asked for', () => {
setup({ value: 3, size: 40 });
const tile = screen.getByRole('button', { name: 'Category: Restaurant' });
expect(tile).toHaveStyle({ width: '40px', height: '40px' });
expect(tile).not.toHaveClass('bg-surface-card');
});
it('FE-COMP-CATTILEMENU-003: a value with no category behind it reads as none', () => {
setup({ value: 99 });
expect(screen.getByRole('button', { name: 'Category: No category' })).toHaveClass('bg-surface-card');
});
it('FE-COMP-CATTILEMENU-004: the list offers "No category" and every category, the current one selected', async () => {
const user = userEvent.setup();
setup({ value: 5 });
await user.click(screen.getByRole('button', { name: 'Category: Museum' }));
const list = screen.getByRole('listbox', { name: 'Category' });
const options = within(list).getAllByRole('option');
expect(options.map((o) => o.textContent)).toEqual(['No category', 'Restaurant', 'Museum']);
expect(options[2]).toHaveAttribute('aria-selected', 'true');
expect(options[0]).toHaveAttribute('aria-selected', 'false');
});
it('FE-COMP-CATTILEMENU-005: picking a category or none reports it and closes the list', async () => {
const user = userEvent.setup();
const { onChange } = setup({ value: 3 });
const tile = screen.getByRole('button', { name: 'Category: Restaurant' });
await user.click(tile);
await user.click(screen.getByRole('option', { name: 'Museum' }));
expect(onChange).toHaveBeenLastCalledWith(5);
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
await user.click(tile);
await user.click(screen.getByRole('option', { name: 'No category' }));
expect(onChange).toHaveBeenLastCalledWith(null);
});
it('FE-COMP-CATTILEMENU-006: Escape closes the list and goes no further, so the dialog around it stays', async () => {
const user = userEvent.setup();
setup();
await user.click(screen.getByRole('button', { name: 'Category: No category' }));
const outer = vi.fn();
document.body.addEventListener('keydown', outer);
fireEvent.keyDown(screen.getByRole('listbox'), { key: 'Escape' });
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
expect(outer).not.toHaveBeenCalled();
document.body.removeEventListener('keydown', outer);
});
it('FE-COMP-CATTILEMENU-007: a press outside closes it, a press inside and other keys do not', async () => {
const user = userEvent.setup();
setup();
const tile = screen.getByRole('button', { name: 'Category: No category' });
await user.click(tile);
fireEvent.mouseDown(screen.getByRole('listbox'));
fireEvent.keyDown(document, { key: 'ArrowDown' });
expect(screen.getByRole('listbox')).toBeInTheDocument();
fireEvent.mouseDown(document.body);
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
expect(tile).toHaveAttribute('aria-expanded', 'false');
});
});
@@ -0,0 +1,103 @@
import { Check, Shapes } from 'lucide-react';
import React, { useEffect, useRef, useState } from 'react';
import type { Category, TranslationFn } from '../../types';
import { getCategoryIcon } from '../shared/categoryIcons';
interface CategoryTileMenuProps {
categories: Category[];
value: number | null;
onChange: (id: number | null) => void;
/** The tile's side in pixels: 46 in a dialog's head band, 40 beside the sheet's name field. */
size?: number;
t: TranslationFn;
}
/**
* The place's category as the tile in front of its name: its icon in its colour,
* and a tap opens the list to pick another. It replaces the row of category chips
* the forms had, so the category reads as part of the place and the form loses a row.
*/
export default function CategoryTileMenu({
categories,
value,
onChange,
size = 46,
t,
}: CategoryTileMenuProps): React.ReactElement {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onDoc = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.stopPropagation();
setOpen(false);
}
};
document.addEventListener('mousedown', onDoc);
document.addEventListener('keydown', onKey, true);
return () => {
document.removeEventListener('mousedown', onDoc);
document.removeEventListener('keydown', onKey, true);
};
}, [open]);
const current = value != null ? (categories.find((c) => c.id === value) ?? null) : null;
const Icon = current ? getCategoryIcon(current.icon ?? undefined) : Shapes;
const tone = current?.color || null;
const label = `${t('collections.category')}: ${current?.name ?? t('collections.noCategory')}`;
return (
<div className="relative flex-none" ref={ref}>
<button
type="button"
onClick={() => setOpen((o) => !o)}
aria-haspopup="listbox"
aria-expanded={open}
aria-label={label}
title={label}
className={`grid place-items-center rounded-[14px] shadow-sm transition-transform hover:scale-[1.03] ${tone ? '' : 'bg-surface-card text-content-muted'}`}
// The category's own colour, the one data-driven value of the tile.
style={{
width: size,
height: size,
...(tone ? { background: `color-mix(in srgb, ${tone} 16%, var(--bg-card))`, color: tone } : {}),
}}
>
<Icon size={Math.round(size * 0.43)} strokeWidth={1.9} />
</button>
{open && (
<div
role="listbox"
aria-label={t('collections.category')}
className="absolute start-0 top-[calc(100%+6px)] z-50 max-h-[280px] w-[220px] overflow-y-auto rounded-xl border border-edge-faint bg-surface-card p-1.5 shadow-lg"
>
{[null, ...categories].map((cat) => {
const on = (cat?.id ?? null) === value;
const OptIcon = cat ? getCategoryIcon(cat.icon ?? undefined) : Shapes;
return (
<button
key={cat?.id ?? 'none'}
type="button"
role="option"
aria-selected={on}
onClick={() => {
onChange(cat?.id ?? null);
setOpen(false);
}}
className={`flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-start text-body ${on ? 'bg-surface-secondary font-semibold text-content' : 'text-content-muted hover:bg-surface-secondary hover:text-content'}`}
>
<OptIcon size={15} className="flex-none" style={cat?.color ? { color: cat.color } : undefined} />
<span className="min-w-0 flex-1 truncate">{cat?.name ?? t('collections.noCategory')}</span>
{on && <Check size={14} className="flex-none" />}
</button>
);
})}
</div>
)}
</div>
);
}
@@ -1,67 +1,12 @@
import React, { useEffect, useRef, useState } from 'react'
import { ChevronDown, Check, Layers, Tag, CheckSquare, Star, Plus, ArrowDownUp, DownloadCloud } from 'lucide-react'
import React from 'react'
import { Layers, Tag, CheckSquare, Star, Plus, ArrowDownUp, DownloadCloud } from 'lucide-react'
import type { StatusFilter, CollectionSortMode } from '../../store/collectionStore'
import type { TranslationFn } from '../../types'
import { getCategoryIcon } from '../shared/categoryIcons'
import { STATUS_META, STATUS_ORDER } from '../../pages/collections/collectionsModel'
import type { CategoryOption, LabelOption } from '../../pages/collections/collectionsModel'
import CollectionLabelFilter from './CollectionLabelFilter'
interface Opt {
key: string | number
label: string
icon?: React.ReactNode
count?: number
}
/** Small custom dropdown — compact trigger + click-away popover. */
function Dropdown({ current, options, onSelect, lead }: {
current: string | number
options: Opt[]
onSelect: (key: string | number) => void
lead: React.ReactNode
}): React.ReactElement {
const [open, setOpen] = useState(false)
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!open) return
const onDoc = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false) }
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false) }
document.addEventListener('mousedown', onDoc)
document.addEventListener('keydown', onKey)
return () => { document.removeEventListener('mousedown', onDoc); document.removeEventListener('keydown', onKey) }
}, [open])
const cur = options.find(o => o.key === current) ?? options[0]
return (
<div className="col-filter" ref={ref}>
<button type="button" className={`col-filter-btn${open ? ' open' : ''}${cur.key === options[0]?.key ? ' is-default' : ''}`} onClick={() => setOpen(o => !o)} aria-haspopup="listbox" aria-expanded={open} title={cur.label}>
{cur.icon ?? lead}
<span className="col-filter-lbl">{cur.label}</span>
<ChevronDown size={14} className="col-filter-chev" />
</button>
{open && (
<div className="col-filter-pop" role="listbox">
{options.map(o => (
<button
key={o.key}
type="button"
role="option"
aria-selected={o.key === current}
className={`col-filter-opt${o.key === current ? ' on' : ''}`}
onClick={() => { onSelect(o.key); setOpen(false) }}
>
{o.icon ?? <span className="col-filter-dot ghost" />}
<span className="col-filter-lbl">{o.label}</span>
{o.count != null && <span className="col-filter-count">{o.count}</span>}
{o.key === current && <Check size={13} className="col-filter-check" />}
</button>
))}
</div>
)}
</div>
)
}
import FilterDropdown, { type FilterOption as Opt } from './FilterDropdown'
interface CollectionFilterBarProps {
statusFilter: StatusFilter
@@ -146,12 +91,12 @@ export default function CollectionFilterBar({
<Plus size={15} />
</button>
)}
<Dropdown current={statusFilter} options={statusOpts} onSelect={k => onStatusFilter(k as StatusFilter)} lead={<Layers size={13} />} />
<FilterDropdown current={statusFilter} options={statusOpts} onSelect={k => onStatusFilter(k as StatusFilter)} lead={<Layers size={13} />} />
{categoryOptions.length > 0 && (
<Dropdown current={categoryFilter} options={catOpts} onSelect={k => onCategoryFilter(k as number | 'all')} lead={<Tag size={13} />} />
<FilterDropdown current={categoryFilter} options={catOpts} onSelect={k => onCategoryFilter(k as number | 'all')} lead={<Tag size={13} />} />
)}
<Dropdown current={ratingFilter} options={ratingOpts} onSelect={k => onRatingFilter(k as number | 'all')} lead={<Star size={13} />} />
<Dropdown current={sortMode} options={sortOpts} onSelect={k => onSortMode(k as CollectionSortMode)} lead={<ArrowDownUp size={13} />} />
<FilterDropdown current={ratingFilter} options={ratingOpts} onSelect={k => onRatingFilter(k as number | 'all')} lead={<Star size={13} />} />
<FilterDropdown current={sortMode} options={sortOpts} onSelect={k => onSortMode(k as CollectionSortMode)} lead={<ArrowDownUp size={13} />} />
{showSelect && (
<button
type="button"
@@ -1,11 +1,16 @@
import React, { useEffect, useMemo, useRef } from 'react'
import { Check, GripVertical, Info, MapPin } from 'lucide-react'
import { Check, GripVertical, Info, MapPin, Star } from 'lucide-react'
import type { CollectionPlace, CollectionStatus, CollectionLabel } from '@trek/shared'
import type { TranslationFn } from '../../types'
import PlaceAvatar from '../shared/PlaceAvatar'
import StatusBadge from './StatusBadge'
import CollectionPlaceTags from './CollectionPlaceTags'
import { usePlaceReorder } from './usePlaceReorder'
import CategoryBadge from './CategoryBadge'
/** A vote average as the map's pins write it: a whole number bare, else one decimal. */
const ratingLabel = (rating: number): string => (Number.isInteger(rating) ? String(rating) : rating.toFixed(1))
interface CollectionListProps {
places: CollectionPlace[]
@@ -82,10 +87,20 @@ export default function CollectionList({
{selectMode ? (
<span className={`col-lcheck${selected ? ' on' : ''}`}>{selected && <Check size={14} strokeWidth={3} />}</span>
) : (
<PlaceAvatar place={place} size={40} category={place.category ? { color: place.category.color ?? undefined, icon: place.category.icon ?? undefined } : null} />
<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>
)}
<div className="li">
<div className="t">{place.name}</div>
<div className="t">{place.category?.name && <CategoryBadge category={place.category} />}<span className="nm">{place.name}</span></div>
{place.address && (
<div className="s">
<MapPin size={11} />
@@ -93,7 +108,7 @@ export default function CollectionList({
</div>
)}
</div>
<CollectionPlaceTags place={place} labels={placeLabels} />
<CollectionPlaceTags place={place} labels={placeLabels} showCategory={false} />
<div className="col-lrow-status">
<StatusBadge status={place.status} onChange={selectMode || !onStatusChange ? undefined : next => onStatusChange(place.id, next)} t={t} />
</div>
@@ -298,14 +298,15 @@ describe('CollectionPlaceDetail', () => {
renderDetail({ canEdit: true, categories: CATEGORIES, place: { ...place, category_id: 1 } });
await user.click(await screen.findByRole('button', { name: 'Edit' }));
expect(screen.getByText('Category')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /^Food$/ })).toHaveClass('on');
// The category is the tile in front of the name; it opens the list to pick from.
await user.click(screen.getByRole('button', { name: 'Category: Food' }));
expect(screen.getByRole('option', { name: 'Food' })).toHaveAttribute('aria-selected', 'true');
await user.click(screen.getByRole('option', { name: 'Museums' }));
expect(screen.getByRole('button', { name: 'Category: Museums' })).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /^Museums$/ }));
expect(screen.getByRole('button', { name: /^Museums$/ })).toHaveClass('on');
await user.click(screen.getByRole('button', { name: 'No category' }));
expect(screen.getByRole('button', { name: 'No category' })).toHaveClass('on');
await user.click(screen.getByRole('button', { name: 'Category: Museums' }));
await user.click(screen.getByRole('option', { name: 'No category' }));
expect(screen.getByRole('button', { name: 'Category: No category' })).toBeInTheDocument();
});
it('FE-COMP-COLDETAIL-023: saving from edit mode sends the whole patch and leaves edit mode', async () => {
@@ -318,10 +319,11 @@ describe('CollectionPlaceDetail', () => {
});
await user.click(await screen.findByRole('button', { name: 'Edit' }));
const nameInput = screen.getByLabelText('List name');
const nameInput = screen.getByLabelText('Name');
await user.clear(nameInput);
await user.type(nameInput, ' Renamed Cafe ');
await user.click(screen.getByRole('button', { name: /^Museums$/ }));
await user.click(screen.getByRole('button', { name: /^Category: / }));
await user.click(screen.getByRole('option', { name: 'Museums' }));
await user.click(screen.getByRole('button', { name: /Nightlife/ }));
const desc = screen.getByPlaceholderText('Add a description…');
await user.clear(desc);
@@ -351,7 +353,7 @@ describe('CollectionPlaceDetail', () => {
const props = renderDetail({ canEdit: true, place: { ...place, description: 'Nice spot', links: [] } });
await user.click(await screen.findByRole('button', { name: 'Edit' }));
await user.clear(screen.getByLabelText('List name'));
await user.clear(screen.getByLabelText('Name'));
await user.clear(screen.getByPlaceholderText('Add a description…'));
await user.click(screen.getByRole('button', { name: /Save/ }));
@@ -372,7 +374,7 @@ describe('CollectionPlaceDetail', () => {
await user.click(screen.getByRole('button', { name: /Save/ }));
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Name taken', 'error', undefined));
expect(screen.getByLabelText('List name')).toBeInTheDocument();
expect(screen.getByLabelText('Name')).toBeInTheDocument();
});
it('FE-COMP-COLDETAIL-026: Cancel discards the edits and returns to read mode', async () => {
@@ -380,7 +382,7 @@ describe('CollectionPlaceDetail', () => {
const props = renderDetail({ canEdit: true });
await user.click(await screen.findByRole('button', { name: 'Edit' }));
await user.type(screen.getByLabelText('List name'), ' Extra');
await user.type(screen.getByLabelText('Name'), ' Extra');
await user.click(screen.getByRole('button', { name: 'Cancel' }));
expect(props.onSave).not.toHaveBeenCalled();
@@ -452,7 +454,7 @@ describe('CollectionPlaceDetail', () => {
const user = userEvent.setup();
const props = renderDetail({ canEdit: true });
await user.click(await screen.findByRole('button', { name: 'Edit' }));
expect(screen.getByLabelText('List name')).toBeInTheDocument();
expect(screen.getByLabelText('Name')).toBeInTheDocument();
const other: CollectionPlace = { ...place, id: 2, name: 'Second Bar', description: null, links: [] };
render(<TranslatedDetail {...{ ...props, place: other }} />);
@@ -3,7 +3,7 @@ import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
import { markdownLinkComponents } from '../shared/markdownLink'
import { X, Pencil, Copy, Trash2, MapPin, Link2, Plus, ExternalLink, Check, Tag, Tags, Camera, Loader2, Navigation } from 'lucide-react'
import { X, Pencil, Copy, Trash2, MapPin, Link2, Plus, ExternalLink, Check, Tags, Camera, Loader2, Navigation } from 'lucide-react'
import type { CollectionPlace, CollectionStatus, CollectionLink, CollectionLabel } from '@trek/shared'
import type { Category, TranslationFn } from '../../types'
import MarkdownToolbar from '../Journey/MarkdownToolbar'
@@ -17,6 +17,7 @@ import { Tooltip } from '../shared/Tooltip'
import PlaceRating from '../shared/StarRating'
import { useCollectionPlaceForm } from './useCollectionPlaceForm'
import { CollectionLocationSearch } from './CollectionLocationSearch'
import CategoryTileMenu from './CategoryTileMenu'
function linkHost(url: string): string {
try { return new URL(url).hostname.replace(/^www\./, '') } catch { return url }
@@ -134,9 +135,13 @@ export default function CollectionPlaceDetail({
</div>
</div>
<div className="col-detail-head">
{editing
? <input value={name} onChange={e => setName(e.target.value)} className="col-detail-name-input" autoFocus aria-label={t('collections.listName')} />
: <h2 className="col-detail-name">{place.name}</h2>}
{editing ? (
// The category rides in front of the name instead of a chip row in the form.
<div className="flex items-center gap-2.5">
{categories.length > 0 && <CategoryTileMenu categories={categories} value={categoryId} onChange={setCategoryId} size={40} t={t} />}
<input value={name} onChange={e => setName(e.target.value)} className="col-detail-name-input min-w-0 flex-1" autoFocus aria-label={t('common.name')} />
</div>
) : <h2 className="col-detail-name">{place.name}</h2>}
</div>
</div>
@@ -176,22 +181,6 @@ export default function CollectionPlaceDetail({
{editing ? (
<div className="col-detail-edit">
{/* Category */}
<div className="col-detail-field">
<div className="col-detail-label"><Tag size={12} /> {t('collections.category')}</div>
<div className="col-detail-cats">
<button type="button" onClick={() => setCategoryId(null)} className={`col-detail-cat${categoryId == null ? ' on' : ''}`}>{t('collections.noCategory')}</button>
{categories.map(cat => {
const Icon = getCategoryIcon(cat.icon ?? undefined)
const on = categoryId === cat.id
return (
<button key={cat.id} type="button" onClick={() => setCategoryId(cat.id)} className={`col-detail-cat${on ? ' on' : ''}`} style={{ ['--cat' as string]: cat.color || '#6366f1' }}>
<Icon size={12} /> {cat.name}
</button>
)
})}
</div>
</div>
{/* A place that has no position yet can be looked up here (#2837). */}
{needsPosition && <CollectionLocationSearch picked={positionPicked} onPick={pickPosition} t={t} />}
{/* Address (#1870): free text, the coordinates stay separate */}
@@ -92,14 +92,17 @@ function labelsThatFit(row: HTMLElement): number {
export default function CollectionPlaceTags({
place,
labels,
showCategory = true,
}: {
place: CollectionPlace;
labels: CollectionLabel[];
/** Off where the row shows the category on the place's tile instead. */
showCategory?: boolean;
}): React.ReactElement | null {
const ref = useRef<HTMLDivElement>(null);
const [fit, setFit] = useState(labels.length);
const labelKey = labels.map((l) => `${l.id}:${l.name}`).join('|');
const categoryName = place.category?.name ?? null;
const categoryName = showCategory ? (place.category?.name ?? null) : null;
// Fitted on every change of the row's width and once more whenever its labels change:
// observing anew hands the observer's first notification to the new labels.
@@ -0,0 +1,93 @@
// FE-COMP-FILTERDROPDOWN-001 to FE-COMP-FILTERDROPDOWN-007
import userEvent from '@testing-library/user-event';
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
import FilterDropdown, { type FilterOption } from './FilterDropdown';
const OPTIONS: FilterOption[] = [
{ key: 'all', label: 'Everything', count: 12 },
{ key: 'trip', label: 'Trips', icon: <span data-testid="trip-icon" />, count: 8 },
{ key: 3, label: 'Food' },
];
function setup(current: string | number = 'all') {
const onSelect = vi.fn<(key: string | number) => void>();
const view = render(
<FilterDropdown current={current} options={OPTIONS} onSelect={onSelect} lead={<span data-testid="lead" />} />
);
const trigger = view.container.querySelector('.col-filter-btn');
if (!(trigger instanceof HTMLButtonElement)) throw new Error('no trigger');
return { ...view, onSelect, trigger };
}
describe('FilterDropdown', () => {
it('FE-COMP-FILTERDROPDOWN-001: the trigger names the current option and marks the default one', () => {
const { trigger } = setup();
expect(trigger).toHaveTextContent('Everything');
expect(trigger).toHaveAttribute('title', 'Everything');
expect(trigger).toHaveAttribute('aria-haspopup', 'listbox');
expect(trigger).toHaveAttribute('aria-expanded', 'false');
expect(trigger).toHaveClass('is-default');
expect(within(trigger).getByTestId('lead')).toBeInTheDocument();
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});
it('FE-COMP-FILTERDROPDOWN-002: a chosen option shows its own icon and drops the default mark', () => {
const { trigger } = setup('trip');
expect(trigger).toHaveTextContent('Trips');
expect(trigger).not.toHaveClass('is-default');
expect(within(trigger).getByTestId('trip-icon')).toBeInTheDocument();
expect(within(trigger).queryByTestId('lead')).not.toBeInTheDocument();
});
it('FE-COMP-FILTERDROPDOWN-003: an unknown current value falls back to the first option', () => {
const { trigger } = setup('gone');
expect(trigger).toHaveTextContent('Everything');
});
it('FE-COMP-FILTERDROPDOWN-004: opening lists every option with its count and the current one selected', async () => {
const user = userEvent.setup();
const { trigger } = setup(3);
await user.click(trigger);
expect(trigger).toHaveAttribute('aria-expanded', 'true');
const options = within(screen.getByRole('listbox')).getAllByRole('option');
expect(options.map((o) => o.textContent)).toEqual(['Everything12', 'Trips8', 'Food']);
expect(options[2]).toHaveAttribute('aria-selected', 'true');
expect(options[0]).toHaveAttribute('aria-selected', 'false');
});
it('FE-COMP-FILTERDROPDOWN-005: picking an option reports its key and closes the list', async () => {
const user = userEvent.setup();
const { trigger, onSelect } = setup();
await user.click(trigger);
await user.click(screen.getByRole('option', { name: /Food/ }));
expect(onSelect).toHaveBeenCalledWith(3);
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});
it('FE-COMP-FILTERDROPDOWN-006: Escape and a press outside close it, the trigger toggles it', async () => {
const user = userEvent.setup();
const { trigger, onSelect } = setup();
await user.click(trigger);
fireEvent.keyDown(document, { key: 'Escape' });
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
await user.click(trigger);
fireEvent.mouseDown(document.body);
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
await user.click(trigger);
await user.click(trigger);
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
expect(onSelect).not.toHaveBeenCalled();
});
it('FE-COMP-FILTERDROPDOWN-007: another key and a press inside leave it open', async () => {
const user = userEvent.setup();
const { trigger } = setup();
await user.click(trigger);
fireEvent.keyDown(document, { key: 'Enter' });
fireEvent.mouseDown(screen.getByRole('listbox'));
expect(screen.getByRole('listbox')).toBeInTheDocument();
});
});
@@ -0,0 +1,80 @@
import { Check, ChevronDown } from 'lucide-react';
import React, { useEffect, useRef, useState } from 'react';
export interface FilterOption {
key: string | number;
label: string;
icon?: React.ReactNode;
count?: number;
}
/** Small custom dropdown — compact trigger + click-away popover. */
export default function FilterDropdown({
current,
options,
onSelect,
lead,
}: {
current: string | number;
options: FilterOption[];
onSelect: (key: string | number) => void;
lead: React.ReactNode;
}): React.ReactElement {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onDoc = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') setOpen(false);
};
document.addEventListener('mousedown', onDoc);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onDoc);
document.removeEventListener('keydown', onKey);
};
}, [open]);
const cur = options.find((o) => o.key === current) ?? options[0];
return (
<div className="col-filter" ref={ref}>
<button
type="button"
className={`col-filter-btn${open ? 'open' : ''}${cur.key === options[0]?.key ? 'is-default' : ''}`}
onClick={() => setOpen((o) => !o)}
aria-haspopup="listbox"
aria-expanded={open}
title={cur.label}
>
{cur.icon ?? lead}
<span className="col-filter-lbl">{cur.label}</span>
<ChevronDown size={14} className="col-filter-chev" />
</button>
{open && (
<div className="col-filter-pop" role="listbox">
{options.map((o) => (
<button
key={o.key}
type="button"
role="option"
aria-selected={o.key === current}
className={`col-filter-opt${o.key === current ? 'on' : ''}`}
onClick={() => {
onSelect(o.key);
setOpen(false);
}}
>
{o.icon ?? <span className="col-filter-dot ghost" />}
<span className="col-filter-lbl">{o.label}</span>
{o.count != null && <span className="col-filter-count">{o.count}</span>}
{o.key === current && <Check size={13} className="col-filter-check" />}
</button>
))}
</div>
)}
</div>
);
}
@@ -280,8 +280,6 @@ export default function ImportCollectionModal({
onClose={onClose}
labelledBy={titleId}
width="narrow"
// The body grows once a file is read; the top edge stays where it was.
align="top"
header={(
<DialogHeader
tile={<DialogTile><FileDown size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>}
@@ -0,0 +1,8 @@
import { Navigate, useLocation } from 'react-router';
import { PLACES_ROOT, placesPathForLegacy } from '../../utils/placesRoutes';
/** An old /collections link (a bookmark, a notification, an assistant card) lands in Places (PLC-07). */
export default function LegacyCollectionsRedirect() {
const { pathname, search } = useLocation();
return <Navigate to={placesPathForLegacy(pathname, search) ?? PLACES_ROOT} replace />;
}
@@ -0,0 +1,95 @@
// FE-COMP-LIBFILTERBAR-001 to FE-COMP-LIBFILTERBAR-006
import userEvent from '@testing-library/user-event';
import React from 'react';
import { render, screen, within } from '../../../tests/helpers/render';
import { useTranslation } from '../../i18n/TranslationContext';
import type { Category } from '../../types';
import LibraryFilterBar from './LibraryFilterBar';
const CATEGORIES = [
{ id: 3, name: 'Restaurant', color: '#E8843D', icon: 'Utensils' },
{ id: 5, name: 'Museum', color: null, icon: null },
] as unknown as Category[];
type Props = Omit<React.ComponentProps<typeof LibraryFilterBar>, 't'>;
function Harness(props: Props): React.ReactElement {
const { t } = useTranslation();
return <LibraryFilterBar {...props} t={t} />;
}
function setup(over: Partial<Props> = {}) {
const props: Props = {
kind: 'all',
counts: { all: 12, trip: 8, list: 5 },
onKind: vi.fn(),
status: 'all',
onStatus: vi.fn(),
categoryId: 'all',
categories: CATEGORIES,
onCategory: vi.fn(),
sort: 'name',
onSort: vi.fn(),
...over,
};
const view = render(<Harness {...props} />);
const triggers = Array.from(view.container.querySelectorAll<HTMLButtonElement>('.col-filter-btn'));
return { ...view, props, triggers };
}
const optionTexts = () =>
within(screen.getByRole('listbox'))
.getAllByRole('option')
.map((o) => o.textContent);
describe('LibraryFilterBar', () => {
it('FE-COMP-LIBFILTERBAR-001: shows where from, status, category and order, each at its default', () => {
const { triggers } = setup();
expect(triggers.map((b) => b.textContent)).toEqual(['All', 'All', 'All', 'Name (A–Z)']);
});
it('FE-COMP-LIBFILTERBAR-002: without categories there is no category filter', () => {
const { triggers } = setup({ categories: [] });
expect(triggers.map((b) => b.textContent)).toEqual(['All', 'All', 'Name (A–Z)']);
});
it('FE-COMP-LIBFILTERBAR-003: where from lists trips and lists with their counts and reports the pick', async () => {
const user = userEvent.setup();
const { triggers, props } = setup();
await user.click(triggers[0]);
expect(optionTexts()).toEqual(['All12', 'Trips8', 'Lists5']);
await user.click(screen.getByRole('option', { name: /Trips/ }));
expect(props.onKind).toHaveBeenCalledWith('trip');
});
it('FE-COMP-LIBFILTERBAR-004: status offers every list status and reports the pick', async () => {
const user = userEvent.setup();
const { triggers, props } = setup({ status: 'visited' });
expect(triggers[1]).toHaveTextContent('Visited');
await user.click(triggers[1]);
expect(optionTexts()).toEqual(['All', 'Idea', 'Want to go', 'Visited', 'Want to revisit']);
await user.click(screen.getByRole('option', { name: 'Want to go' }));
expect(props.onStatus).toHaveBeenCalledWith('want');
});
it('FE-COMP-LIBFILTERBAR-005: category lists the categories by name and reports the id', async () => {
const user = userEvent.setup();
const { triggers, props } = setup({ categoryId: 3 });
expect(triggers[2]).toHaveTextContent('Restaurant');
await user.click(triggers[2]);
expect(optionTexts()).toEqual(['All', 'Restaurant', 'Museum']);
await user.click(screen.getByRole('option', { name: 'Museum' }));
expect(props.onCategory).toHaveBeenCalledWith(5);
});
it('FE-COMP-LIBFILTERBAR-006: order switches between name and last changed', async () => {
const user = userEvent.setup();
const { triggers, props } = setup({ sort: 'updated' });
expect(triggers[3]).toHaveTextContent('Last changed');
await user.click(triggers[3]);
expect(optionTexts()).toEqual(['Name (A–Z)', 'Last changed']);
await user.click(screen.getByRole('option', { name: 'Name (A–Z)' }));
expect(props.onSort).toHaveBeenCalledWith('name');
});
});
@@ -0,0 +1,99 @@
import type { CollectionStatus, PlacesLibraryCounts, PlacesLibrarySort } from '@trek/shared';
import { ArrowDownUp, Bookmark, 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';
import { getCategoryIcon } from '../shared/categoryIcons';
import FilterDropdown, { type FilterOption } from './FilterDropdown';
import type { LibraryKindFilter } from './usePlacesLibrary';
interface LibraryFilterBarProps {
kind: LibraryKindFilter;
counts: PlacesLibraryCounts;
onKind: (kind: LibraryKindFilter) => void;
status: CollectionStatus | 'all';
onStatus: (status: CollectionStatus | 'all') => void;
categoryId: number | 'all';
categories: Category[];
onCategory: (id: number | 'all') => void;
sort: PlacesLibrarySort;
onSort: (sort: PlacesLibrarySort) => void;
t: TranslationFn;
}
/**
* The filter row of "All places", built from the same compact dropdowns as the
* lists' row: where a place comes from (trips, lists or both, with their counts),
* the status it has in a list, its category, and the order.
*/
export default function LibraryFilterBar({
kind,
counts,
onKind,
status,
onStatus,
categoryId,
categories,
onCategory,
sort,
onSort,
t,
}: LibraryFilterBarProps): React.ReactElement {
const kindOpts: FilterOption[] = [
{ key: 'all', label: t('collections.library.kindAll'), count: counts.all },
{ key: 'trip', label: t('collections.library.kindTrips'), icon: <Luggage size={13} />, count: counts.trip },
{ key: 'list', label: t('collections.library.kindLists'), icon: <Bookmark size={13} />, count: counts.list },
];
const statusOpts: FilterOption[] = [
{ key: 'all', label: t('common.all') },
...STATUS_ORDER.map((s) => {
const Icon = STATUS_META[s].icon;
return {
key: s,
label: t(STATUS_META[s].labelKey),
icon: <Icon size={13} style={{ color: STATUS_META[s].color }} />,
};
}),
];
const catOpts: FilterOption[] = [
{ key: 'all', label: t('common.all') },
...categories.map((c) => {
const Icon = getCategoryIcon(c.icon ?? undefined);
return { key: c.id, label: c.name, icon: <Icon size={13} style={{ color: c.color ?? undefined }} /> };
}),
];
const sortOpts: FilterOption[] = [
{ key: 'name', label: t('collections.sort.nameAsc') },
{ key: 'updated', label: t('collections.library.sortUpdated') },
];
return (
<div className="col-filterbar">
<FilterDropdown
current={kind}
options={kindOpts}
onSelect={(k) => onKind(k as LibraryKindFilter)}
lead={<Globe2 size={13} />}
/>
<FilterDropdown
current={status}
options={statusOpts}
onSelect={(k) => onStatus(k as CollectionStatus | 'all')}
lead={<Layers size={13} />}
/>
{categories.length > 0 && (
<FilterDropdown
current={categoryId}
options={catOpts}
onSelect={(k) => onCategory(k as number | 'all')}
lead={<Tag size={13} />}
/>
)}
<FilterDropdown
current={sort}
options={sortOpts}
onSelect={(k) => onSort(k as PlacesLibrarySort)}
lead={<ArrowDownUp size={13} />}
/>
</div>
);
}
@@ -0,0 +1,54 @@
// FE-COMP-LIBORIGINS-001 to FE-COMP-LIBORIGINS-004
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';
type Props = Omit<React.ComponentProps<typeof LibraryOrigins>, 't'>;
function Harness(props: Props): React.ReactElement {
const { t } = useTranslation();
return <LibraryOrigins {...props} t={t} />;
}
const pillTexts = (container: HTMLElement) =>
Array.from(container.querySelectorAll('.col-origin-pill')).map((el) => el.textContent);
describe('LibraryOrigins', () => {
it("FE-COMP-LIBORIGINS-001: an origin goes by its list's or its trip's name", () => {
expect(originName(listOrigin({ collection_name: 'Wishlist' }))).toBe('Wishlist');
expect(originName(tripOrigin({ trip_title: 'Japan 2027' }))).toBe('Japan 2027');
});
it('FE-COMP-LIBORIGINS-002: trips come before lists, each with a title saying where the place is', () => {
const { container } = render(
<Harness origins={[listOrigin({ collection_name: 'Favourites' }), tripOrigin({ trip_title: 'Rome 2026' })]} />
);
expect(pillTexts(container)).toEqual(['Rome 2026', 'Favourites']);
expect(screen.getByTitle('In the trip Rome 2026')).toBeInTheDocument();
expect(screen.getByTitle('In the list Favourites')).toBeInTheDocument();
});
it('FE-COMP-LIBORIGINS-003: past two origins the rest is counted', () => {
const { container } = render(
<Harness
origins={[
listOrigin({ collection_place_id: 1, collection_name: 'A list' }),
tripOrigin({ place_id: 2, trip_title: 'First trip' }),
listOrigin({ collection_place_id: 3, collection_name: 'B list' }),
tripOrigin({ place_id: 4, trip_title: 'Second trip' }),
]}
/>
);
expect(pillTexts(container)).toEqual(['First trip', 'Second trip', '+2']);
expect(screen.queryByText('A list')).not.toBeInTheDocument();
});
it('FE-COMP-LIBORIGINS-004: two origins or fewer show no count', () => {
const { container } = render(<Harness origins={[tripOrigin()]} />);
expect(pillTexts(container)).toEqual(['Rome 2026']);
expect(container.querySelector('.col-origin-pill.more')).toBeNull();
});
});
@@ -0,0 +1,51 @@
import type { PlacesLibraryOrigin } from '@trek/shared';
import { Bookmark, Luggage } from 'lucide-react';
import React from 'react';
import type { TranslationFn } from '../../types';
/** 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.
*/
export default function LibraryOrigins({
origins,
t,
}: {
origins: PlacesLibraryOrigin[];
t: TranslationFn;
}): React.ReactElement {
const ordered = [...origins].sort((a, b) => (a.kind === b.kind ? 0 : a.kind === 'trip' ? -1 : 1));
const rest = ordered.length - SHOWN;
return (
<div className="col-lrow-origins">
{ordered.slice(0, SHOWN).map((origin) => {
const Icon = origin.kind === 'trip' ? Luggage : Bookmark;
return (
<span
key={origin.kind === 'trip' ? `t${origin.place_id}` : `l${origin.collection_place_id}`}
className="col-origin-pill"
title={
origin.kind === 'trip'
? t('collections.library.fromTrip', { name: originName(origin) })
: t('collections.library.fromList', { name: originName(origin) })
}
>
<Icon size={12} className="flex-none" aria-hidden="true" />
<span>{originName(origin)}</span>
</span>
);
})}
{rest > 0 && (
<span className="col-origin-pill more">{t('collections.library.moreOrigins', { count: rest })}</span>
)}
</div>
);
}
@@ -0,0 +1,245 @@
// FE-COMP-LIBPLACEDETAIL-001 to FE-COMP-LIBPLACEDETAIL-013
import userEvent from '@testing-library/user-event';
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import React from 'react';
import {
bothOrigins,
libraryDetail,
libraryEntry,
libraryInfo,
listDetail,
listOrigin,
tripDetail,
tripOrigin,
} from '../../../tests/helpers/placesLibrary';
import { render, screen, within } from '../../../tests/helpers/render';
import { useTranslation } from '../../i18n/TranslationContext';
import { type NavigationTarget, openNavigationTarget } from '../Planner/placeNavigation';
import LibraryPlaceDetail from './LibraryPlaceDetail';
const nav = vi.hoisted(() => ({ targets: [] as NavigationTarget[] }));
vi.mock('../Planner/placeNavigation', () => ({
getNavigationTargets: () => nav.targets,
navigationTargetLabel: (target: NavigationTarget) => target.label,
openNavigationTarget: vi.fn(),
}));
vi.mock('../shared/NavigationMenu', () => ({
NavigationMenu: ({ targets, onClose }: { targets: NavigationTarget[]; onClose: () => void }) => (
<div role="menu" aria-label="nav-menu">
{targets.map((target) => (
<span key={target.id}>{target.label}</span>
))}
<button type="button" onClick={onClose}>
menu-close
</button>
</div>
),
}));
const GOOGLE: NavigationTarget = { id: 'google', label: 'Google Maps', url: 'https://maps.example/g' };
const OSM: NavigationTarget = { id: 'osm', label: 'OpenStreetMap', url: 'https://maps.example/o' };
type Props = Omit<React.ComponentProps<typeof LibraryPlaceDetail>, 't'>;
function Harness(props: Props): React.ReactElement {
const { t } = useTranslation();
return <LibraryPlaceDetail {...props} t={t} />;
}
/** The Colosseum in a read-only trip, planned and booked there, and in a list with labels and votes. */
function fullDetail(): PlacesLibraryDetailResponse {
const data = bothOrigins({ category: { id: 3, name: 'Restaurant', color: '#E8843D', icon: 'Utensils' } });
data.entry.origins = [tripOrigin({ read_only: true }), listOrigin()];
data.details = [
tripDetail({
info: libraryInfo({ name: 'Colosseo' }),
notes: 'Book the underground tour',
days: [{ day_id: 1, day_number: 2, date: null, title: null, time: '10:00', end_time: null }],
has_accommodation: true,
has_reservation: true,
}),
listDetail({
info: libraryInfo({ description: 'Ancient arena' }),
notes: ' ',
labels: [{ id: 1, name: 'Must see', color: '#EF4444' }],
rating: { average: 4.5, count: 2, mine: 5 },
}),
];
return data;
}
function setup(over: Partial<Props> = {}) {
const props: Props = {
data: fullDetail(),
loading: false,
cover: null,
language: 'en',
onClose: vi.fn(),
onOpenList: vi.fn(),
onOpenTrip: vi.fn(),
onSaveToList: vi.fn(),
onCopyToTrip: vi.fn(),
...over,
};
const view = render(<Harness {...props} />);
return { ...view, props };
}
beforeEach(() => {
nav.targets = [];
vi.mocked(openNavigationTarget).mockClear();
});
describe('LibraryPlaceDetail: the sheet', () => {
it('FE-COMP-LIBPLACEDETAIL-001: while it loads it shows a spinner and nothing to do yet', () => {
const { container } = setup({ data: null, loading: true });
const dialog = screen.getByRole('dialog', { name: 'All places' });
expect(container.querySelector('.animate-spin')).not.toBeNull();
expect(within(dialog).getAllByRole('button')).toHaveLength(1);
expect(within(dialog).getByRole('button', { name: 'Close' })).toBeInTheDocument();
expect(screen.queryByRole('heading')).not.toBeInTheDocument();
});
it('FE-COMP-LIBPLACEDETAIL-002: the head carries the cover, the category and the name, the body the address', () => {
const { container } = setup({ cover: '/uploads/cover.jpg' });
expect(screen.getByRole('dialog', { name: 'Colosseum' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Colosseum' })).toBeInTheDocument();
expect(screen.getByText('Restaurant')).toBeInTheDocument();
expect(screen.getByText('Piazza del Colosseo')).toBeInTheDocument();
expect(container.querySelector('.col-detail-cover img')).toHaveAttribute('src', '/uploads/cover.jpg');
expect(screen.queryByText('No coordinates, so not on the map')).not.toBeInTheDocument();
expect(screen.getByText('Ancient arena')).toBeInTheDocument();
});
it('FE-COMP-LIBPLACEDETAIL-003: without a cover or coordinates it falls back to the gradient and says why it is not on the map', () => {
const entry = libraryEntry({ lat: null, lng: null, address: null });
const { container } = setup({ data: libraryDetail(entry, [tripDetail()]) });
expect(container.querySelector('.col-detail-cover img')).toBeNull();
expect(screen.getByText('No coordinates, so not on the map')).toBeInTheDocument();
expect(container.querySelector('.col-detail-cover-cat')).toBeNull();
});
it('FE-COMP-LIBPLACEDETAIL-004: docked it takes the column it is given, otherwise it stays centred', () => {
const { container, unmount } = setup({ anchorRect: { left: 120, width: 400 } });
const docked = container.querySelector('.col-detail');
expect(docked).toHaveClass('docked');
expect(docked).toHaveStyle({ left: '120px', width: '400px' });
unmount();
const centred = setup({ anchorRect: null }).container.querySelector('.col-detail');
expect(centred).not.toHaveClass('docked');
});
it('FE-COMP-LIBPLACEDETAIL-005: the close button closes it', async () => {
const user = userEvent.setup();
const { props } = setup();
await user.click(screen.getByRole('button', { name: 'Close' }));
expect(props.onClose).toHaveBeenCalledTimes(1);
});
});
describe('LibraryPlaceDetail: where the place sits', () => {
it('FE-COMP-LIBPLACEDETAIL-006: a trip shows its planned day, its name there, a stay, a booking and its notes', async () => {
const user = userEvent.setup();
const { props } = setup();
expect(screen.getByText('In your trips')).toBeInTheDocument();
const card = screen.getByRole('button', { name: 'Open in the trip: Rome 2026' });
expect(within(card).getByText('Day 2, 10:00')).toBeInTheDocument();
expect(within(card).getByText('Read only')).toBeInTheDocument();
expect(within(card).getByText('Called Colosseo here')).toBeInTheDocument();
expect(within(card).getByText('Stay')).toBeInTheDocument();
expect(within(card).getByText('Booking')).toBeInTheDocument();
expect(within(card).getByText('Book the underground tour')).toBeInTheDocument();
await user.click(card);
expect(props.onOpenTrip).toHaveBeenCalledWith(5, 42);
});
it('FE-COMP-LIBPLACEDETAIL-007: a list shows its status, labels and votes, and no notes when they are blank', async () => {
const user = userEvent.setup();
const { props } = setup();
expect(screen.getByText('In your lists')).toBeInTheDocument();
const card = screen.getByRole('button', { name: 'Open in the list: Favourites' });
expect(within(card).getByText('Want to go')).toBeInTheDocument();
expect(within(card).getByText('Must see')).toBeInTheDocument();
expect(within(card).getByText('4.5 from 2 votes')).toBeInTheDocument();
expect(within(card).queryByText('Notes')).not.toBeInTheDocument();
expect(within(card).queryByText(/^Called/)).not.toBeInTheDocument();
await user.click(card);
expect(props.onOpenList).toHaveBeenCalledWith(9, 900);
});
it('FE-COMP-LIBPLACEDETAIL-008: a plain trip place shows only its trip dates, nothing else', () => {
const entry = libraryEntry({ origins: [tripOrigin({ trip_start: '2026-12-01', trip_end: '2026-12-05' })] });
setup({ data: libraryDetail(entry, [tripDetail()]) });
const card = screen.getByRole('button', { name: 'Open in the trip: Rome 2026' });
expect(card.querySelector('.col-origin-title .sub')?.textContent).toMatch(/1.*5/);
expect(card.querySelector('.col-origin-chips')).toBeNull();
expect(within(card).queryByText('Read only')).not.toBeInTheDocument();
expect(screen.queryByText('In your lists')).not.toBeInTheDocument();
});
it('FE-COMP-LIBPLACEDETAIL-009: an origin the server sent no detail for is left out', () => {
const data = bothOrigins();
data.details = [tripDetail()];
setup({ data });
expect(screen.getByRole('button', { name: 'Open in the trip: Rome 2026' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Open in the list: Favourites' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Copy to trip/ })).not.toBeInTheDocument();
});
});
describe('LibraryPlaceDetail: what to do with it', () => {
it('FE-COMP-LIBPLACEDETAIL-010: a trip place can be kept in a list, a saved one copied to a trip', async () => {
const user = userEvent.setup();
const { props } = setup();
await user.click(screen.getByRole('button', { name: /Save to Collection/ }));
expect(props.onSaveToList).toHaveBeenCalledWith(props.data?.entry.origins[0], props.data?.details[0]);
await user.click(screen.getByRole('button', { name: /Copy to trip/ }));
expect(props.onCopyToTrip).toHaveBeenCalledWith(900);
});
it('FE-COMP-LIBPLACEDETAIL-011: a place only in a list cannot be saved again', () => {
const entry = libraryEntry({ key: 'list:900', origins: [listOrigin()] });
setup({ data: libraryDetail(entry, [listDetail()]) });
expect(screen.queryByRole('button', { name: /Save to Collection/ })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: /Copy to trip/ })).toBeInTheDocument();
});
it('FE-COMP-LIBPLACEDETAIL-012: one map app opens straight away, none hides the button', async () => {
const user = userEvent.setup();
nav.targets = [GOOGLE];
const { unmount } = setup();
await user.click(screen.getByRole('button', { name: /Google Maps/ }));
expect(openNavigationTarget).toHaveBeenCalledWith(GOOGLE);
expect(screen.queryByRole('menu')).not.toBeInTheDocument();
unmount();
nav.targets = [];
setup();
expect(screen.queryByRole('button', { name: /Navigation|Google Maps/ })).not.toBeInTheDocument();
});
it('FE-COMP-LIBPLACEDETAIL-013: several map apps open a menu that the button and the menu itself close', async () => {
const user = userEvent.setup();
nav.targets = [GOOGLE, OSM];
setup();
const button = screen.getByRole('button', { name: /Navigation/ });
await user.click(button);
const menu = screen.getByRole('menu');
expect(within(menu).getByText('OpenStreetMap')).toBeInTheDocument();
expect(openNavigationTarget).not.toHaveBeenCalled();
await user.click(within(menu).getByRole('button', { name: 'menu-close' }));
expect(screen.queryByRole('menu')).not.toBeInTheDocument();
await user.click(button);
await user.click(button);
expect(screen.queryByRole('menu')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,362 @@
import type { PlacesLibraryDetail, PlacesLibraryDetailResponse, PlacesLibraryOrigin } from '@trek/shared';
import {
Bookmark,
BookmarkPlus,
ChevronRight,
Copy,
Hotel,
Loader2,
Luggage,
MapPin,
MapPinOff,
Navigation,
NotebookPen,
Star,
Ticket,
X,
} from 'lucide-react';
import React, { 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 { tripLine } from './libraryDates';
import { originName } from './LibraryOrigins';
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;
/** The place's own image, or the provider's photo for it. */
cover: string | null;
language: string;
/** Where the sheet docks: over the list column in the split, centred otherwise. */
anchorRect?: { left: number; width: number } | null;
onClose: () => void;
onOpenList: (collectionId: number, collectionPlaceId: number) => void;
onOpenTrip: (tripId: number, placeId: number) => void;
/** Keeps the place in a list, from what the trip knows of it. */
onSaveToList: (origin: TripOrigin, detail: TripDetail) => void;
/** Copies a saved place into a trip (the list's own copy flow). */
onCopyToTrip: (collectionPlaceId: number) => void;
t: TranslationFn;
}
function Notes({ text, t }: { text: string | null; t: TranslationFn }) {
if (!text?.trim()) return null;
return (
<span className="col-origin-notes">
<span className="col-detail-label">
<NotebookPen size={11} /> {t('collections.notes')}
</span>
<span className="txt">{text}</span>
</span>
);
}
function TripCard({
origin,
detail,
entryName,
language,
onOpen,
t,
}: {
origin: TripOrigin;
detail: TripDetail;
entryName: string;
language: string;
onOpen: () => void;
t: TranslationFn;
}) {
const line = tripLine(origin, detail, language, t);
const extras = detail.has_accommodation || detail.has_reservation || detail.info.name !== entryName;
return (
<button
type="button"
className="col-origin"
onClick={onOpen}
aria-label={`${t('collections.library.openTrip')}: ${originName(origin)}`}
>
<span className="col-origin-head">
<span className="col-origin-ico">
<Luggage size={15} />
</span>
<span className="col-origin-title">
<span className="nm">{originName(origin)}</span>
{line && <span className="sub">{line}</span>}
</span>
{origin.read_only && <span className="col-origin-tag">{t('collections.library.readOnly')}</span>}
<ChevronRight size={16} className="col-origin-chev" />
</span>
{extras && (
<span className="col-origin-chips">
{detail.info.name !== entryName && (
<span className="col-origin-chip">{t('collections.library.calledHere', { name: detail.info.name })}</span>
)}
{detail.has_accommodation && (
<span className="col-origin-chip">
<Hotel size={11} /> {t('collections.library.stay')}
</span>
)}
{detail.has_reservation && (
<span className="col-origin-chip">
<Ticket size={11} /> {t('collections.library.booking')}
</span>
)}
</span>
)}
<Notes text={detail.notes} t={t} />
</button>
);
}
function ListCard({
origin,
detail,
entryName,
onOpen,
t,
}: {
origin: ListOrigin;
detail: ListDetail;
entryName: string;
onOpen: () => void;
t: TranslationFn;
}) {
const extras = detail.labels.length > 0 || detail.rating.average != null || detail.info.name !== entryName;
return (
<button
type="button"
className="col-origin"
onClick={onOpen}
aria-label={`${t('collections.library.openList')}: ${originName(origin)}`}
>
<span className="col-origin-head">
<span className="col-origin-ico">
<Bookmark size={15} />
</span>
<span className="col-origin-title">
<span className="nm">{originName(origin)}</span>
</span>
<StatusBadge status={origin.status} t={t} />
<ChevronRight size={16} className="col-origin-chev" />
</span>
{extras && (
<span className="col-origin-chips">
{detail.info.name !== entryName && (
<span className="col-origin-chip">{t('collections.library.calledHere', { name: detail.info.name })}</span>
)}
{detail.labels.map((label) => (
<span
key={label.id}
className="col-labelchip on static"
style={{ ['--label' as string]: label.color || 'var(--accent)' }}
>
<span className="col-labelchip-dot" /> {label.name}
</span>
))}
{detail.rating.average != null && (
<span className="col-origin-chip">
<Star size={11} />{' '}
{t('collections.library.rating', {
rating: detail.rating.average.toFixed(1),
count: detail.rating.count,
})}
</span>
)}
</span>
)}
<Notes text={detail.notes} t={t} />
</button>
);
}
/**
* One place of "All places" (PLC-08), in the same sheet a saved place opens in:
* docked over the list column, cover and category on top, then every trip and list
* the place sits in with what each keeps of it, so a note from a list and a day from
* a trip are never mistaken for one another. The list stays as it was underneath.
*/
export default function LibraryPlaceDetail({
data,
loading,
cover,
language,
anchorRect,
onClose,
onOpenList,
onOpenTrip,
onSaveToList,
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;
return (
<div
className={`col-detail${anchorRect ? 'docked' : ''}`}
style={dockStyle}
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>
<div className="col-detail-body">
{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>
)}
</>
)
)}
</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>
)}
</div>
);
}
@@ -131,6 +131,7 @@ describe('ListEditorModal', () => {
expect(actions.createCollection).toHaveBeenCalledWith({
name: 'Rome',
color: '#6366f1',
icon: 'Bookmark',
description: 'gelato',
links: [],
})
@@ -1,11 +1,12 @@
import React, { useId } from 'react'
import { Bookmark, ImagePlus, Trash2, Search, Loader2 } from 'lucide-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'
import { Tooltip } from '../shared/Tooltip'
import { normalizeLinkUrl } from '../../pages/collections/collectionsModel'
import type { TranslationFn } from '../../types'
import type { Collection } from '@trek/shared'
import { LIST_ICONS, LIST_ICON_NAMES, listIcon } from './listIcons'
import { useListEditor } from './useListEditor'
const SWATCHES = ['#6366f1', '#ec4899', '#14b8a6', '#f97316', '#8b5cf6', '#ef4444', '#3b82f6', '#22c55e']
@@ -32,16 +33,17 @@ interface ListEditorModalProps {
export default function ListEditorModal({ target, onClose, onCreated, onRequestDelete, t }: ListEditorModalProps): React.ReactElement | null {
const labelId = useId()
const {
editing, fileRef, name, setName, color, setColor, description, setDescription, links, setLinks, setLink,
editing, fileRef, name, setName, color, setColor, icon, setIcon, description, setDescription, links, setLinks, setLink,
coverPreview, coverQuery, setCoverQuery, coverResults, searchingCover, saving, pickCover, searchCover, pickUnsplash, save,
} = useListEditor({ target, onClose, onCreated, t, defaultColor: '#6366f1', normalizeLinkUrl })
const TileIcon = listIcon(icon)
if (!target) return null
// The list's own colour runs through the dialog: the head band, its tile and the cover.
const header = (
<DialogHeader
tile={<DialogTile><Bookmark size={20} strokeWidth={1.9} style={{ color }} /></DialogTile>}
tile={<DialogTile><TileIcon size={20} strokeWidth={1.9} style={{ color }} /></DialogTile>}
tint={`color-mix(in srgb, ${color} 12%, transparent)`}
labelId={labelId}
onClose={onClose}
@@ -149,6 +151,29 @@ export default function ListEditorModal({ target, onClose, onCreated, onRequestD
</div>
</EditorField>
<EditorField label={t('collections.listIcon')}>
<div role="group" aria-label={t('collections.listIcon')} className="flex flex-wrap gap-1.5">
{LIST_ICON_NAMES.map(name => {
const Icon = LIST_ICONS[name]
const on = icon === name
return (
<button
key={name}
type="button"
onClick={() => setIcon(name)}
aria-label={name}
aria-pressed={on}
className={`grid h-9 w-9 place-items-center rounded-[10px] transition-colors ${on ? '' : 'text-content-muted hover:bg-surface-secondary hover:text-content'}`}
// The list's own colour on the picked symbol, the one data-driven value here.
style={on ? { color, background: `color-mix(in srgb, ${color} 16%, transparent)` } : undefined}
>
<Icon size={17} strokeWidth={2} />
</button>
)
})}
</div>
</EditorField>
<EditorField label={t('collections.description')} htmlFor={`${labelId}-description`}>
<textarea
id={`${labelId}-description`}
+35 -16
View File
@@ -1,15 +1,22 @@
import React from 'react'
import { Plus, Layers, Users, Upload } from 'lucide-react'
import { Plus, Layers, Users, Upload, Globe2 } from 'lucide-react'
import type { Collection } from '@trek/shared'
import type { TranslationFn } from '../../types'
import { ALL_SAVED } from '../../store/collectionStore'
import type { ActiveCollectionId, IncomingCollectionInvite } from '../../store/collectionStore'
import CollectionInviteCard from './CollectionInviteCard'
import { Tooltip } from '../shared/Tooltip'
import { listIcon } from './listIcons'
interface ListsRailProps {
ownedLists: Collection[]
sharedLists: Collection[]
activeId: ActiveCollectionId
/** How many places the lists hold together, beside "All saved". */
savedCount?: number
/** The overview of every place is open (PLC-07); it sits above the lists. */
libraryActive?: boolean
onSelectLibrary?: () => void
incomingInvites: IncomingCollectionInvite[]
onSelect: (id: ActiveCollectionId) => void
onNewList: () => void
@@ -21,10 +28,12 @@ interface ListsRailProps {
}
function ListRow({ list, active, onSelect }: { list: Collection; active: boolean; onSelect: (id: number) => void }): React.ReactElement {
const ListIcon = listIcon(list.icon)
return (
<div className="col-row">
<button type="button" onClick={() => onSelect(list.id)} className={`col-row-btn${active ? ' on' : ''}`}>
<span className="dot" style={{ background: list.color || '#6366f1' }} />
{/* 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="nm">{list.name}</span>
<span className="ct">{list.place_count ?? 0}</span>
</button>
@@ -40,7 +49,7 @@ function ListRow({ list, active, onSelect }: { list: Collection; active: boolean
*/
export default function ListsRail(props: ListsRailProps): React.ReactElement {
const {
ownedLists, sharedLists, activeId, incomingInvites,
ownedLists, sharedLists, activeId, incomingInvites, libraryActive = false, onSelectLibrary, savedCount = 0,
onSelect, onNewList, onImportList, onAcceptInvite, onDeclineInvite, t,
} = props
@@ -48,29 +57,39 @@ export default function ListsRail(props: ListsRailProps): React.ReactElement {
<>
<div className="col-rail-newrow">
<button type="button" onClick={onNewList} className="col-rail-new">
<Plus size={16} /> {t('collections.newList')}
<span className="col-rail-plus"><Plus size={15} strokeWidth={2.4} /></span> {t('collections.newList')}
</button>
{/* Import sits beside New rather than in the hero: a file becomes a NEW
list, so it belongs where lists are made, not on the one open. */}
<button
type="button"
onClick={onImportList}
className="col-rail-new col-rail-import"
aria-label={t('collections.file.importButton')}
title={t('collections.file.importTitle')}
>
<Upload size={15} />
</button>
<Tooltip label={t('collections.file.importTitle')} placement="bottom">
<button
type="button"
onClick={onImportList}
className="col-rail-new col-rail-import"
aria-label={t('collections.file.importButton')}
>
<Upload size={16} />
</button>
</Tooltip>
</div>
{onSelectLibrary && (
<div className="col-row">
<button type="button" onClick={onSelectLibrary} className={`col-row-btn${libraryActive ? ' on' : ''}`} aria-current={libraryActive ? 'page' : undefined}>
<span className="ico tile"><Globe2 size={15} /></span>
<span className="nm">{t('collections.library.title')}</span>
</button>
</div>
)}
<div className="col-row">
<button type="button" onClick={() => onSelect(ALL_SAVED)} className={`col-row-btn${activeId === ALL_SAVED ? ' on' : ''}`}>
<span className="ico"><Layers size={16} /></span>
<button type="button" onClick={() => onSelect(ALL_SAVED)} className={`col-row-btn${!libraryActive && activeId === ALL_SAVED ? ' on' : ''}`}>
<span className="ico tile"><Layers size={15} /></span>
<span className="nm">{t('collections.allSaved')}</span>
{savedCount > 0 && <span className="ct">{savedCount}</span>}
</button>
</div>
{ownedLists.length > 0 && <div className="col-rail-sep" />}
{ownedLists.length > 0 && <div className="col-rail-label">{t('collections.myLists')}</div>}
{ownedLists.map(list => (
<ListRow key={list.id} list={list} active={activeId === list.id} onSelect={onSelect} />
))}
@@ -107,7 +107,7 @@ describe('MSaveToCollectionSheet', () => {
expect(screen.queryByRole('button', { name: 'View' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /New list/ }));
expect(mockNavigate).toHaveBeenCalledWith('/collections');
expect(mockNavigate).toHaveBeenCalledWith('/places/saved');
expect(useSaveToCollectionStore.getState().target).toBeNull();
});
@@ -239,7 +239,7 @@ describe('MSaveToCollectionSheet', () => {
await screen.findByText('Favorites');
fireEvent.click(screen.getByRole('button', { name: 'View' }));
expect(mockNavigate).toHaveBeenCalledWith('/collections');
expect(mockNavigate).toHaveBeenCalledWith('/places/saved');
expect(useSaveToCollectionStore.getState().target).toBeNull();
});
@@ -10,6 +10,9 @@ const SKIP_KEYS: Record<CollectionMapSkipReason, string> = {
invalid: 'collections.file.mapSkipInvalid',
};
/** What a list file holds for a place; the file schema leaves its places to the server to check. */
type MapPlace = { name?: string; address?: string | null };
interface MapImportPreviewProps {
file: CollectionFile;
map: Pick<CollectionMapReadResult, 'skipped' | 'folders'>;
@@ -51,7 +54,7 @@ export default function MapImportPreview({
</button>
</div>
<ul className="m-0 flex max-h-[34vh] list-none flex-col gap-0.5 overflow-y-auto rounded-[14px] border border-edge-faint bg-surface-secondary p-1.5">
{file.places.map((place, index) => {
{(file.places as MapPlace[]).map((place, index) => {
const on = picked.has(index);
const folder = map.folders[index];
return (
@@ -0,0 +1,360 @@
// FE-COMP-PLACESLIBVIEW-001 to FE-COMP-PLACESLIBVIEW-020
import userEvent from '@testing-library/user-event';
import React from 'react';
import {
libraryDetail,
libraryEntry,
libraryInfo,
libraryState,
type PlacesLibraryState,
threeEntries,
tripDetail,
tripOrigin,
} from '../../../tests/helpers/placesLibrary';
import { act, fireEvent, render, screen, within } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store';
import { useTranslation } from '../../i18n/TranslationContext';
import { useCollectionStore } from '../../store/collectionStore';
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';
import type CollectionMapPanel from './CollectionMapPanel';
import type CopyToTripModal from './CopyToTripModal';
import type LibraryPlaceDetail from './LibraryPlaceDetail';
import PlacesLibraryView from './PlacesLibraryView';
type MapProps = React.ComponentProps<typeof CollectionMapPanel>;
type DetailProps = React.ComponentProps<typeof LibraryPlaceDetail>;
type CopyProps = React.ComponentProps<typeof CopyToTripModal>;
const seen = vi.hoisted(() => ({
lib: null as PlacesLibraryState | null,
map: null as MapProps | null,
detail: null as DetailProps | null,
copy: null as CopyProps | null,
rect: { left: 300, width: 600 } as { left: number; width: number } | null,
}));
vi.mock('./usePlacesLibrary', () => ({
usePlacesLibrary: () => seen.lib,
}));
// The map stack does not render in jsdom; the panel's contract is what the view hands it.
vi.mock('./CollectionMapPanel', () => ({
default: (props: MapProps) => {
seen.map = props;
return <div data-testid="map-panel">{`markers:${props.places.length}`}</div>;
},
}));
vi.mock('./LibraryPlaceDetail', () => ({
default: (props: DetailProps) => {
seen.detail = props;
return <div data-testid="place-detail" />;
},
}));
vi.mock('./CopyToTripModal', () => ({
default: (props: CopyProps) => {
seen.copy = props;
return <div data-testid="copy-modal">{`copy:${props.placeIds.join(',')}`}</div>;
},
}));
vi.mock('../shared/PlaceAvatar', () => ({ default: () => <span data-testid="avatar" /> }));
vi.mock('../../hooks/useElementRect', () => ({
useElementRect: () => ({ ref: () => undefined, rect: seen.rect }),
}));
function captured<T>(value: T | null): T {
if (value == null) throw new Error('not rendered');
return value;
}
type ViewProps = Omit<React.ComponentProps<typeof PlacesLibraryView>, 't'>;
function Harness(props: ViewProps): React.ReactElement {
const { t } = useTranslation();
return <PlacesLibraryView {...props} t={t} />;
}
const openSave = vi.fn<(target: Parameters<ReturnType<typeof useSaveToCollectionStore.getState>['open']>[0]) => void>();
const copyToTrip = vi.fn<ReturnType<typeof useCollectionStore.getState>['copyToTrip']>();
function setup(lib: Partial<PlacesLibraryState> = {}, over: Partial<ViewProps> = {}) {
seen.lib = libraryState(lib);
const props: ViewProps = {
categories: [],
dark: false,
isWide: false,
language: 'en',
view: 'list',
onView: vi.fn(),
mapLocked: false,
onToggleMapLocked: vi.fn(),
navigate: vi.fn(),
...over,
};
const view = render(<Harness {...props} />);
return { ...view, props, lib: captured(seen.lib) };
}
const rows = () => Array.from(document.querySelectorAll<HTMLElement>('.col-lrow'));
beforeEach(() => {
resetAllStores();
seen.lib = null;
seen.map = null;
seen.detail = null;
seen.copy = null;
seen.rect = { left: 300, width: 600 };
openSave.mockReset();
copyToTrip.mockReset();
copyToTrip.mockResolvedValue({ copied: 1, skipped: [] });
useSaveToCollectionStore.setState({ open: openSave });
useCollectionStore.setState({ copyToTrip });
});
describe('PlacesLibraryView: the rows', () => {
it('FE-COMP-PLACESLIBVIEW-001: one row per place with its name, address and where it comes from', () => {
setup({ entries: threeEntries() });
expect(rows()).toHaveLength(3);
const [first, second] = rows();
expect(within(first).getByText('Pantheon')).toBeInTheDocument();
expect(within(first).getByText('Piazza della Rotonda')).toBeInTheDocument();
expect(within(first).getByText('Rome 2026')).toBeInTheDocument();
expect(within(second).getByText('Favourites')).toBeInTheDocument();
expect(screen.getAllByTestId('avatar')).toHaveLength(3);
});
it('FE-COMP-PLACESLIBVIEW-002: a click, Enter or Space opens a place, other keys do not', () => {
const { lib } = setup({ entries: threeEntries() });
const [first, second, third] = rows();
fireEvent.click(first);
fireEvent.keyDown(second, { key: 'Enter' });
fireEvent.keyDown(third, { key: ' ' });
fireEvent.keyDown(third, { key: 'a' });
expect(lib.open).toHaveBeenNthCalledWith(1, 'trip:1');
expect(lib.open).toHaveBeenNthCalledWith(2, 'trip:2');
expect(lib.open).toHaveBeenNthCalledWith(3, 'list:30');
expect(lib.open).toHaveBeenCalledTimes(3);
});
it('FE-COMP-PLACESLIBVIEW-003: the open place is marked and its sheet shows', () => {
setup({ entries: threeEntries(), selectedKey: 'trip:2' });
expect(rows().map((r) => r.classList.contains('sel'))).toEqual([false, true, false]);
expect(screen.getByTestId('place-detail')).toBeInTheDocument();
});
it('FE-COMP-PLACESLIBVIEW-004: "more" counts what is left, loads it and waits while it loads', async () => {
const user = userEvent.setup();
const { lib, unmount } = setup({ entries: threeEntries(), total: 8, hasMore: true });
await user.click(screen.getByRole('button', { name: 'Show 5 more' }));
expect(lib.loadMore).toHaveBeenCalledTimes(1);
unmount();
setup({ entries: threeEntries(), total: 8, hasMore: true, loadingMore: true });
expect(screen.getByRole('button', { name: 'Show 5 more' })).toBeDisabled();
});
it('FE-COMP-PLACESLIBVIEW-005: no "more" once everything is there, and no sheet without a place open', () => {
setup({ entries: threeEntries(), total: 3 });
expect(screen.queryByRole('button', { name: /more/ })).not.toBeInTheDocument();
expect(screen.queryByTestId('place-detail')).not.toBeInTheDocument();
});
});
describe('PlacesLibraryView: states', () => {
it('FE-COMP-PLACESLIBVIEW-006: offline it says it needs a connection', () => {
setup({ offline: true, entries: threeEntries() });
expect(screen.getByText('All places needs a connection.')).toBeInTheDocument();
expect(rows()).toHaveLength(0);
});
it('FE-COMP-PLACESLIBVIEW-007: a failure shows as an alert', () => {
setup({ error: 'Library is down' });
expect(screen.getByRole('alert')).toHaveTextContent('Library is down');
});
it('FE-COMP-PLACESLIBVIEW-008: the first load shows a spinner, a later one keeps the rows', () => {
const { container, unmount } = setup({ loading: true });
expect(container.querySelector('.col-loading')).not.toBeNull();
unmount();
const again = setup({ loading: true, entries: threeEntries() });
expect(again.container.querySelector('.col-loading')).toBeNull();
expect(rows()).toHaveLength(3);
});
it('FE-COMP-PLACESLIBVIEW-009: with no places at all it says so and offers nothing to clear', () => {
setup();
expect(screen.getByText('No places yet')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Clear filters' })).not.toBeInTheDocument();
});
it('FE-COMP-PLACESLIBVIEW-010: a filter that matches nothing offers to clear the filters', async () => {
const user = userEvent.setup();
const { lib } = setup({ filtered: true });
expect(screen.getByText('No matches')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Clear filters' }));
expect(lib.resetFilters).toHaveBeenCalledTimes(1);
});
});
describe('PlacesLibraryView: search, filters and the map', () => {
it('FE-COMP-PLACESLIBVIEW-011: on a narrow screen the search sits above the places and there is no map', () => {
const { lib } = setup({ entries: threeEntries(), search: 'pan' });
const search = screen.getByRole('textbox', { name: 'Search all places' });
expect(search).toHaveValue('pan');
fireEvent.change(search, { target: { value: 'pant' } });
expect(lib.setSearch).toHaveBeenCalledWith('pant');
expect(screen.queryByTestId('map-panel')).not.toBeInTheDocument();
});
it('FE-COMP-PLACESLIBVIEW-012: the filter row reaches the hook', async () => {
const user = userEvent.setup();
const { lib, container } = setup({ entries: threeEntries(), counts: { all: 3, trip: 2, list: 2 } });
const kindTrigger = container.querySelector<HTMLButtonElement>('.col-filter-btn');
await user.click(captured(kindTrigger));
await user.click(screen.getByRole('option', { name: /Trips/ }));
expect(lib.setKind).toHaveBeenCalledWith('trip');
});
it('FE-COMP-PLACESLIBVIEW-013: a wide screen splits into the list and a map of the places with a position', () => {
const { container } = setup({ entries: threeEntries(), selectedKey: 'trip:2' }, { isWide: true });
expect(container.querySelector('.col-split')).not.toBeNull();
expect(screen.getByTestId('map-panel')).toHaveTextContent('markers:2');
expect(screen.queryByRole('textbox', { name: 'Search all places' })).not.toBeInTheDocument();
const map = captured(seen.map);
expect(map.places.map((p) => p.name)).toEqual(['Pantheon', 'Trevi Fountain']);
expect(map.selectedPlaceId).toBe(2);
expect(map.overlay).toBe(true);
});
it('FE-COMP-PLACESLIBVIEW-014: a pin opens its place, the map closes it, the map search is the same search', () => {
const { lib } = setup({ entries: threeEntries() }, { isWide: true });
const map = captured(seen.map);
expect(map.selectedPlaceId).toBeNull();
act(() => map.onSelect(2));
expect(lib.show).toHaveBeenCalledWith('trip:2');
act(() => map.onSelect(99));
expect(lib.show).toHaveBeenCalledTimes(1);
act(() => map.onDeselect());
expect(lib.close).toHaveBeenCalledTimes(1);
act(() => map.onSearch('trevi'));
expect(lib.setSearch).toHaveBeenCalledWith('trevi');
});
it('FE-COMP-PLACESLIBVIEW-015: going to the map alone closes the place, coming back does not', () => {
const { lib, props, unmount } = setup({ entries: threeEntries() }, { isWide: true, view: 'list' });
act(() => captured(seen.map).onToggleView());
expect(lib.close).toHaveBeenCalledTimes(1);
expect(props.onView).toHaveBeenCalledWith('map');
unmount();
const back = setup({ entries: threeEntries() }, { isWide: true, view: 'map' });
expect(back.container.querySelector('.col-split.map-full')).not.toBeNull();
act(() => captured(seen.map).onToggleView());
expect(back.lib.close).not.toHaveBeenCalled();
expect(back.props.onView).toHaveBeenCalledWith('list');
});
it('FE-COMP-PLACESLIBVIEW-016: a wide screen without any position keeps the plain list', () => {
const unplaced = threeEntries().map((e) => ({ ...e, lat: null, lng: null }));
const { container } = setup({ entries: unplaced }, { isWide: true });
expect(container.querySelector('.col-split')).toBeNull();
expect(screen.getByRole('textbox', { name: 'Search all places' })).toBeInTheDocument();
});
});
describe('PlacesLibraryView: the place sheet', () => {
it('FE-COMP-PLACESLIBVIEW-017: the sheet docks over the list, over the map alone, or nowhere without the split', () => {
const split = setup({ entries: threeEntries(), selectedKey: 'trip:1' }, { isWide: true });
expect(captured(seen.detail).anchorRect).toEqual({ left: 300, width: 600 });
split.unmount();
const mapAlone = setup({ entries: threeEntries(), selectedKey: 'trip:1' }, { isWide: true, view: 'map' });
expect(captured(seen.detail).anchorRect).toEqual({ left: 312, width: 420 });
mapAlone.unmount();
seen.rect = { left: 0, width: 300 };
const narrowMap = setup({ entries: threeEntries(), selectedKey: 'trip:1' }, { isWide: true, view: 'map' });
expect(captured(seen.detail).anchorRect).toEqual({ left: 12, width: 276 });
narrowMap.unmount();
seen.rect = null;
const unmeasured = setup({ entries: threeEntries(), selectedKey: 'trip:1' }, { isWide: true, view: 'map' });
expect(captured(seen.detail).anchorRect).toBeNull();
unmeasured.unmount();
setup({ entries: threeEntries(), selectedKey: 'trip:1' });
expect(captured(seen.detail).anchorRect).toBeNull();
});
it('FE-COMP-PLACESLIBVIEW-018: the sheet gets what the hook loaded and opens a list or a trip by its route', () => {
const detail = libraryDetail(libraryEntry(), [tripDetail()]);
const { lib, props } = setup({
entries: threeEntries(),
selectedKey: 'trip:42',
detail,
detailLoading: true,
cover: '/uploads/c.jpg',
});
const sheet = captured(seen.detail);
expect(sheet.data).toBe(detail);
expect(sheet.loading).toBe(true);
expect(sheet.cover).toBe('/uploads/c.jpg');
expect(sheet.language).toBe('en');
act(() => sheet.onOpenList(3, 30));
expect(props.navigate).toHaveBeenLastCalledWith('/places/3?place=30');
act(() => sheet.onOpenTrip(5, 42));
expect(props.navigate).toHaveBeenLastCalledWith('/trips/5?place=42');
act(() => sheet.onClose());
expect(lib.close).toHaveBeenCalledTimes(1);
});
it('FE-COMP-PLACESLIBVIEW-019: keeping a trip place in a list hands over what the trip knows of it', () => {
const entry = libraryEntry({ category: { id: 3, name: 'Restaurant', color: null, icon: null } });
setup({ entries: [entry], selectedKey: 'trip:42', detail: libraryDetail(entry, [tripDetail()]) });
const info = libraryInfo({
name: 'Colosseo',
description: 'Arena',
website: 'https://colosseo.example',
phone: '+39 06',
image_url: '/uploads/c.jpg',
});
act(() => captured(seen.detail).onSaveToList(tripOrigin(), tripDetail({ info })));
expect(openSave).toHaveBeenCalledWith({
name: 'Colosseo',
source_trip_id: 5,
source_place_id: 42,
description: 'Arena',
lat: 41.89,
lng: 12.49,
address: 'Piazza del Colosseo',
category_id: 3,
image_url: '/uploads/c.jpg',
website: 'https://colosseo.example',
phone: '+39 06',
});
});
it('FE-COMP-PLACESLIBVIEW-020: copying a saved place opens the trip picker, which copies it and closes', async () => {
setup({ entries: threeEntries(), selectedKey: 'list:30' });
expect(screen.queryByTestId('copy-modal')).not.toBeInTheDocument();
act(() => captured(seen.detail).onCopyToTrip(900));
expect(screen.getByTestId('copy-modal')).toHaveTextContent('copy:900');
const modal = captured(seen.copy);
expect(modal.isOpen).toBe(true);
const carry = { include_notes: true } as Parameters<CopyProps['onCopy']>[1];
await act(async () => {
await modal.onCopy(7, carry);
});
expect(copyToTrip).toHaveBeenCalledWith(7, [900], undefined, carry);
act(() => modal.onClose());
expect(screen.queryByTestId('copy-modal')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,305 @@
import type { CollectionPlace, PlacesLibraryEntry } from '@trek/shared';
import { Loader2, MapPin, Search } from 'lucide-react';
import React, { useMemo, useState } from 'react';
import { useElementRect } from '../../hooks/useElementRect';
import { useCollectionStore } from '../../store/collectionStore';
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';
import type { Category, TranslationFn } from '../../types';
import { placesPath } from '../../utils/placesRoutes';
import EmptyState from '../shared/EmptyState';
import PlaceAvatar from '../shared/PlaceAvatar';
import CategoryBadge from './CategoryBadge';
import CollectionMapPanel from './CollectionMapPanel';
import CopyToTripModal from './CopyToTripModal';
import LibraryFilterBar from './LibraryFilterBar';
import LibraryOrigins from './LibraryOrigins';
import LibraryPlaceDetail from './LibraryPlaceDetail';
import { usePlacesLibrary } from './usePlacesLibrary';
interface PlacesLibraryViewProps {
categories: Category[];
dark: boolean;
isWide: boolean;
language: string;
/** The list and map halves of the page, shared with the lists: split, or the map alone. */
view: 'list' | 'map';
onView: (view: 'list' | 'map') => void;
mapLocked: boolean;
onToggleMapLocked: () => void;
navigate: (to: string) => void;
t: TranslationFn;
}
/** A map point per entry with a position; the map speaks CollectionPlace, keyed by a running id. */
function toMapPlaces(entries: PlacesLibraryEntry[]) {
const keyOf = new Map<number, string>();
const idOf = new Map<string, number>();
const places = entries.flatMap((entry, i) => {
if (entry.lat == null || entry.lng == null) return [];
const id = i + 1;
keyOf.set(id, entry.key);
idOf.set(entry.key, id);
return [
{
id,
name: entry.name,
lat: entry.lat,
lng: entry.lng,
address: entry.address,
image_url: entry.image_url,
category_id: entry.category?.id ?? null,
category: entry.category,
status: 'idea',
} as unknown as CollectionPlace,
];
});
return { places, keyOf, idOf };
}
/**
* "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
* row, map bar (search, lock, list toggle) and place sheet as a list. Opening a place
* docks its sheet over the list column (PLC-08); the list keeps its scroll underneath.
*/
export default function PlacesLibraryView({
categories,
dark,
isWide,
language,
view,
onView,
mapLocked,
onToggleMapLocked,
navigate,
t,
}: PlacesLibraryViewProps): React.ReactElement {
const lib = usePlacesLibrary({ active: true, t });
const openSave = useSaveToCollectionStore((s) => s.open);
const copyToTrip = useCollectionStore((s) => s.copyToTrip);
const [copyId, setCopyId] = useState<number | null>(null);
const listCol = useElementRect<HTMLDivElement>();
const mapCol = useElementRect<HTMLDivElement>();
const map = useMemo(() => toMapPlaces(lib.entries), [lib.entries]);
const selectedMapId = lib.selectedKey ? (map.idOf.get(lib.selectedKey) ?? null) : null;
const split = isWide && map.places.length > 0;
const filterBar = (
<LibraryFilterBar
kind={lib.kind}
counts={lib.counts}
onKind={lib.setKind}
status={lib.status}
onStatus={lib.setStatus}
categoryId={lib.categoryId}
categories={categories}
onCategory={lib.setCategoryId}
sort={lib.sort}
onSort={lib.setSort}
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>
);
}
// 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 = (
<>
{!split && (
<div className="col-toolbar">
<div className="col-toolbar-spacer" />
<div className="col-search">
<Search size={15} />
<input
value={lib.search}
onChange={(e) => lib.setSearch(e.target.value)}
placeholder={t('collections.library.search')}
aria-label={t('collections.library.search')}
/>
</div>
</div>
)}
{filterBar}
{rows}
</>
);
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;
return (
<>
{split ? (
<div className={`col-split${view === 'map' ? 'map-full' : ''}`}>
<div className="col-split-list" ref={listCol.ref}>
{listColumn}
</div>
<div className="col-split-map" ref={mapCol.ref}>
<CollectionMapPanel
places={map.places}
selectedPlaceId={selectedMapId}
onSelect={(id) => {
const key = map.keyOf.get(id);
if (key) lib.show(key);
}}
onDeselect={lib.close}
dark={dark}
overlay
view={view}
onToggleView={() => {
if (view !== 'map') lib.close();
onView(view === 'map' ? 'list' : 'map');
}}
search={lib.search}
onSearch={lib.setSearch}
mapLocked={mapLocked}
onToggleMapLocked={onToggleMapLocked}
t={t}
/>
</div>
</div>
) : (
listColumn
)}
{lib.selectedKey && (
<LibraryPlaceDetail
data={lib.detail}
loading={lib.detailLoading}
cover={lib.cover}
language={language}
anchorRect={anchor}
onClose={lib.close}
onOpenList={(collectionId, placeId) => navigate(`${placesPath(collectionId)}?place=${placeId}`)}
onOpenTrip={(tripId, placeId) => navigate(`/trips/${tripId}?place=${placeId}`)}
onSaveToList={(origin, d) =>
openSave({
name: d.info.name,
source_trip_id: origin.trip_id,
source_place_id: origin.place_id,
description: d.info.description,
lat: d.info.lat,
lng: d.info.lng,
address: d.info.address,
category_id: lib.detail?.entry.category?.id ?? null,
image_url: d.info.image_url,
website: d.info.website,
phone: d.info.phone,
})
}
onCopyToTrip={setCopyId}
t={t}
/>
)}
{copyId != null && (
<CopyToTripModal
isOpen
placeIds={[copyId]}
onClose={() => setCopyId(null)}
onCopy={(tripId, carry) => copyToTrip(tripId, [copyId], undefined, carry)}
t={t}
/>
)}
</>
);
}
@@ -112,7 +112,7 @@ describe('SaveToCollectionModal', () => {
expect(await screen.findByText('Create a list first to save places.')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /New list/ }));
expect(mockNavigate).toHaveBeenCalledWith('/collections');
expect(mockNavigate).toHaveBeenCalledWith('/places/saved');
expect(useSaveToCollectionStore.getState().target).toBeNull();
});
@@ -327,7 +327,7 @@ describe('SaveToCollectionModal', () => {
await screen.findByText('Favorites');
fireEvent.click(screen.getByRole('button', { name: 'View' }));
expect(mockNavigate).toHaveBeenCalledWith('/collections');
expect(mockNavigate).toHaveBeenCalledWith('/places/saved');
expect(useSaveToCollectionStore.getState().target).toBeNull();
unmount();
@@ -0,0 +1,42 @@
// FE-COMP-LIBDATES-001 to FE-COMP-LIBDATES-003
import { describe, expect, it } from 'vitest';
import { dayDate, tripLine, tripRange } from './libraryDates';
describe('libraryDates', () => {
it('FE-COMP-LIBDATES-001: a trip reads as one short range, or one date when only one end is known', () => {
// ICU spaces the dash differently between versions.
expect(tripRange('2026-12-01', '2026-12-05', 'en-GB')).toMatch(/^1\s?–\s?5 Dec$/);
expect(tripRange('2026-12-01', null, 'en-GB')).toBe('1 Dec');
expect(tripRange(null, null, 'en-GB')).toBeNull();
expect(tripRange('not a date', null, 'en-GB')).toBeNull();
});
it('FE-COMP-LIBDATES-002: a planned day carries its weekday', () => {
expect(dayDate('2026-12-02', 'en-GB')).toMatch(/^Wed,? 2 Dec$/);
expect(dayDate(null, 'en-GB')).toBeNull();
});
it('FE-COMP-LIBDATES-003: a trip origin names its planned day, counts the others, or falls back to the trip dates', () => {
const t = (k: string, p?: Record<string, string | number>) => `${k}${p ? JSON.stringify(p) : ''}`;
const trip = { trip_start: '2026-12-01', trip_end: '2026-12-05' };
const day = (n: number, time: string | null) => ({
day_id: n,
day_number: n,
date: '2026-12-02',
title: null,
time,
end_time: null,
});
expect(tripLine(trip, { days: [] }, 'en-GB', t)).toMatch(/^1\s?–\s?5 Dec$/);
expect(tripLine(trip, { days: [day(2, '10:00')] }, 'en-GB', t)).toMatch(
/^collections\.library\.dayOn\{"day":2,"date":"Wed,? 2 Dec, 10:00"\}$/
);
expect(tripLine(trip, { days: [day(2, null), day(3, null)] }, 'en-GB', t)).toMatch(
/collections\.library\.moreOrigins\{"count":1\}$/
);
expect(tripLine(trip, { days: [{ ...day(4, null), date: null }] }, 'en-GB', t)).toBe(
'collections.library.day{"day":4}'
);
});
});
@@ -0,0 +1,49 @@
import type { PlacesLibraryTripDetail, PlacesLibraryTripOrigin } from '@trek/shared';
/**
* The dates of "All places" in the reader's language: a trip as one short range
* ("1 to 5 Dec" in the locale's own form), a planned day as its weekday and date ("Wed, 2 Dec"). Dates are
* calendar days without a time zone, read and written in UTC so no zone shifts them.
*/
const SHORT: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'short', timeZone: 'UTC' };
const asDate = (iso: string | null | undefined): Date | null => {
if (!iso) return null;
const d = new Date(`${iso.slice(0, 10)}T00:00:00Z`);
return Number.isNaN(d.getTime()) ? null : d;
};
export function tripRange(
start: string | null | undefined,
end: string | null | undefined,
language: string
): string | null {
const a = asDate(start);
const b = asDate(end);
if (a && b) return new Intl.DateTimeFormat(language, SHORT).formatRange(a, b);
const one = a ?? b;
return one ? new Intl.DateTimeFormat(language, SHORT).format(one) : null;
}
export function dayDate(date: string | null | undefined, language: string): string | null {
const d = asDate(date);
return d ? new Intl.DateTimeFormat(language, { ...SHORT, weekday: 'short' }).format(d) : null;
}
/** What a trip origin says under its name: the planned day, or the trip's dates when it is not planned yet. */
export function tripLine(
origin: Pick<PlacesLibraryTripOrigin, 'trip_start' | 'trip_end'>,
detail: Pick<PlacesLibraryTripDetail, 'days'>,
language: string,
t: (key: string, params?: Record<string, string | number>) => string
): string | null {
const day = detail.days[0];
if (!day) return tripRange(origin.trip_start, origin.trip_end, language);
const when = [dayDate(day.date, language), day.time].filter(Boolean).join(', ');
const first = when
? t('collections.library.dayOn', { day: day.day_number, date: when })
: t('collections.library.day', { day: day.day_number });
return detail.days.length > 1
? `${first} ${t('collections.library.moreOrigins', { count: detail.days.length - 1 })}`
: first;
}
@@ -0,0 +1,14 @@
// FE-COMP-LISTICONS-001
import { Bookmark, Heart } from 'lucide-react';
import { describe, expect, it } from 'vitest';
import { DEFAULT_LIST_ICON, LIST_ICON_NAMES, listIcon } from './listIcons';
describe('listIcons', () => {
it('FE-COMP-LISTICONS-001: resolves a known symbol and falls back to the bookmark', () => {
expect(listIcon('Heart')).toBe(Heart);
expect(listIcon('NoSuchIcon')).toBe(Bookmark);
expect(listIcon(null)).toBe(Bookmark);
expect(LIST_ICON_NAMES[0]).toBe(DEFAULT_LIST_ICON);
});
});
@@ -0,0 +1,67 @@
import {
Baby,
Bed,
Bike,
Bookmark,
Camera,
Coffee,
Flag,
Gift,
Heart,
Landmark,
type LucideIcon,
MapPin,
Mountain,
Music,
Palette,
PawPrint,
Plane,
ShoppingBag,
Snowflake,
Star,
Sun,
TreePine,
Utensils,
Waves,
Wine,
} from 'lucide-react';
/**
* The symbols a list can wear (the column has always been there, holding "Bookmark").
* A small curated set rather than every Lucide icon: a list is told apart at a glance,
* and two dozen symbols are enough for food, nature, culture, nights out and stays.
*/
export const LIST_ICONS: Record<string, LucideIcon> = {
Bookmark,
Heart,
Star,
Utensils,
Coffee,
Wine,
Landmark,
Palette,
Music,
Camera,
Mountain,
TreePine,
Waves,
Sun,
Snowflake,
Bike,
Bed,
Plane,
ShoppingBag,
Gift,
Baby,
PawPrint,
Flag,
MapPin,
};
export const LIST_ICON_NAMES = Object.keys(LIST_ICONS);
export const DEFAULT_LIST_ICON = 'Bookmark';
/** The symbol of a list; one this build does not know falls back to the bookmark. */
export function listIcon(name: string | null | undefined): LucideIcon {
return (name && LIST_ICONS[name]) || Bookmark;
}
@@ -1,4 +1,4 @@
// FE-COMP-LISTEDITORHOOK-001 to FE-COMP-LISTEDITORHOOK-011: the list create / edit logic
// FE-COMP-LISTEDITORHOOK-001 to FE-COMP-LISTEDITORHOOK-012: the list create / edit logic
// behind both the desktop dialog and the phone sheet.
import { act, renderHook } from '@testing-library/react';
import type { Collection } from '@trek/shared';
@@ -136,6 +136,7 @@ describe('useListEditor', () => {
expect(actions.createCollection).toHaveBeenCalledWith({
name: 'Rome',
color: '#6366f1',
icon: 'Bookmark',
description: null,
links: [{ label: 'Map', url: 'https://maps.example' }],
});
@@ -153,6 +154,7 @@ describe('useListEditor', () => {
expect(actions.updateCollection).toHaveBeenCalledWith(4, {
name: 'Tokyo',
color: '#ec4899',
icon: 'Bookmark',
description: 'Food spots',
links: [{ label: 'Blog', url: 'https://a.example' }],
cover_image: 'https://img.example/u.jpg',
@@ -240,4 +242,14 @@ describe('useListEditor', () => {
unmount();
expect(URL.revokeObjectURL).toHaveBeenCalledTimes(2);
});
it('FE-COMP-LISTEDITORHOOK-012: a list keeps the symbol it was given, and a picked one is saved', async () => {
const { result } = setup({ target: { ...LIST, icon: 'Wine' } });
expect(result.current.icon).toBe('Wine');
act(() => result.current.setIcon('Heart'));
await act(async () => {
await result.current.save();
});
expect(actions.updateCollection).toHaveBeenCalledWith(4, expect.objectContaining({ icon: 'Heart' }));
});
});
@@ -6,6 +6,7 @@ import { useCollectionStore } from '../../store/collectionStore';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { useToast } from '../shared/Toast';
import { DEFAULT_LIST_ICON } from './listIcons';
export interface CoverSearchPhoto {
id: string;
@@ -62,6 +63,7 @@ export function useListEditor({
const [name, setName] = useState('');
const [color, setColor] = useState(defaultColor);
const [icon, setIcon] = useState(DEFAULT_LIST_ICON);
const [description, setDescription] = useState('');
const [links, setLinks] = useState<CollectionLink[]>([]);
const [coverFile, setCoverFile] = useState<File | null>(null);
@@ -90,6 +92,7 @@ export function useListEditor({
const edit = target !== 'new' ? target : null;
setName(edit?.name ?? '');
setColor(edit?.color ?? defaultColor);
setIcon(edit?.icon || DEFAULT_LIST_ICON);
setDescription(edit?.description ?? '');
setLinks(edit?.links ?? []);
setCoverFile(null);
@@ -156,6 +159,7 @@ export function useListEditor({
const payload = {
name: trimmed,
color,
icon,
description: description.trim() || null,
links: cleanListLinks(links, normalizeLinkUrl),
...(pendingUnsplashUrl ? { cover_image: pendingUnsplashUrl } : {}),
@@ -187,6 +191,8 @@ export function useListEditor({
setName,
color,
setColor,
icon,
setIcon,
description,
setDescription,
links,
@@ -0,0 +1,431 @@
// FE-COMP-PLACESLIBHOOK-001 to FE-COMP-PLACESLIBHOOK-025: 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';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
libraryDetail,
libraryEntry,
libraryInfo,
libraryPage,
listDetail,
listOrigin,
tripDetail,
} from '../../../tests/helpers/placesLibrary';
import { OnlineOnlyError } from '../../repo/onlineOnly';
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
import type { TranslationFn } from '../../types';
import { entryHasPosition, parseEntryKey, usePlacesLibrary } from './usePlacesLibrary';
vi.mock('../../repo/placesLibraryRepo', () => ({
placesLibraryRepo: { list: vi.fn(), detail: vi.fn(), coverPhoto: vi.fn() },
}));
const list = vi.mocked(placesLibraryRepo.list);
const detail = vi.mocked(placesLibraryRepo.detail);
const coverPhoto = vi.mocked(placesLibraryRepo.coverPhoto);
// A stable identity t: the hook's failure handler depends on it.
const t: TranslationFn = (key) => key;
const FIRST_PAGE = { sort: 'name', limit: 60 };
function deferred<T>() {
let resolve: (value: T) => void = () => undefined;
const promise = new Promise<T>((res) => {
resolve = res;
});
return { promise, resolve };
}
function apiError(message: string) {
return { response: { data: { error: message } } };
}
function mount(active = true) {
return renderHook(({ on }: { on: boolean }) => usePlacesLibrary({ active: on, t }), {
initialProps: { on: active },
});
}
async function mountLoaded(page: PlacesLibraryPageResponse = libraryPage([libraryEntry()])) {
list.mockResolvedValue(page);
const view = mount();
await waitFor(() => expect(view.result.current.loading).toBe(false));
return view;
}
beforeEach(() => {
list.mockReset();
detail.mockReset();
coverPhoto.mockReset();
coverPhoto.mockResolvedValue(null);
});
describe('parseEntryKey and entryHasPosition', () => {
it('FE-COMP-PLACESLIBHOOK-001: reads a trip or list key and refuses anything else', () => {
expect(parseEntryKey('trip:42')).toEqual({ kind: 'trip', id: 42 });
expect(parseEntryKey('list:900')).toEqual({ kind: 'list', id: 900 });
expect(parseEntryKey('own:3')).toBeNull();
expect(parseEntryKey('trip:abc')).toBeNull();
expect(parseEntryKey('trip:4:5')).toBeNull();
});
it('FE-COMP-PLACESLIBHOOK-002: an entry is a map point only with two finite coordinates', () => {
expect(entryHasPosition({ lat: 41.9, lng: 12.5 })).toBe(true);
expect(entryHasPosition({ lat: 0, lng: 0 })).toBe(true);
expect(entryHasPosition({ lat: null, lng: 12.5 })).toBe(false);
expect(entryHasPosition({ lat: 41.9, lng: null })).toBe(false);
expect(entryHasPosition({ lat: Number.NaN, lng: 12.5 })).toBe(false);
expect(entryHasPosition({ lat: 41.9, lng: Number.POSITIVE_INFINITY })).toBe(false);
});
});
describe('usePlacesLibrary: the first page', () => {
it('FE-COMP-PLACESLIBHOOK-003: asks nothing while inactive and loads once it becomes active', async () => {
list.mockResolvedValue(libraryPage([]));
const { rerender, result } = mount(false);
expect(list).not.toHaveBeenCalled();
expect(result.current.loading).toBe(false);
rerender({ on: true });
await waitFor(() => expect(list).toHaveBeenCalledTimes(1));
});
it('FE-COMP-PLACESLIBHOOK-004: loads the first page with its total, counts and cursor', async () => {
const pending = deferred<PlacesLibraryPageResponse>();
list.mockReturnValue(pending.promise);
const { result } = mount();
expect(result.current.loading).toBe(true);
expect(list).toHaveBeenCalledWith(FIRST_PAGE, expect.any(AbortSignal));
const placed = libraryEntry({ key: 'trip:1', name: 'Pantheon' });
const unplaced = libraryEntry({ key: 'list:2', name: 'Somewhere', lat: null, lng: null });
await act(async () => {
pending.resolve(
libraryPage([placed, unplaced], { total: 7, counts: { all: 7, trip: 4, list: 3 }, next_cursor: 'c1' })
);
await pending.promise;
});
expect(result.current.loading).toBe(false);
expect(result.current.entries).toEqual([placed, unplaced]);
expect(result.current.mappable).toEqual([placed]);
expect(result.current.total).toBe(7);
expect(result.current.counts).toEqual({ all: 7, trip: 4, list: 3 });
expect(result.current.hasMore).toBe(true);
expect(result.current.error).toBeNull();
expect(result.current.offline).toBe(false);
});
it('FE-COMP-PLACESLIBHOOK-005: without a connection it says offline instead of failing', async () => {
list.mockRejectedValue(new OnlineOnlyError());
const { result } = mount();
await waitFor(() => expect(result.current.offline).toBe(true));
expect(result.current.error).toBeNull();
expect(result.current.loading).toBe(false);
});
it("FE-COMP-PLACESLIBHOOK-006: a failure shows the server's message, else the generic error", async () => {
list.mockRejectedValueOnce(apiError('Library is down'));
const { result } = mount();
await waitFor(() => expect(result.current.error).toBe('Library is down'));
list.mockRejectedValueOnce(new Error('network'));
act(() => result.current.reload());
await waitFor(() => expect(result.current.error).toBe('common.error'));
expect(result.current.offline).toBe(false);
});
it('FE-COMP-PLACESLIBHOOK-007: reload asks for the first page again and clears an earlier error', async () => {
list.mockRejectedValueOnce(apiError('Boom'));
const { result } = mount();
await waitFor(() => expect(result.current.error).toBe('Boom'));
list.mockResolvedValueOnce(libraryPage([libraryEntry()]));
act(() => result.current.reload());
await waitFor(() => expect(result.current.entries).toHaveLength(1));
expect(result.current.error).toBeNull();
expect(list).toHaveBeenCalledTimes(2);
});
});
describe('usePlacesLibrary: filters and search', () => {
it('FE-COMP-PLACESLIBHOOK-008: each filter goes to the server and marks the overview as filtered', async () => {
const { result } = await mountLoaded(libraryPage([]));
expect(result.current.filtered).toBe(false);
act(() => result.current.setKind('trip'));
await waitFor(() =>
expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, kind: 'trip' }, expect.any(AbortSignal))
);
expect(result.current.filtered).toBe(true);
act(() => {
result.current.setCategoryId(3);
result.current.setStatus('want');
result.current.setSort('updated');
});
await waitFor(() =>
expect(list).toHaveBeenLastCalledWith(
{ kind: 'trip', category_id: 3, status: 'want', sort: 'updated', limit: 60 },
expect.any(AbortSignal)
)
);
expect(result.current.kind).toBe('trip');
expect(result.current.categoryId).toBe(3);
expect(result.current.status).toBe('want');
expect(result.current.sort).toBe('updated');
});
it('FE-COMP-PLACESLIBHOOK-009: clearing the filters keeps the order but drops every filter', async () => {
const { result } = await mountLoaded(libraryPage([]));
act(() => {
result.current.setKind('list');
result.current.setStatus('visited');
result.current.setSort('updated');
result.current.setSearch('rome');
});
await waitFor(() => expect(result.current.filtered).toBe(true));
act(() => result.current.resetFilters());
expect(result.current.search).toBe('');
expect(result.current.kind).toBe('all');
expect(result.current.categoryId).toBe('all');
expect(result.current.status).toBe('all');
expect(result.current.sort).toBe('updated');
expect(result.current.filtered).toBe(false);
await waitFor(() => expect(list).toHaveBeenLastCalledWith({ sort: 'updated', limit: 60 }, expect.any(AbortSignal)));
});
it('FE-COMP-PLACESLIBHOOK-010: typing settles before it asks, trimmed, and only the last word asks', async () => {
const { result } = await mountLoaded(libraryPage([]));
act(() => result.current.setSearch('ro'));
act(() => result.current.setSearch(' rome '));
expect(result.current.search).toBe(' rome ');
expect(list).toHaveBeenCalledTimes(1);
expect(result.current.filtered).toBe(false);
await waitFor(() => expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, q: 'rome' }, expect.any(AbortSignal)));
expect(list).toHaveBeenCalledTimes(2);
expect(list).not.toHaveBeenCalledWith(expect.objectContaining({ q: 'ro' }), expect.anything());
expect(result.current.filtered).toBe(true);
});
it('FE-COMP-PLACESLIBHOOK-011: a filter change drops the page still on its way', async () => {
const stale = deferred<PlacesLibraryPageResponse>();
list.mockReturnValueOnce(stale.promise);
const { result } = mount();
const firstSignal = list.mock.calls[0]?.[1];
const fresh = libraryEntry({ key: 'trip:2', name: 'Fresh' });
list.mockResolvedValueOnce(libraryPage([fresh]));
act(() => result.current.setKind('trip'));
expect(firstSignal?.aborted).toBe(true);
await waitFor(() => expect(result.current.entries).toEqual([fresh]));
await act(async () => {
stale.resolve(libraryPage([libraryEntry({ key: 'trip:1', name: 'Stale' })]));
await stale.promise;
});
expect(result.current.entries).toEqual([fresh]);
expect(result.current.loading).toBe(false);
});
});
describe('usePlacesLibrary: more pages', () => {
it('FE-COMP-PLACESLIBHOOK-012: "more" appends the next page from the cursor without doubles', async () => {
const { result } = await mountLoaded(
libraryPage([libraryEntry({ key: 'trip:1' }), libraryEntry({ key: 'trip:2' })], {
total: 3,
next_cursor: 'c1',
})
);
list.mockResolvedValueOnce(
libraryPage([libraryEntry({ key: 'trip:2' }), libraryEntry({ key: 'trip:3' })], { next_cursor: null })
);
await act(async () => {
await result.current.loadMore();
});
expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, cursor: 'c1' }, expect.any(AbortSignal));
expect(result.current.entries.map((e) => e.key)).toEqual(['trip:1', 'trip:2', 'trip:3']);
expect(result.current.hasMore).toBe(false);
expect(result.current.loadingMore).toBe(false);
expect(result.current.total).toBe(3);
});
it('FE-COMP-PLACESLIBHOOK-013: "more" asks nothing when there is no next page', async () => {
const { result } = await mountLoaded(libraryPage([libraryEntry()]));
await act(async () => {
await result.current.loadMore();
});
expect(list).toHaveBeenCalledTimes(1);
});
it('FE-COMP-PLACESLIBHOOK-014: "more" shows its loading state and a failure as the error', async () => {
const { result } = await mountLoaded(libraryPage([libraryEntry()], { next_cursor: 'c1' }));
const next = deferred<PlacesLibraryPageResponse>();
list.mockReturnValueOnce(next.promise.then(() => Promise.reject(apiError('Page gone'))));
let call: Promise<void> = Promise.resolve();
act(() => {
call = result.current.loadMore();
});
expect(result.current.loadingMore).toBe(true);
await act(async () => {
next.resolve(libraryPage([]));
await call;
});
expect(result.current.loadingMore).toBe(false);
expect(result.current.error).toBe('Page gone');
expect(result.current.entries).toHaveLength(1);
});
it('FE-COMP-PLACESLIBHOOK-025: a filter changed while "more" loads frees the button again', async () => {
const { result } = await mountLoaded(libraryPage([libraryEntry()], { next_cursor: 'c1' }));
const next = deferred<PlacesLibraryPageResponse>();
list.mockReturnValueOnce(next.promise);
act(() => {
void result.current.loadMore();
});
expect(result.current.loadingMore).toBe(true);
list.mockResolvedValue(libraryPage([libraryEntry()]));
act(() => result.current.setKind('trip'));
expect(result.current.loadingMore).toBe(false);
});
it('FE-COMP-PLACESLIBHOOK-015: "more" without a connection says offline', async () => {
const { result } = await mountLoaded(libraryPage([libraryEntry()], { next_cursor: 'c1' }));
list.mockRejectedValueOnce(new OnlineOnlyError());
await act(async () => {
await result.current.loadMore();
});
expect(result.current.offline).toBe(true);
expect(result.current.error).toBeNull();
});
});
describe('usePlacesLibrary: the open entry', () => {
it('FE-COMP-PLACESLIBHOOK-016: opening an entry loads what its origin keeps; opening it again closes it', async () => {
const { result } = await mountLoaded();
const answer = libraryDetail(libraryEntry({ image_url: '/uploads/own.jpg' }), [tripDetail()]);
const pending = deferred<PlacesLibraryDetailResponse>();
detail.mockReturnValueOnce(pending.promise);
act(() => result.current.open('trip:42'));
expect(result.current.selectedKey).toBe('trip:42');
expect(result.current.detailLoading).toBe(true);
expect(detail).toHaveBeenCalledWith('trip', 42, expect.any(AbortSignal));
await act(async () => {
pending.resolve(answer);
await pending.promise;
});
expect(result.current.detail).toBe(answer);
expect(result.current.detailLoading).toBe(false);
act(() => result.current.open('trip:42'));
expect(result.current.selectedKey).toBeNull();
expect(result.current.detail).toBeNull();
});
it('FE-COMP-PLACESLIBHOOK-017: show keeps an entry open, close shuts it, a saved place is asked as a list one', async () => {
const { result } = await mountLoaded();
detail.mockResolvedValue(libraryDetail(libraryEntry({ key: 'list:900', origins: [listOrigin()] }), [listDetail()]));
act(() => result.current.show('list:900'));
act(() => result.current.show('list:900'));
expect(result.current.selectedKey).toBe('list:900');
await waitFor(() => expect(result.current.detail?.entry.key).toBe('list:900'));
expect(detail).toHaveBeenCalledTimes(1);
expect(detail).toHaveBeenCalledWith('list', 900, expect.any(AbortSignal));
act(() => result.current.close());
expect(result.current.selectedKey).toBeNull();
expect(result.current.detail).toBeNull();
expect(result.current.cover).toBeNull();
});
it('FE-COMP-PLACESLIBHOOK-018: a key it cannot read loads nothing', async () => {
const { result } = await mountLoaded();
act(() => result.current.open('own:5'));
expect(result.current.selectedKey).toBe('own:5');
expect(detail).not.toHaveBeenCalled();
expect(result.current.detail).toBeNull();
});
it('FE-COMP-PLACESLIBHOOK-019: a failed detail closes the entry and shows the error', async () => {
const { result } = await mountLoaded();
detail.mockRejectedValueOnce(apiError('Place is gone'));
act(() => result.current.open('trip:42'));
await waitFor(() => expect(result.current.error).toBe('Place is gone'));
expect(result.current.selectedKey).toBeNull();
expect(result.current.detail).toBeNull();
});
it('FE-COMP-PLACESLIBHOOK-020: a detail without a connection says offline', async () => {
const { result } = await mountLoaded();
detail.mockRejectedValueOnce(new OnlineOnlyError());
act(() => result.current.open('trip:42'));
await waitFor(() => expect(result.current.offline).toBe(true));
expect(result.current.selectedKey).toBeNull();
});
it('FE-COMP-PLACESLIBHOOK-021: reload asks for the open entry again too', async () => {
const { result } = await mountLoaded();
detail.mockResolvedValue(libraryDetail(libraryEntry(), [tripDetail()]));
act(() => result.current.open('trip:42'));
await waitFor(() => expect(result.current.detail).not.toBeNull());
act(() => result.current.reload());
await waitFor(() => expect(detail).toHaveBeenCalledTimes(2));
expect(list).toHaveBeenCalledTimes(2);
});
});
describe('usePlacesLibrary: the cover', () => {
it("FE-COMP-PLACESLIBHOOK-022: the entry's own image wins, else the first origin image", async () => {
const { result } = await mountLoaded();
detail.mockResolvedValueOnce(libraryDetail(libraryEntry({ image_url: '/uploads/entry.jpg' }), [tripDetail()]));
act(() => result.current.open('trip:42'));
await waitFor(() => expect(result.current.cover).toBe('/uploads/entry.jpg'));
act(() => result.current.close());
detail.mockResolvedValueOnce(
libraryDetail(libraryEntry({ key: 'trip:7', origins: [] }), [
tripDetail(),
listDetail({ info: libraryInfo({ image_url: '/uploads/list.jpg' }) }),
])
);
act(() => result.current.open('trip:7'));
await waitFor(() => expect(result.current.cover).toBe('/uploads/list.jpg'));
expect(coverPhoto).not.toHaveBeenCalled();
});
it("FE-COMP-PLACESLIBHOOK-023: without an image of its own it asks the provider's photo", async () => {
const { result } = await mountLoaded();
const entry = libraryEntry();
coverPhoto.mockResolvedValueOnce('https://photos.example/colosseum.jpg');
detail.mockResolvedValueOnce(libraryDetail(entry, [tripDetail()]));
act(() => result.current.open('trip:42'));
await waitFor(() => expect(result.current.cover).toBe('https://photos.example/colosseum.jpg'));
expect(coverPhoto).toHaveBeenCalledWith(entry);
});
it('FE-COMP-PLACESLIBHOOK-024: a failed photo lookup leaves the gradient', async () => {
const { result } = await mountLoaded();
coverPhoto.mockRejectedValueOnce(new Error('no photo'));
detail.mockResolvedValueOnce(libraryDetail(libraryEntry(), [tripDetail()]));
act(() => result.current.open('trip:42'));
await waitFor(() => expect(coverPhoto).toHaveBeenCalledTimes(1));
await act(async () => {
await Promise.resolve();
});
expect(result.current.cover).toBeNull();
expect(result.current.detail).not.toBeNull();
});
});
@@ -0,0 +1,249 @@
import type {
CollectionStatus,
PlacesLibraryCounts,
PlacesLibraryDetailResponse,
PlacesLibraryEntry,
PlacesLibraryKind,
PlacesLibrarySort,
} from '@trek/shared';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { OnlineOnlyError } from '../../repo/onlineOnly';
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
/** Which origins the overview shows: all, only trip places, only saved ones. */
export type LibraryKindFilter = 'all' | PlacesLibraryKind;
const PAGE = 60;
/** How long typing settles before the search asks the server. */
const SEARCH_SETTLE_MS = 250;
const NO_COUNTS: PlacesLibraryCounts = { all: 0, trip: 0, list: 0 };
/** The origin an entry is opened from: its key, `trip:<place id>` or `list:<saved place id>`. */
export function parseEntryKey(key: string): { kind: PlacesLibraryKind; id: number } | null {
const match = /^(trip|list):(\d+)$/.exec(key);
return match ? { kind: match[1] as PlacesLibraryKind, id: Number(match[2]) } : null;
}
/** 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 }) {
const [search, setSearch] = useState('');
const [query, setQuery] = useState('');
const [kind, setKind] = useState<LibraryKindFilter>('all');
const [categoryId, setCategoryId] = useState<number | 'all'>('all');
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);
return () => clearTimeout(timer);
}, [search]);
const filters = useMemo(
() => ({
...(query ? { q: query } : {}),
...(kind !== 'all' ? { kind } : {}),
...(categoryId !== 'all' ? { category_id: categoryId } : {}),
...(status !== 'all' ? { status } : {}),
sort,
limit: PAGE,
}),
[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('');
setQuery('');
setKind('all');
setCategoryId('all');
setStatus('all');
}, []);
const mappable = useMemo(() => entries.filter(entryHasPosition), [entries]);
return {
search,
setSearch,
kind,
setKind,
categoryId,
setCategoryId,
sort,
setSort,
status,
setStatus,
filtered,
resetFilters,
entries,
mappable,
total,
counts,
hasMore: cursor != null,
loading,
loadingMore,
loadMore,
error,
offline,
reload,
selectedKey,
open,
show,
close,
detail,
detailLoading,
cover,
};
}
@@ -271,7 +271,7 @@ describe('useSaveToCollection', () => {
act(() => result.current.openCollections());
expect(useSaveToCollectionStore.getState().target).toBeNull();
expect(mockNavigate).toHaveBeenCalledWith('/collections');
expect(mockNavigate).toHaveBeenCalledWith('/places/saved');
});
it('FE-COMP-SAVETOCOLHOOK-014: a load landing after the target changed is dropped', async () => {
@@ -12,6 +12,7 @@ import { useTranslation } from '../../i18n';
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';
import { useServerPing } from '../../sync/useServerPing';
import { getApiErrorMessage } from '../../utils/apiError';
import { PLACES_SAVED } from '../../utils/placesRoutes';
import { useToast } from '../shared/Toast';
type MembershipEntry = CollectionMembership['lists'][number];
@@ -193,7 +194,7 @@ export function useSaveToCollection() {
const openCollections = () => {
close();
navigate('/collections');
navigate(PLACES_SAVED);
};
return {
@@ -5,6 +5,7 @@ import { useTranslation } from '../../i18n'
import { entityGradient } from '../../utils/gradients'
import { useCollectionLists } from './useCollectionLists'
import { readShownCollections, rememberShownCollections } from './collectionsWidgetMemory'
import { placesPath } from '../../utils/placesRoutes'
/**
* Dashboard sidebar widget — a glassy `.tool` card that surfaces the user's
@@ -47,7 +48,7 @@ export default function CollectionsWidget({ onOpen }: { onOpen: () => void }): R
key={list.id}
className="col-badge"
style={{ ['--badge-color' as string]: list.color || '#6366f1' }}
onClick={() => navigate(`/collections/${list.id}`)}
onClick={() => navigate(placesPath(list.id))}
>
{list.cover_image
? <img className="col-badge-media" src={list.cover_image} alt="" />
+2 -1
View File
@@ -8,6 +8,7 @@ import type { LucideIcon } from 'lucide-react'
import { resolvePluginIcon } from '../shared/PluginIcon'
import { useAuthStore } from '../../store/authStore'
import { visibleManagedNavItems } from '../../managed'
import { addonPath } from './navItems'
import { isNavItemActive, useCreateAction } from './useCreateAction'
const ADDON_NAV: Record<string, { icon: LucideIcon; labelKey: string }> = {
@@ -37,7 +38,7 @@ export default function BottomNav() {
{ to: '/dashboard', label: t('nav.myTrips'), icon: LayoutGrid },
...globalAddons.flatMap(addon => {
const nav = ADDON_NAV[addon.id]
return nav ? [{ to: `/${addon.id}`, label: t(nav.labelKey), icon: nav.icon }] : []
return nav ? [{ to: addonPath(addon.id), label: t(nav.labelKey), icon: nav.icon }] : []
}),
...pagePlugins.map(p => ({ to: `/plugins/${p.id}`, label: p.name, icon: resolvePluginIcon(p.icon) })),
// Empty in this repository — see client/src/managed.
+2 -1
View File
@@ -17,6 +17,7 @@ import { useCollapseOnOverflow } from '../../hooks/useCollapseOnOverflow'
import { openMailInbox } from '../MailIngest/mailInboxOpener'
import { useMailInboxShell } from '../MailIngest/useMailInboxShell'
import MailInboxDialog from '../MailIngest/MailInboxDialog'
import { addonPath } from './navItems'
import UserMenuFooter from './UserMenuFooter'
const ADDON_ICONS: Record<string, LucideIcon> = { CalendarDays, Briefcase, Globe, Compass, Bookmark }
@@ -105,7 +106,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
}
const tabs = [{ id: '__trips', path: '/dashboard', label: t('nav.myTrips'), Icon: Briefcase },
...globalAddons.map(a => ({ id: a.id, path: `/${a.id}`, label: getAddonName(a), Icon: ADDON_ICONS[a.icon] || CalendarDays })),
...globalAddons.map(a => ({ id: a.id, path: addonPath(a.id), label: getAddonName(a), Icon: ADDON_ICONS[a.icon] || CalendarDays })),
...pagePlugins.map(p => ({ id: `plugin:${p.id}`, path: `/plugins/${p.id}`, label: p.name, Icon: resolvePluginIcon(p.icon) })),
// Empty in this repository — see client/src/managed.
...visibleManagedNavItems(user?.role === 'admin').map(m => ({ id: `managed:${m.id}`, path: m.path, label: m.label, Icon: m.Icon }))
+6 -1
View File
@@ -54,6 +54,11 @@ export const MOBILE_NAV_MAX_BAR = 2
* assistant comes last: it takes a slot only one of the addons left free, rather
* than sitting alone behind the More button.
*/
/** Where an addon's page lives: its id, except Collections, which became Places (PLC-07). */
export function addonPath(id: string): string {
return id === 'collections' ? '/places' : `/${id}`
}
export const DEFAULT_DOCK_IDS = ['vacay', 'journey', 'atlas', 'collections', ASSISTANT_NAV_ID]
export function buildNavItems(
@@ -68,7 +73,7 @@ export function buildNavItems(
const translated = t(key)
return {
id: a.id,
to: `/${a.id}`,
to: addonPath(a.id),
label: translated && translated !== key ? translated : a.name || a.id,
icon: ADDON_ICONS[a.id] ?? resolvePluginIcon(a.icon),
}
@@ -91,14 +91,14 @@ describe('useCreateAction', () => {
});
it('FE-COMP-CREATEACTION-008: collections add a place to the open list on the phone only', () => {
const all = at('/collections', true);
const all = at('/places', true);
expect(all.label).toBe('collections.addPlace');
act(() => all.run());
expect(mockNavigate).toHaveBeenLastCalledWith('/collections?create=place');
const one = at('/collections/12', true);
expect(mockNavigate).toHaveBeenLastCalledWith('/places?create=place');
const one = at('/places/12', true);
act(() => one.run());
expect(mockNavigate).toHaveBeenLastCalledWith('/collections/12?create=place');
expect(at('/collections/12', false).label).toBe('dashboard.newTrip');
expect(mockNavigate).toHaveBeenLastCalledWith('/places/12?create=place');
expect(at('/places/12', false).label).toBe('dashboard.newTrip');
});
});
@@ -27,8 +27,8 @@ export function useCreateAction(phone: boolean): CreateAction {
const inJourney = useMatch('/journey/:id');
const onJourneyList = useMatch('/journey');
const onAtlas = useMatch('/atlas');
const onCollections = useMatch('/collections');
const inCollection = useMatch('/collections/:id');
const onCollections = useMatch('/places');
const inCollection = useMatch('/places/:id');
if (inTrip) {
const id = inTrip.params.id ?? '';
@@ -52,10 +52,10 @@ export function useCreateAction(phone: boolean): CreateAction {
return { label: t('atlas.searchCountry'), run: () => navigate('/atlas?search=1') };
}
if (phone && (onCollections || inCollection)) {
// Picking a list moves the route to /collections/:id, so the exact match
// Picking a list moves the route to /places/:id, so the exact match
// alone dropped the "+" through to creating a trip (#1930). The handoff keeps
// the id, otherwise adding would land on "All saved".
const path = inCollection ? `/collections/${inCollection.params.id}` : '/collections';
const path = inCollection ? `/places/${inCollection.params.id}` : '/places';
return { label: t('collections.addPlace'), run: () => navigate(`${path}?create=place`) };
}
return { label: t('dashboard.newTrip'), run: () => navigate('/dashboard?create=1') };
@@ -3,17 +3,16 @@ import { afterEach, describe, expect, it } from 'vitest';
import { controlBoxes, layoutPlaceNames, tagPlaceName } from './placeNameLabels';
type Rect = { left: number; top: number; width: number; height: number };
type Rect = { x: number; y: number; w: number; h: number };
/** jsdom lays nothing out, so every element answers the box it was given. */
function place(el: Element, r: Rect): void {
el.getBoundingClientRect = () =>
({ ...r, right: r.left + r.width, bottom: r.top + r.height, x: r.left, y: r.top, toJSON: () => ({}) }) as DOMRect;
el.getBoundingClientRect = () => ({ x: r.x, y: r.y, width: r.w, height: r.h, toJSON: () => ({}) }) as DOMRect;
}
function mapWith(pins: { name: string; priority: 0 | 1 | 2; at: Rect; label: Rect }[]): HTMLElement {
const container = document.createElement('div');
place(container, { left: 0, top: 0, width: 800, height: 600 });
place(container, { x: 0, y: 0, w: 800, h: 600 });
document.body.appendChild(container);
for (const pin of pins) {
const el = document.createElement('div');
@@ -42,8 +41,8 @@ describe('place names on the map', () => {
{
name: '<b>Senso-ji</b>',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
at: { x: 10, y: 10, w: 20, h: 20 },
label: { x: 36, y: 12, w: 80, h: 16 },
},
]);
layoutPlaceNames(c, true);
@@ -57,14 +56,14 @@ describe('place names on the map', () => {
{
name: 'Plain',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
at: { x: 10, y: 10, w: 20, h: 20 },
label: { x: 36, y: 12, w: 80, h: 16 },
},
{
name: 'Picked',
priority: 2,
at: { left: 10, top: 60, width: 20, height: 20 },
label: { left: 40, top: 14, width: 80, height: 16 },
at: { x: 10, y: 60, w: 20, h: 20 },
label: { x: 40, y: 14, w: 80, h: 16 },
},
]);
layoutPlaceNames(c, true);
@@ -78,29 +77,29 @@ describe('place names on the map', () => {
{
name: 'Covers a pin',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
at: { x: 10, y: 10, w: 20, h: 20 },
label: { x: 36, y: 12, w: 80, h: 16 },
},
{
name: 'Neighbour',
priority: 0,
at: { left: 60, top: 8, width: 20, height: 20 },
label: { left: 300, top: 300, width: 40, height: 16 },
at: { x: 60, y: 8, w: 20, h: 20 },
label: { x: 300, y: 300, w: 40, h: 16 },
},
{
name: 'Edge',
priority: 0,
at: { left: 760, top: 200, width: 20, height: 20 },
label: { left: 786, top: 202, width: 80, height: 16 },
at: { x: 760, y: 200, w: 20, h: 20 },
label: { x: 786, y: 202, w: 80, h: 16 },
},
{
name: 'Under control',
priority: 0,
at: { left: 400, top: 500, width: 20, height: 20 },
label: { left: 426, top: 502, width: 80, height: 16 },
at: { x: 400, y: 500, w: 20, h: 20 },
label: { x: 426, y: 502, w: 80, h: 16 },
},
]);
layoutPlaceNames(c, true, [{ left: 450, top: 490, right: 520, bottom: 530 }]);
layoutPlaceNames(c, true, [{ x0: 450, y0: 490, x1: 520, y1: 530 }]);
const hidden = labels(c).map((l) => l.hasAttribute('data-hidden'));
expect(hidden).toEqual([true, false, true, true]);
});
@@ -110,8 +109,8 @@ describe('place names on the map', () => {
{
name: 'Senso-ji',
priority: 0,
at: { left: 10, top: 10, width: 20, height: 20 },
label: { left: 36, top: 12, width: 80, height: 16 },
at: { x: 10, y: 10, w: 20, h: 20 },
label: { x: 36, y: 12, w: 80, h: 16 },
},
]);
layoutPlaceNames(c, true);
@@ -123,9 +122,9 @@ describe('place names on the map', () => {
it('FE-MAP-PLACENAMES-005: control boxes are read off the elements the selector finds', () => {
const c = document.createElement('div');
const btn = document.createElement('button');
place(btn, { left: 5, top: 6, width: 30, height: 30 });
place(btn, { x: 5, y: 6, w: 30, h: 30 });
c.appendChild(btn);
expect(controlBoxes(c, 'button')).toEqual([{ left: 5, top: 6, right: 35, bottom: 36 }]);
expect(controlBoxes(c, 'button')).toEqual([{ x0: 5, y0: 6, x1: 35, y1: 36 }]);
expect(controlBoxes(null, 'button')).toEqual([]);
});
});
+17 -19
View File
@@ -25,18 +25,24 @@ export function tagPlaceName(el: HTMLElement | null | undefined, name: string, p
el.setAttribute(PRIORITY_ATTR, String(priority));
}
/** A screen box: x0/y0 the top corner the reading starts at on screen, x1/y1 the opposite one. Plain geometry. */
interface Box {
left: number;
top: number;
right: number;
bottom: number;
x0: number;
y0: number;
x1: number;
y1: number;
}
const boxOf = (el: Element): Box => {
const r = el.getBoundingClientRect();
return { x0: r.x, y0: r.y, x1: r.x + r.width, y1: r.y + r.height };
};
// Overlaps nothing: a marker that was not measured cannot push a label away.
const NO_BOX: Box = { left: Infinity, top: Infinity, right: -Infinity, bottom: -Infinity };
const NO_BOX: Box = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };
const overlaps = (a: Box, b: Box, gap = 2): boolean =>
a.left < b.right + gap && b.left < a.right + gap && a.top < b.bottom + gap && b.top < a.bottom + gap;
a.x0 < b.x1 + gap && b.x0 < a.x1 + gap && a.y0 < b.y1 + gap && b.y0 < a.y1 + gap;
function ensureLabel(marker: HTMLElement): HTMLElement {
const name = marker.getAttribute(PLACE_NAME_ATTR) ?? '';
@@ -64,12 +70,9 @@ export function layoutPlaceNames(container: HTMLElement | null, enabled: boolean
container.querySelectorAll(`.${LABEL_CLASS}`).forEach((label) => label.remove());
return;
}
const frame = container.getBoundingClientRect();
const frame = boxOf(container);
const markerBoxes = new Map<HTMLElement, Box>();
for (const marker of markers) {
const r = marker.getBoundingClientRect();
markerBoxes.set(marker, { left: r.left, top: r.top, right: r.right, bottom: r.bottom });
}
for (const marker of markers) markerBoxes.set(marker, boxOf(marker));
const ordered = markers
.map((marker, index) => ({ marker, index, priority: Number(marker.getAttribute(PRIORITY_ATTR) ?? 0) }))
.sort((a, b) => b.priority - a.priority || a.index - b.index);
@@ -78,10 +81,8 @@ export function layoutPlaceNames(container: HTMLElement | null, enabled: boolean
for (const { marker } of ordered) {
const label = ensureLabel(marker);
label.removeAttribute(HIDDEN_ATTR);
const r = label.getBoundingClientRect();
const box: Box = { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
const offFrame =
box.left < frame.left || box.right > frame.right || box.top < frame.top || box.bottom > frame.bottom;
const box = boxOf(label);
const offFrame = box.x0 < frame.x0 || box.x1 > frame.x1 || box.y0 < frame.y0 || box.y1 > frame.y1;
const coversMarker = markers.some(
(other) => other !== marker && overlaps(box, markerBoxes.get(other) ?? NO_BOX, 0)
);
@@ -95,10 +96,7 @@ export function layoutPlaceNames(container: HTMLElement | null, enabled: boolean
/** The boxes of the map controls inside `container` that a label must leave free. */
export function controlBoxes(container: HTMLElement | null, selector: string): Box[] {
if (!container) return [];
return Array.from(container.querySelectorAll<HTMLElement>(selector)).map((el) => {
const r = el.getBoundingClientRect();
return { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
});
return Array.from(container.querySelectorAll<HTMLElement>(selector)).map(boxOf);
}
/** What no label may cover: the controls drawn over the map beside it. */
+2 -1
View File
@@ -2,7 +2,8 @@
element, so it pans with it; placeNameLabels.ts decides which ones stay visible. */
.trek-place-name {
position: absolute;
left: calc(100% + 6px); /* rtl-lint-disable: map geometry, the label sits beside the pin on screen */
/* After the pin in the reading direction, so an Arabic map reads the name from the pin outward. */
inset-inline-start: calc(100% + 6px);
top: 50%;
transform: translateY(-50%);
max-width: 13em;
@@ -26,12 +26,12 @@ describe('cornerBadgeHtml', () => {
it('FE-MAP-RATINGBADGE-101: day numbers win the corner over the rating', () => {
const html = cornerBadgeHtml([2, 5], 4.5, true, -4);
expect(html).toContain('2 · 5');
expect(html).toContain('bottom:-4px;right:-4px');
expect(html).not.toContain('#f59e0b');
expect(html).toContain('bottom:-4px;inset-inline-end:-4px');
expect(html).not.toContain('#fbbf24');
});
it('FE-MAP-RATINGBADGE-102: without numbers the rating shows when asked for, else nothing', () => {
expect(cornerBadgeHtml(null, 4, true, -2)).toContain('#f59e0b');
expect(cornerBadgeHtml(null, 4, true, -2)).toContain('#fbbf24');
expect(cornerBadgeHtml([], 4, false, -2)).toBe('');
expect(cornerBadgeHtml([3], null, true, -2)).toContain('height:18px');
});
+17 -14
View File
@@ -1,29 +1,32 @@
/** 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 disc on the corner of its marker.
* The rating a place carries, as a star 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 rounded value and no star: at eighteen pixels a star is a smudge, and "4.5" is
* already the whole sentence.
* 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.
*/
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:-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);
position:absolute;bottom:-6px;right:-6px;
width:22px;height:22px;
display:flex;align-items:center;justify-content:center;
font-size:9px;font-weight:800;color:#fff;
font-family:var(--font-system);line-height:1;
box-sizing:border-box;white-space:nowrap;
">${label}</span>`;
"><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>`;
}
/**
@@ -40,7 +43,7 @@ export function cornerBadgeHtml(
if (!orderNumbers || orderNumbers.length === 0) return showRating ? ratingBadgeHtml(rating) : '';
const many = orderNumbers.length > 1;
return `<span style="
position:absolute;bottom:${inset}px;right:${inset}px;
position:absolute;bottom:${inset}px;inset-inline-end:${inset}px;
min-width:18px;height:${many ? 16 : 18}px;border-radius:${many ? 8 : 9}px;
padding:0 ${many ? 4 : 3}px;
background:rgba(255,255,255,0.94);
@@ -28,7 +28,7 @@ export function usePlaceNameLayout(
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
const scope = container.parentElement ?? container;
const controls = enabled ? controlBoxes(scope, PLACE_NAMES_CONTROLS).filter((b) => b.right > b.left) : [];
const controls = enabled ? controlBoxes(scope, PLACE_NAMES_CONTROLS).filter((b) => b.x1 > b.x0) : [];
layoutPlaceNames(container, enabled, controls);
});
};
@@ -1,4 +1,5 @@
import { MapPinOff } from 'lucide-react';
import type React from 'react';
import { useTranslation } from '../../i18n';
import { EditorField, GRID_2, INPUT, PANEL } from '../shared/dialogParts';
@@ -24,6 +25,15 @@ interface PlaceFormLocationProps {
*/
export function PlaceFormLocation({ fieldId, form, onChange, warnWithoutCoordinates }: PlaceFormLocationProps) {
const { t } = useTranslation();
// "48.85, 2.35" pasted into either coordinate fills both halves.
const pastePair = (e: React.ClipboardEvent<HTMLInputElement>) => {
const pair = parseCoordinatePair(e.clipboardData.getData('text'));
if (pair) {
e.preventDefault();
onChange('lat', pair[0]);
onChange('lng', pair[1]);
}
};
const hint = warnWithoutCoordinates && addressWithoutCoordinates(form) && (
<span className="flex items-start gap-1 text-content-muted">
<MapPinOff size={12} strokeWidth={2} aria-hidden="true" className="mt-px flex-none text-warning" />
@@ -49,15 +59,7 @@ export function PlaceFormLocation({ fieldId, form, onChange, warnWithoutCoordina
mode="signed"
value={form.lat}
onValueChange={(v) => onChange('lat', v)}
onPaste={(e) => {
// "48.85, 2.35" pasted into the latitude fills both halves.
const pair = parseCoordinatePair(e.clipboardData.getData('text'));
if (pair) {
e.preventDefault();
onChange('lat', pair[0]);
onChange('lng', pair[1]);
}
}}
onPaste={pastePair}
placeholder={t('places.formLat')}
className={INPUT}
/>
@@ -68,6 +70,7 @@ export function PlaceFormLocation({ fieldId, form, onChange, warnWithoutCoordina
mode="signed"
value={form.lng}
onValueChange={(v) => onChange('lng', v)}
onPaste={pastePair}
placeholder={t('places.formLng')}
className={INPUT}
/>
@@ -6,6 +6,7 @@ import { collectionToursRepo } from '../../../repo/collectionToursRepo';
import { OnlineOnlyError } from '../../../repo/onlineOnly';
import { useAuthStore } from '../../../store/authStore';
import { canAddToCollection } from '../../../utils/collectionAccess';
import { PLACES_SAVED } from '../../../utils/placesRoutes';
import { useToast } from '../../shared/Toast';
/** The saved tour of a trip that is to be kept. */
@@ -127,7 +128,7 @@ export function useSaveTourToCollection(target: TourSaveTarget, { startOpen = fa
retry: () => setOpening((value) => value + 1),
openCollections: () => {
setOpen(false);
void navigate('/collections');
void navigate(PLACES_SAVED);
},
};
}