Files
TREK/client/tests/unit/mobile/collections/MPlacesLibrary.test.tsx
T
Maurice bacc6a29a7 feat(places): review possible duplicates, and repair the client gates
All places offers the pairs that look like one place: both sides side by side
with what differs marked, "keep this one" to group them as one place of the
user's own (undo right after), and "not the same place" to set a pair aside for
good. Desktop dialog and phone sheet share usePlaceDuplicates; every locale has
the new strings.

What the last dev run flagged on the client:
- Tailwind's Prettier plugin had trimmed the leading space of conditional class
  names (col-filter-btn, col-lrow sel, col-split map-full, col-detail docked),
  so the filter row and the open row lost their styling; those classes are now
  joined so the formatter cannot glue them.
- The dock position lives in one helper for the lists and All places, which
  moves the measured-position markers there instead of adding new ones.
- usePlacesLibrary is split into filters, pages, detail and cover hooks that
  derive their loading state instead of setting it inside effects; the big
  sheets and views are cut into parts under the complexity limit, dynamic icons
  go through createElement, originName moves out of a component file.
- formatRange is guarded like in the packing export, the cover lookup skips
  places without a position.
- Tests follow the rename to Places, the category icon, the default list icon
  and the new trip collections store; react-hooks/refs is lowered to the count
  the run measured.
- The rating on a place is a round badge again, in the list and on the map.
2026-11-29 16:28:22 +01:00

355 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// FE-MOB-PLACESLIB-001 to FE-MOB-PLACESLIB-018
import userEvent from '@testing-library/user-event';
import type { ComponentProps } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type CollectionMap from '../../../../src/components/Collections/CollectionMap';
import { useTranslation } from '../../../../src/i18n';
import type MCollTripPickerSheet from '../../../../src/mobile/screens/collections/MCollTripPickerSheet';
import type MLibraryPlaceSheet from '../../../../src/mobile/screens/collections/MLibraryPlaceSheet';
import MPlacesLibrary from '../../../../src/mobile/screens/collections/MPlacesLibrary';
import { useCollectionStore } from '../../../../src/store/collectionStore';
import { useSaveToCollectionStore } from '../../../../src/store/saveToCollectionStore';
import type { Category } from '../../../../src/types';
import {
libraryDetail,
libraryEntry,
libraryInfo,
libraryState,
type PlacesLibraryState,
threeEntries,
tripDetail,
tripOrigin,
} from '../../../helpers/placesLibrary';
import { act, fireEvent, render, screen } from '../../../helpers/render';
import { resetAllStores } from '../../../helpers/store';
type MapProps = ComponentProps<typeof CollectionMap>;
type SheetProps = ComponentProps<typeof MLibraryPlaceSheet>;
type PickerProps = ComponentProps<typeof MCollTripPickerSheet>;
const seen = vi.hoisted(() => ({
lib: null as PlacesLibraryState | null,
map: null as MapProps | null,
sheet: null as SheetProps | null,
picker: null as PickerProps | null,
}));
vi.mock('../../../../src/components/Collections/usePlacesLibrary', () => ({
usePlacesLibrary: () => seen.lib,
}));
// Keep the map stack out of jsdom; what the screen hands it is the contract.
// The review of possible duplicates has its own tests; here it has none to offer.
vi.mock('../../../../src/components/Collections/usePlaceDuplicates', () => ({
usePlaceDuplicates: () => ({
pairs: [],
hasMore: false,
loading: false,
busy: null,
lastMerge: null,
merge: vi.fn(),
dismiss: vi.fn(),
undo: vi.fn(),
reload: vi.fn(),
}),
}));
vi.mock('../../../../src/components/Collections/CollectionMap', () => ({
default: (props: MapProps) => {
seen.map = props;
return <div data-testid="map">{`markers:${props.places.length}`}</div>;
},
}));
vi.mock('../../../../src/mobile/screens/collections/MLibraryPlaceSheet', () => ({
default: (props: SheetProps) => {
seen.sheet = props;
return props.open ? <div data-testid="place-sheet" /> : null;
},
}));
vi.mock('../../../../src/mobile/screens/collections/MCollTripPickerSheet', () => ({
default: (props: PickerProps) => {
seen.picker = props;
return props.open ? <div data-testid="trip-picker" /> : null;
},
}));
const CATEGORIES = [
{ id: 3, name: 'Restaurant', color: '#E8843D', icon: 'Utensils' },
{ id: 5, name: 'Museum', color: '#9B5DE5', icon: 'Landmark' },
] as unknown as Category[];
type Props = Omit<ComponentProps<typeof MPlacesLibrary>, 't'>;
function Harness(props: Props) {
const { t } = useTranslation();
return <MPlacesLibrary {...props} t={t} />;
}
function captured<T>(value: T | null): T {
if (value == null) throw new Error('not rendered');
return value;
}
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<Props> = {}) {
seen.lib = libraryState(lib);
const props: Props = {
categories: CATEGORIES,
language: 'en',
dark: false,
view: 'list',
onView: vi.fn(),
navigate: vi.fn(),
...over,
};
const view = render(<Harness {...props} />);
return { ...view, props, lib: captured(seen.lib) };
}
beforeEach(() => {
resetAllStores();
seen.lib = null;
seen.map = null;
seen.sheet = null;
seen.picker = null;
openSave.mockReset();
copyToTrip.mockReset();
copyToTrip.mockResolvedValue({ copied: 1, skipped: [] });
useSaveToCollectionStore.setState({ open: openSave });
useCollectionStore.setState({ copyToTrip });
});
describe('MPlacesLibrary: the head', () => {
it('FE-MOB-PLACESLIB-001: the list or map switch shows which one is on and asks for the other', async () => {
const user = userEvent.setup();
const { props } = setup();
expect(screen.getByRole('button', { name: 'List' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByRole('button', { name: 'Map' })).toHaveAttribute('aria-pressed', 'false');
await user.click(screen.getByRole('button', { name: 'Map' }));
expect(props.onView).toHaveBeenCalledWith('map');
});
it('FE-MOB-PLACESLIB-002: the search shows and changes the search', () => {
const { lib } = setup({ search: 'pan' });
const input = screen.getByRole('textbox', { name: 'Search all places' });
expect(input).toHaveValue('pan');
fireEvent.change(input, { target: { value: 'pant' } });
expect(lib.setSearch).toHaveBeenCalledWith('pant');
});
it('FE-MOB-PLACESLIB-003: where from opens with its counts and picks a kind', async () => {
const user = userEvent.setup();
const { lib } = setup({ counts: { all: 9, trip: 6, list: 4 } });
const [kindChip] = screen.getAllByRole('button', { name: 'All' });
await user.click(kindChip);
expect(kindChip).toHaveAttribute('aria-expanded', 'true');
expect(screen.getByRole('button', { name: /^Trips/ })).toHaveTextContent('Trips6');
expect(screen.getByRole('button', { name: /^Lists/ })).toHaveTextContent('Lists4');
await user.click(screen.getByRole('button', { name: /^Trips/ }));
expect(lib.setKind).toHaveBeenCalledWith('trip');
expect(screen.queryByRole('button', { name: /^Lists/ })).not.toBeInTheDocument();
});
it('FE-MOB-PLACESLIB-004: a chosen kind names itself on its chip', () => {
setup({ kind: 'list' });
expect(screen.getByRole('button', { name: 'Lists' })).toHaveAttribute('aria-expanded', 'false');
});
it('FE-MOB-PLACESLIB-005: status lists every status and picks one or all', async () => {
const user = userEvent.setup();
const { lib } = setup({ status: 'visited' });
const statusChip = screen.getByRole('button', { name: 'Visited' });
await user.click(statusChip);
await user.click(screen.getByRole('button', { name: 'Want to go' }));
expect(lib.setStatus).toHaveBeenLastCalledWith('want');
await user.click(statusChip);
expect(screen.getByRole('button', { name: 'Want to revisit' })).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Idea' }));
expect(lib.setStatus).toHaveBeenLastCalledWith('idea');
await user.click(statusChip);
const allRows = screen.getAllByRole('button', { name: 'All' });
await user.click(allRows[allRows.length - 1]);
expect(lib.setStatus).toHaveBeenLastCalledWith('all');
});
it('FE-MOB-PLACESLIB-006: category names the current one and picks another or all', async () => {
const user = userEvent.setup();
const { lib } = setup({ categoryId: 3 });
const chip = screen.getByRole('button', { name: 'Category: Restaurant' });
await user.click(chip);
await user.click(screen.getByRole('button', { name: 'Museum' }));
expect(lib.setCategoryId).toHaveBeenLastCalledWith(5);
await user.click(chip);
const allRows = screen.getAllByRole('button', { name: 'All' });
await user.click(allRows[allRows.length - 1]);
expect(lib.setCategoryId).toHaveBeenLastCalledWith('all');
});
it('FE-MOB-PLACESLIB-007: without categories there is no category chip', () => {
setup({}, { categories: [] });
expect(screen.queryByRole('button', { name: /^Category:/ })).not.toBeInTheDocument();
});
it('FE-MOB-PLACESLIB-008: the order chip picks name or last changed', async () => {
const user = userEvent.setup();
const { lib } = setup();
await user.click(screen.getByRole('button', { name: 'Sort' }));
expect(screen.getByRole('button', { name: 'Name (A–Z)' })).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Last changed' }));
expect(lib.setSort).toHaveBeenCalledWith('updated');
});
it('FE-MOB-PLACESLIB-009: a tap beside the open dropdown or on its chip again closes it', async () => {
const user = userEvent.setup();
setup();
const sortChip = screen.getByRole('button', { name: 'Sort' });
await user.click(sortChip);
await user.click(screen.getByRole('button', { name: 'Close' }));
expect(screen.queryByRole('button', { name: 'Last changed' })).not.toBeInTheDocument();
await user.click(sortChip);
expect(sortChip).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(sortChip);
expect(screen.queryByRole('button', { name: 'Last changed' })).not.toBeInTheDocument();
});
});
describe('MPlacesLibrary: the places', () => {
it('FE-MOB-PLACESLIB-010: a card per place names it, its address and its first origin, the rest counted', () => {
setup({ entries: threeEntries() });
const pantheon = screen.getByRole('button', { name: /Pantheon/ });
expect(pantheon).toHaveTextContent('Piazza della Rotonda');
expect(pantheon).toHaveTextContent('Rome 2026');
const trevi = screen.getByRole('button', { name: /Trevi Fountain/ });
expect(trevi).toHaveTextContent('Rome 2026+1');
expect(screen.getByRole('button', { name: /Secret garden/ })).toHaveTextContent('Wishlist');
});
it('FE-MOB-PLACESLIB-011: a card opens its place', async () => {
const user = userEvent.setup();
const { lib } = setup({ entries: threeEntries() });
await user.click(screen.getByRole('button', { name: /Secret garden/ }));
expect(lib.show).toHaveBeenCalledWith('list:30');
});
it('FE-MOB-PLACESLIB-012: "more" counts what is left and loads it, and waits while it loads', async () => {
const user = userEvent.setup();
const { lib, unmount } = setup({ entries: threeEntries(), total: 4, hasMore: true });
await user.click(screen.getByRole('button', { name: 'Show 1 more' }));
expect(lib.loadMore).toHaveBeenCalledTimes(1);
unmount();
setup({ entries: threeEntries(), total: 4, hasMore: true, loadingMore: true });
expect(screen.getByRole('button', { name: 'Show 1 more' })).toBeDisabled();
});
it('FE-MOB-PLACESLIB-013: offline, failed, loading and empty each say so', () => {
const offline = setup({ offline: true });
expect(screen.getByText('All places needs a connection.')).toBeInTheDocument();
offline.unmount();
const failed = setup({ error: 'Library is down' });
expect(screen.getByRole('alert')).toHaveTextContent('Library is down');
failed.unmount();
const loading = setup({ loading: true });
expect(loading.container.querySelector('.animate-spin')).not.toBeNull();
loading.unmount();
const empty = setup();
expect(screen.getByText('No places yet')).toBeInTheDocument();
empty.unmount();
setup({ filtered: true });
expect(screen.getByText('No matches')).toBeInTheDocument();
});
it('FE-MOB-PLACESLIB-014: the map shows the places with a position and a pin opens its place', () => {
const { lib } = setup({ entries: threeEntries() }, { view: 'map', dark: true });
expect(screen.getByTestId('map')).toHaveTextContent('markers:2');
const map = captured(seen.map);
expect(map.dark).toBe(true);
expect(map.places.map((p) => p.name)).toEqual(['Pantheon', 'Trevi Fountain']);
act(() => map.onOpenPlace(2));
expect(lib.show).toHaveBeenCalledWith('trip:2');
act(() => map.onOpenPlace(99));
expect(lib.show).toHaveBeenCalledTimes(1);
expect(screen.queryByRole('button', { name: /Pantheon/ })).not.toBeInTheDocument();
});
});
describe('MPlacesLibrary: the place sheet', () => {
it('FE-MOB-PLACESLIB-015: the sheet is open while a place is and gets what the hook loaded', () => {
const detail = libraryDetail(libraryEntry(), [tripDetail()]);
const { lib, unmount } = setup({ selectedKey: 'trip:42', detail, detailLoading: true, cover: '/uploads/c.jpg' });
const sheet = captured(seen.sheet);
expect(screen.getByTestId('place-sheet')).toBeInTheDocument();
expect(sheet.data).toBe(detail);
expect(sheet.loading).toBe(true);
expect(sheet.cover).toBe('/uploads/c.jpg');
act(() => sheet.onClose());
expect(lib.close).toHaveBeenCalledTimes(1);
unmount();
setup();
expect(captured(seen.sheet).open).toBe(false);
});
it('FE-MOB-PLACESLIB-016: opening a list or a trip goes to its route', () => {
const { props } = setup({ selectedKey: 'trip:42' });
const sheet = captured(seen.sheet);
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');
});
it('FE-MOB-PLACESLIB-017: 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({ selectedKey: 'trip:42', detail: libraryDetail(entry, [tripDetail()]) });
const info = libraryInfo({ name: 'Colosseo', description: 'Arena', website: 'https://c.example', phone: '+39' });
act(() => captured(seen.sheet).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: null,
website: 'https://c.example',
phone: '+39',
});
});
it('FE-MOB-PLACESLIB-018: copying closes the place and opens the trip picker, which copies it', async () => {
const { lib } = setup({ selectedKey: 'list:30' });
expect(captured(seen.picker).open).toBe(false);
expect(captured(seen.picker).count).toBe(1);
act(() => captured(seen.sheet).onCopyToTrip(900));
expect(lib.close).toHaveBeenCalledTimes(1);
expect(screen.getByTestId('trip-picker')).toBeInTheDocument();
const picker = captured(seen.picker);
const carry = { include_notes: false } as Parameters<PickerProps['onCopy']>[1];
await act(async () => {
await picker.onCopy(7, carry);
});
expect(copyToTrip).toHaveBeenCalledWith(7, [900], undefined, carry);
act(() => picker.onClose());
expect(screen.queryByTestId('trip-picker')).not.toBeInTheDocument();
});
});