test(places): cover the place sheet sections, tags, trip lists and the visited filter

This commit is contained in:
Maurice
2026-11-29 21:16:39 +01:00
parent d008331e5f
commit c944ef6de5
60 changed files with 4182 additions and 44 deletions
@@ -30,7 +30,6 @@ describe('CategoryTileMenu', () => {
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();
});
@@ -1,5 +1,5 @@
// FE-COMP-COPYCARRY-001 to FE-COMP-COPYCARRY-002
import { fireEvent, render, screen } from '../../../tests/helpers/render';
// FE-COMP-COPYCARRY-001 to FE-COMP-COPYCARRY-004
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
import CopyCarryPanel from './CopyCarryPanel';
const t = (k: string) => k;
@@ -47,4 +47,79 @@ describe.each(['dialog', 'sheet'] as const)('CopyCarryPanel (%s)', (variant) =>
expect(screen.queryByText('collections.copyCarry.notes')).toBeNull();
expect(screen.getByRole('button', { name: 'Coffee' })).toHaveAttribute('aria-pressed', 'false');
});
it('FE-COMP-COPYCARRY-003: offers the own tags as their own group and toggles them apart from the labels', () => {
const onToggleTag = vi.fn();
const onTogglePersonalTag = vi.fn();
render(
<CopyCarryPanel
options={{
hasNotes: false,
tags: [{ id: 7, name: 'Coffee' }],
personalTags: [
{ id: 3, name: 'Wine', color: '#aa0000' },
{ id: 4, name: 'Beach', color: null },
],
}}
includeNotes={false}
onIncludeNotes={vi.fn()}
tagIds={[]}
onToggleTag={onToggleTag}
personalTagIds={[4]}
onTogglePersonalTag={onTogglePersonalTag}
variant={variant}
t={t}
/>
);
const own = screen.getByRole('group', { name: 'collections.copyCarry.personalTags' });
expect(screen.getByText('collections.copyCarry.personalTagsHint')).toBeInTheDocument();
expect(within(own).getByRole('button', { name: 'Beach' })).toHaveAttribute('aria-pressed', 'true');
expect(within(own).getByRole('button', { name: 'Wine' })).toHaveAttribute('aria-pressed', 'false');
expect(within(own).queryByRole('button', { name: 'Coffee' })).toBeNull();
fireEvent.click(within(own).getByRole('button', { name: 'Wine' }));
expect(onTogglePersonalTag).toHaveBeenCalledWith(3);
expect(onToggleTag).not.toHaveBeenCalled();
});
it('FE-COMP-COPYCARRY-004: no own tags group without tags or without a handler, and nothing picked by default', () => {
const personalTags = [{ id: 3, name: 'Wine' }];
const { rerender } = render(
<CopyCarryPanel
options={{ hasNotes: false, tags: [], personalTags }}
includeNotes={false}
onIncludeNotes={vi.fn()}
tagIds={[]}
onToggleTag={vi.fn()}
variant={variant}
t={t}
/>
);
expect(screen.queryByText('collections.copyCarry.personalTags')).toBeNull();
rerender(
<CopyCarryPanel
options={{ hasNotes: false, tags: [], personalTags: [] }}
includeNotes={false}
onIncludeNotes={vi.fn()}
tagIds={[]}
onToggleTag={vi.fn()}
onTogglePersonalTag={vi.fn()}
variant={variant}
t={t}
/>
);
expect(screen.queryByText('collections.copyCarry.personalTags')).toBeNull();
rerender(
<CopyCarryPanel
options={{ hasNotes: false, tags: [], personalTags }}
includeNotes={false}
onIncludeNotes={vi.fn()}
tagIds={[]}
onToggleTag={vi.fn()}
onTogglePersonalTag={vi.fn()}
variant={variant}
t={t}
/>
);
expect(screen.getByRole('button', { name: 'Wine' })).toHaveAttribute('aria-pressed', 'false');
});
});
@@ -0,0 +1,28 @@
// FE-COMP-ENTRYTAGDOTS-001 to FE-COMP-ENTRYTAGDOTS-002
import { render, screen } from '../../../tests/helpers/render';
import EntryTagDots from './EntryTagDots';
describe('EntryTagDots', () => {
it('FE-COMP-ENTRYTAGDOTS-001: draws nothing for a row without tags', () => {
const { container, rerender } = render(<EntryTagDots tags={undefined} />);
expect(container).toBeEmptyDOMElement();
rerender(<EntryTagDots tags={[]} />);
expect(container).toBeEmptyDOMElement();
});
it('FE-COMP-ENTRYTAGDOTS-002: one dot per tag up to four, named by all of them, in their colour or the accent', () => {
const tags = [
{ id: 1, name: 'Beach', color: '#ff0000' },
{ id: 2, name: 'Coffee', color: null },
{ id: 3, name: 'Late', color: '#00ff00' },
{ id: 4, name: 'Wine', color: '#0000ff' },
{ id: 5, name: 'Zoo', color: '#ffff00' },
];
render(<EntryTagDots tags={tags} />);
const dots = screen.getByRole('img', { name: 'Beach, Coffee, Late, Wine, Zoo' });
const spans = Array.from(dots.children) as HTMLElement[];
expect(spans).toHaveLength(4);
expect(spans[0].style.background).toBe('rgb(255, 0, 0)');
expect(spans[1].style.background).toBe('var(--accent)');
});
});
@@ -0,0 +1,163 @@
// FE-COMP-ENTRYTAGSSEC-001 to FE-COMP-ENTRYTAGSSEC-009: the reader's own tags in the
// desktop sheet of All places (PLC-21), rendered against a mocked useEntryTags.
import type { PlacesLibraryDetailResponse, Tag } from '@trek/shared';
import { bothOrigins } from '../../../tests/helpers/placesLibrary';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import EntryTagsSection from './EntryTagsSection';
import type { useEntryTags } from './useEntryTags';
type EntryTags = ReturnType<typeof useEntryTags>;
const hook = vi.hoisted(() => ({ state: null as unknown as EntryTags, args: [] as unknown[] }));
vi.mock('./useEntryTags', () => ({
useEntryTags: (args: unknown) => {
hook.args.push(args);
return hook.state;
},
}));
vi.mock('../shared/ConfirmDialog', () => ({
default: ({ isOpen, onConfirm, title }: { isOpen: boolean; onConfirm: () => void; title: string }) =>
isOpen ? (
<div role="dialog" aria-label={title}>
<button type="button" onClick={onConfirm}>
confirm
</button>
</div>
) : null,
}));
const t = (k: string, p?: Record<string, unknown>) => (p ? `${k}:${JSON.stringify(p)}` : k);
const tag = (id: number, name: string, color = '#aa0000'): Tag => ({ id, user_id: 1, trip_id: null, name, color });
const BEACH = tag(1, 'Beach');
const WINE = tag(3, 'Wine', '');
function state(over: Partial<EntryTags> = {}): EntryTags {
return {
all: [BEACH, WINE],
assigned: [],
assignedIds: [],
query: '',
setQuery: vi.fn(),
matches: [BEACH, WINE],
canCreate: false,
toggle: vi.fn(() => Promise.resolve()),
createAndAdd: vi.fn(() => Promise.resolve()),
rename: vi.fn(() => Promise.resolve()),
destroy: vi.fn(() => Promise.resolve()),
busy: false,
...over,
};
}
function mount(over: Partial<EntryTags> = {}, data: PlacesLibraryDetailResponse | null = bothOrigins()) {
hook.state = state(over);
const onChanged = vi.fn();
render(<EntryTagsSection data={data} onChanged={onChanged} t={t} />);
return { tags: hook.state, onChanged };
}
const openPicker = () => fireEvent.click(screen.getByRole('button', { name: 'placeTags.add' }));
beforeEach(() => {
hook.args.length = 0;
});
describe('EntryTagsSection', () => {
it('FE-COMP-ENTRYTAGSSEC-001: without tags on the place it says they are private, and hands the entry to the hook', () => {
const data = bothOrigins();
const { onChanged } = mount({}, data);
expect(screen.getByText('placeTags.private')).toBeInTheDocument();
expect(screen.queryByRole('menu')).toBeNull();
expect(hook.args[0]).toEqual({ entry: data.entry, onChanged, t });
mount({}, null);
expect(hook.args.at(-1)).toMatchObject({ entry: null });
});
it('FE-COMP-ENTRYTAGSSEC-002: shows the carried tags as chips that take a tag off', () => {
const { tags } = mount({ assigned: [{ id: 1, name: 'Beach', color: null }], assignedIds: [1] });
expect(screen.queryByText('placeTags.private')).toBeNull();
expect(screen.getByText('Beach')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'placeTags.removeFrom:{"name":"Beach"}' }));
expect(tags.toggle).toHaveBeenCalledWith(1);
});
it('FE-COMP-ENTRYTAGSSEC-003: the picker ticks the carried tags and toggles one on a click', () => {
const { tags } = mount({ assignedIds: [3] });
openPicker();
expect(screen.getByRole('button', { name: 'placeTags.add' })).toHaveAttribute('aria-expanded', 'true');
expect(screen.getByRole('menuitemcheckbox', { name: 'Wine' })).toHaveAttribute('aria-checked', 'true');
expect(screen.getByRole('menuitemcheckbox', { name: 'Beach' })).toHaveAttribute('aria-checked', 'false');
fireEvent.click(screen.getByRole('menuitemcheckbox', { name: 'Beach' }));
expect(tags.toggle).toHaveBeenCalledWith(1);
});
it('FE-COMP-ENTRYTAGSSEC-004: typing goes to the search, and a new name is made from it by click or Enter', () => {
const { tags } = mount({ query: ' Rooftop ', matches: [], canCreate: true });
openPicker();
fireEvent.change(screen.getByRole('textbox', { name: 'placeTags.search' }), { target: { value: 'Roof' } });
expect(tags.setQuery).toHaveBeenCalledWith('Roof');
expect(screen.queryByText('placeTags.none')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'placeTags.create:{"name":"Rooftop"}' }));
expect(tags.createAndAdd).toHaveBeenCalledTimes(1);
fireEvent.submit(screen.getByRole('textbox', { name: 'placeTags.search' }));
expect(tags.createAndAdd).toHaveBeenCalledTimes(2);
});
it('FE-COMP-ENTRYTAGSSEC-005: Enter makes nothing when the name exists, and no match says so', () => {
const { tags } = mount({ query: 'zz', matches: [], canCreate: false });
openPicker();
expect(screen.getByText('placeTags.none')).toBeInTheDocument();
fireEvent.submit(screen.getByRole('textbox', { name: 'placeTags.search' }));
expect(tags.createAndAdd).not.toHaveBeenCalled();
});
it('FE-COMP-ENTRYTAGSSEC-006: the create row is disabled while a change runs', () => {
mount({ query: 'New', matches: [], canCreate: true, busy: true });
openPicker();
expect(screen.getByRole('button', { name: 'placeTags.create:{"name":"New"}' })).toBeDisabled();
});
it('FE-COMP-ENTRYTAGSSEC-007: renames a tag in place, or cancels without asking', () => {
const { tags } = mount();
openPicker();
fireEvent.click(screen.getAllByRole('button', { name: 'placeTags.rename' })[0]);
const input = screen.getByRole('textbox', { name: 'placeTags.rename' });
expect(input).toHaveValue('Beach');
fireEvent.change(input, { target: { value: 'Seaside' } });
fireEvent.click(screen.getByRole('button', { name: 'common.save' }));
expect(tags.rename).toHaveBeenCalledWith(1, 'Seaside');
expect(screen.getByRole('menuitemcheckbox', { name: 'Beach' })).toBeInTheDocument();
fireEvent.click(screen.getAllByRole('button', { name: 'placeTags.rename' })[1]);
fireEvent.click(screen.getByRole('button', { name: 'common.cancel' }));
expect(tags.rename).toHaveBeenCalledTimes(1);
expect(screen.queryByRole('textbox', { name: 'placeTags.rename' })).toBeNull();
});
it('FE-COMP-ENTRYTAGSSEC-008: deleting asks first, and a click in the dialog keeps the picker open', () => {
const { tags } = mount();
openPicker();
fireEvent.click(screen.getAllByRole('button', { name: 'placeTags.delete' })[1]);
const dialog = screen.getByRole('dialog', { name: 'placeTags.deleteTitle:{"name":"Wine"}' });
fireEvent.pointerDown(dialog);
expect(screen.getByRole('menu')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'confirm' }));
expect(tags.destroy).toHaveBeenCalledWith(3);
});
it('FE-COMP-ENTRYTAGSSEC-009: a press outside closes the picker, one inside keeps it, and the button toggles it', () => {
mount();
openPicker();
fireEvent.pointerDown(screen.getByRole('menu'));
expect(screen.getByRole('menu')).toBeInTheDocument();
fireEvent.pointerDown(document.body);
expect(screen.queryByRole('menu')).toBeNull();
openPicker();
openPicker();
expect(screen.queryByRole('menu')).toBeNull();
});
});
@@ -24,7 +24,6 @@ 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');
@@ -23,13 +23,11 @@ describe('LibraryOrigins', () => {
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', () => {
it('FE-COMP-LIBORIGINS-002: trips come before lists', () => {
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', () => {
@@ -1,4 +1,4 @@
// FE-COMP-LIBPLACEDETAIL-001 to FE-COMP-LIBPLACEDETAIL-013
// FE-COMP-LIBPLACEDETAIL-001 to FE-COMP-LIBPLACEDETAIL-017
import userEvent from '@testing-library/user-event';
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import React from 'react';
@@ -19,6 +19,22 @@ import { type NavigationTarget, openNavigationTarget } from '../Planner/placeNav
import LibraryPlaceDetail from './LibraryPlaceDetail';
const nav = vi.hoisted(() => ({ targets: [] as NavigationTarget[] }));
/** The props each section below the origins was last handed; they read their own stores. */
const sections = vi.hoisted(() => ({}) as Record<string, Record<string, unknown>>);
const section = vi.hoisted(
() => (name: string) =>
function Section(props: Record<string, unknown>) {
sections[name] = props;
return <div data-testid={`section-${name}`} />;
}
);
vi.mock('./EntryTagsSection', () => ({ default: section('tags') }));
vi.mock('./OriginNotesSection', () => ({ default: section('notes') }));
vi.mock('./PlaceMediaSection', () => ({ default: section('media') }));
vi.mock('./VisitsSection', () => ({ default: section('visits') }));
vi.mock('./PlaceActivitiesSection', () => ({ default: section('activities') }));
vi.mock('./PlaceHistorySection', () => ({ default: section('history') }));
vi.mock('../Planner/placeNavigation', () => ({
getNavigationTargets: () => nav.targets,
@@ -82,6 +98,7 @@ function setup(over: Partial<Props> = {}) {
onOpenTrip: vi.fn(),
onSaveToList: vi.fn(),
onCopyToTrip: vi.fn(),
onNotesSaved: vi.fn(),
...over,
};
const view = render(<Harness {...props} />);
@@ -91,6 +108,7 @@ function setup(over: Partial<Props> = {}) {
beforeEach(() => {
nav.targets = [];
vi.mocked(openNavigationTarget).mockClear();
for (const key of Object.keys(sections)) delete sections[key];
});
describe('LibraryPlaceDetail: the sheet', () => {
@@ -142,7 +160,7 @@ describe('LibraryPlaceDetail: the sheet', () => {
});
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 () => {
it('FE-COMP-LIBPLACEDETAIL-006: a trip shows its planned day, its name there, a stay and a booking, its notes go below', async () => {
const user = userEvent.setup();
const { props } = setup();
expect(screen.getByText('In your trips')).toBeInTheDocument();
@@ -152,18 +170,19 @@ describe('LibraryPlaceDetail: where the place sits', () => {
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();
// The notes moved out of the card into the notes section under the origins.
expect(within(card).queryByText('Book the underground tour')).not.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 () => {
it('FE-COMP-LIBPLACEDETAIL-007: a list beside a trip shows its status under its name, its labels and votes', 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(card.querySelector('.col-origin-title .sub')?.textContent).toBe('Want to go');
expect(within(card).getByText('Must see')).toBeInTheDocument();
expect(within(card).getByText('4.5 from 2 votes')).toBeInTheDocument();
expect(within(card).queryByText('Notes')).not.toBeInTheDocument();
@@ -243,3 +262,49 @@ describe('LibraryPlaceDetail: what to do with it', () => {
expect(screen.queryByRole('menu')).not.toBeInTheDocument();
});
});
describe('LibraryPlaceDetail: the look of its origins and the sections below', () => {
it('FE-COMP-LIBPLACEDETAIL-014: a trip with a cover shows it, a list wears its own symbol and colour', () => {
const entry = libraryEntry({
origins: [
tripOrigin({ trip_cover: '/uploads/covers/rome.jpg' }),
listOrigin({ collection_color: '#ff0000', collection_icon: 'star' }),
],
});
const { container } = setup({ data: libraryDetail(entry, [tripDetail(), listDetail()]) });
expect(container.querySelector('.col-origin-cover')).toHaveAttribute('src', '/uploads/covers/rome.jpg');
const ico = container.querySelector<HTMLElement>('.col-origin-ico-list');
expect(ico?.style.getPropertyValue('--list')).toBe('#ff0000');
expect(container.querySelector('.col-origin-pair')).not.toBeNull();
});
it('FE-COMP-LIBPLACEDETAIL-015: a list on its own keeps its status badge and the accent colour', () => {
const entry = libraryEntry({ key: 'list:900', origins: [listOrigin()] });
const { container } = setup({ data: libraryDetail(entry, [listDetail()]) });
const card = screen.getByRole('button', { name: 'Open in the list: Favourites' });
expect(within(card).getByText('Want to go')).toBeInTheDocument();
expect(card.querySelector('.col-origin-title .sub')).toBeNull();
expect(container.querySelector<HTMLElement>('.col-origin-ico-list')?.style.getPropertyValue('--list')).toBe(
'var(--accent)'
);
expect(container.querySelector('.col-origin-pair')).toBeNull();
});
it('FE-COMP-LIBPLACEDETAIL-016: tags, notes, media, visits, activities and history follow, wired to the place', () => {
const { props } = setup();
for (const name of ['tags', 'notes', 'media', 'visits', 'activities', 'history']) {
expect(screen.getByTestId(`section-${name}`)).toBeInTheDocument();
}
expect(sections.tags).toMatchObject({ data: props.data, onChanged: props.onNotesSaved });
expect(sections.notes).toMatchObject({ data: props.data, onSaved: props.onNotesSaved });
expect(sections.media).toMatchObject({ entry: props.data?.entry });
expect(sections.visits).toMatchObject({ entry: props.data?.entry, language: 'en' });
expect(sections.activities).toMatchObject({ entry: props.data?.entry, language: 'en' });
expect(sections.history).toMatchObject({ entry: props.data?.entry, language: 'en' });
});
it('FE-COMP-LIBPLACEDETAIL-017: while it loads no section is drawn', () => {
setup({ data: null, loading: true });
expect(screen.queryByTestId('section-notes')).toBeNull();
});
});
@@ -0,0 +1,91 @@
// FE-COMP-ORIGINNOTESSEC-001 to FE-COMP-ORIGINNOTESSEC-005: the notes section of the desktop place sheet.
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import type { MockInstance } from 'vitest';
import {
libraryDetail,
libraryEntry,
listDetail,
listOrigin,
tripDetail,
tripOrigin,
} from '../../../tests/helpers/placesLibrary';
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
import OriginNotesSection from './OriginNotesSection';
const toastError = vi.hoisted(() => vi.fn());
vi.mock('../shared/Toast', () => {
const toast = { error: toastError, success: vi.fn(), warning: vi.fn(), info: vi.fn() };
return { useToast: () => toast };
});
const t = (k: string, p?: Record<string, unknown>) => (p ? `${k}:${JSON.stringify(p)}` : k);
function data(tripNotes: string | null, canEdit = true): PlacesLibraryDetailResponse {
const entry = libraryEntry({
origins: [tripOrigin({ can_edit: canEdit }), listOrigin({ can_edit: canEdit })],
});
return libraryDetail(entry, [tripDetail({ notes: tripNotes }), listDetail()]);
}
let saveNotes: MockInstance<typeof placesLibraryRepo.saveNotes>;
beforeEach(() => {
toastError.mockReset();
saveNotes = vi.spyOn(placesLibraryRepo, 'saveNotes').mockResolvedValue(undefined);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('OriginNotesSection', () => {
it('FE-COMP-ORIGINNOTESSEC-001: nothing to read and nowhere to write leaves the section out', () => {
const { container } = render(<OriginNotesSection data={data(null, false)} onSaved={vi.fn()} t={t} />);
expect(container).toBeEmptyDOMElement();
});
it('FE-COMP-ORIGINNOTESSEC-002: a read-only note shows with its source and no pencil or add', () => {
render(<OriginNotesSection data={data('Buy tickets online', false)} onSaved={vi.fn()} t={t} />);
expect(screen.getByText('collections.notes')).toBeInTheDocument();
expect(screen.getByText('Rome 2026')).toBeInTheDocument();
expect(screen.getByText('Buy tickets online')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'placeNotes.edit' })).toBeNull();
expect(screen.queryByRole('button', { name: /placeNotes\.add/ })).toBeNull();
});
it('FE-COMP-ORIGINNOTESSEC-003: edits a note in place and saves it', async () => {
const onSaved = vi.fn();
render(<OriginNotesSection data={data('Buy tickets online')} onSaved={onSaved} t={t} />);
fireEvent.click(screen.getByRole('button', { name: 'placeNotes.edit' }));
const field = screen.getByRole('textbox', { name: 'placeNotes.fieldLabel:{"source":"Rome 2026"}' });
expect(field).toHaveValue('Buy tickets online');
// The pencil hides while its note is open.
expect(screen.queryByRole('button', { name: 'placeNotes.edit' })).toBeNull();
fireEvent.change(field, { target: { value: 'Tickets at the gate' } });
fireEvent.click(screen.getByRole('button', { name: 'common.save' }));
await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1));
expect(saveNotes).toHaveBeenCalledWith({ kind: 'trip', trip_id: 5, place_id: 42 }, 'Tickets at the gate');
expect(screen.queryByRole('textbox')).toBeNull();
});
it('FE-COMP-ORIGINNOTESSEC-004: "+ Note" goes straight to the one empty place, and cancel closes it', () => {
render(<OriginNotesSection data={data('Buy tickets online')} onSaved={vi.fn()} t={t} />);
fireEvent.click(screen.getByRole('button', { name: /placeNotes\.add/ }));
expect(screen.getByRole('textbox', { name: 'placeNotes.fieldLabel:{"source":"Favourites"}' })).toHaveValue('');
fireEvent.click(screen.getByRole('button', { name: 'common.cancel' }));
expect(screen.queryByRole('textbox')).toBeNull();
expect(saveNotes).not.toHaveBeenCalled();
});
it('FE-COMP-ORIGINNOTESSEC-005: with several empty places "+ Note" asks which one, then opens it', () => {
render(<OriginNotesSection data={data(null)} onSaved={vi.fn()} t={t} />);
fireEvent.click(screen.getByRole('button', { name: /placeNotes\.add/ }));
expect(screen.queryByRole('textbox')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: /Favourites/ }));
expect(screen.getByRole('textbox', { name: 'placeNotes.fieldLabel:{"source":"Favourites"}' })).toBeInTheDocument();
// The chooser closes and the other trip stays a target.
expect(screen.queryByRole('button', { name: /Rome 2026/ })).toBeNull();
});
});
@@ -0,0 +1,115 @@
// FE-COMP-PLACEACTSECTION-001 to FE-COMP-PLACEACTSECTION-006: the tours and bookings of a
// place in the desktop sheet of All places (PLC-18), against a mocked hook.
import {
activitiesState,
activityCandidate,
listSource,
placeActivity,
tripSource,
} from '../../../tests/helpers/placeExtras';
import { libraryEntry } from '../../../tests/helpers/placesLibrary';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import PlaceActivitiesSection from './PlaceActivitiesSection';
import { usePlaceActivities } from './usePlaceActivities';
const mockNavigate = vi.fn();
vi.mock('react-router', async (importOriginal) => {
const actual = await importOriginal<typeof import('react-router')>();
return { ...actual, useNavigate: () => mockNavigate };
});
vi.mock('./usePlaceActivities', async (importOriginal) => {
const actual = await importOriginal<typeof import('./usePlaceActivities')>();
return { ...actual, usePlaceActivities: vi.fn() };
});
const hook = vi.mocked(usePlaceActivities);
const t = (k: string) => k;
function show(state = activitiesState()) {
hook.mockReturnValue(state);
render(<PlaceActivitiesSection entry={libraryEntry()} language="en-GB" t={t} />);
return state;
}
beforeEach(() => {
mockNavigate.mockClear();
hook.mockReset();
});
describe('PlaceActivitiesSection', () => {
it('FE-COMP-PLACEACTSECTION-001: is not there with nothing linked and nothing to link', () => {
show();
expect(screen.queryByText('placeActivities.title')).toBeNull();
});
it('FE-COMP-PLACEACTSECTION-002: an activity opens where it lives, a said link comes off again', () => {
const linked = placeActivity();
const implicit = placeActivity({
key: 'tour:8',
type: 'tour',
title: 'Forum walk',
target: { kind: 'tour', trip_id: 5, tour_id: 8 },
can_unlink: false,
});
const state = show(activitiesState({ activities: [linked, implicit] }));
fireEvent.click(screen.getByRole('button', { name: /Colosseum tickets/ }));
expect(mockNavigate).toHaveBeenCalledWith('/trips/5?booking=7');
fireEvent.click(screen.getByRole('button', { name: /Forum walk/ }));
expect(mockNavigate).toHaveBeenLastCalledWith('/trips/5?tour=8');
const unlink = screen.getAllByRole('button', { name: 'placeActivities.unlink' });
expect(unlink).toHaveLength(1);
fireEvent.click(unlink[0]);
expect(state.unlink).toHaveBeenCalledWith(linked);
expect(screen.getByText('placeActivities.atThisPlace')).toBeInTheDocument();
// Nothing more to link: no "+ Link".
expect(screen.queryByRole('button', { name: /placeActivities\.link/ })).toBeNull();
});
it('FE-COMP-PLACEACTSECTION-003: with nothing linked yet but rights to link, it says so and offers the picker', () => {
const state = show(activitiesState({ canLink: true }));
expect(screen.getByText('placeActivities.none')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /placeActivities\.link/ }));
expect(state.openPicker).toHaveBeenCalledTimes(1);
});
it('FE-COMP-PLACEACTSECTION-004: the picker lists the candidates of every source and links the picked one', () => {
const booking = activityCandidate();
const tour = activityCandidate({ key: 'collection_tour:3', type: 'tour', title: 'Old town walk' });
const state = show(
activitiesState({
canLink: true,
picking: [
{ source: tripSource(), candidates: [booking] },
{ source: listSource(), candidates: [tour] },
],
})
);
expect(screen.getByText('placeActivities.pickTitle')).toBeInTheDocument();
expect(screen.queryByText('placeActivities.none')).toBeNull();
expect(screen.queryByText('placeActivities.nothingToLink')).toBeNull();
// The "+ Link" button gives way to the open picker.
expect(screen.queryByRole('button', { name: /placeActivities\.link/ })).toBeNull();
fireEvent.click(screen.getByRole('button', { name: /Old town walk/ }));
expect(state.link).toHaveBeenCalledWith(listSource(), tour);
fireEvent.click(screen.getByRole('button', { name: 'common.close' }));
expect(state.closePicker).toHaveBeenCalledTimes(1);
});
it('FE-COMP-PLACEACTSECTION-005: a picker without candidates says there is nothing to link', () => {
show(activitiesState({ canLink: true, picking: [{ source: tripSource(), candidates: [] }] }));
expect(screen.getByText('placeActivities.nothingToLink')).toBeInTheDocument();
});
it('FE-COMP-PLACEACTSECTION-006: while a write runs the buttons wait', () => {
show(
activitiesState({
activities: [placeActivity()],
canLink: true,
busy: true,
})
);
expect(screen.getByRole('button', { name: /placeActivities\.link/ })).toBeDisabled();
expect(screen.getByRole('button', { name: 'placeActivities.unlink' })).toBeDisabled();
});
});
@@ -0,0 +1,72 @@
// FE-COMP-PLACEHISTSECTION-001 to FE-COMP-PLACEHISTSECTION-005: the change history of a
// place in the desktop sheet of All places (PLC-14), against a mocked hook.
import { historyEntries, historyEntry, historyState } from '../../../tests/helpers/placeExtras';
import { libraryEntry } from '../../../tests/helpers/placesLibrary';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import PlaceHistorySection from './PlaceHistorySection';
import { usePlaceHistory } from './usePlaceHistory';
vi.mock('./usePlaceHistory', () => ({ usePlaceHistory: vi.fn() }));
const hook = vi.mocked(usePlaceHistory);
const t = (k: string) => k;
function show(state = historyState()) {
hook.mockReturnValue(state);
render(<PlaceHistorySection entry={libraryEntry()} language="en-GB" t={t} />);
return state;
}
beforeEach(() => {
hook.mockReset();
});
describe('PlaceHistorySection', () => {
it('FE-COMP-PLACEHISTSECTION-001: is not there before the first change', () => {
show();
expect(screen.queryByText('placeHistory.title')).toBeNull();
});
it('FE-COMP-PLACEHISTSECTION-002: a change shows the detail, from and to, the trip, who and when', () => {
show(historyState({ entries: [historyEntry()] }));
expect(screen.getByText('placeHistory.field.name')).toBeInTheDocument();
expect(screen.getByText('Colosseo')).toHaveClass('line-through');
expect(screen.getByText('Colosseum')).toBeInTheDocument();
expect(screen.getByText(/Rome 2026/)).toHaveTextContent(/anna/);
expect(screen.queryByRole('button')).toBeNull();
});
it('FE-COMP-PLACEHISTSECTION-003: a list change names the list, a picture change only its detail', () => {
show(
historyState({
entries: [
historyEntry({
field: 'image',
old_value: '/a.jpg',
new_value: '/b.jpg',
origin: { kind: 'list', collection_id: 9, collection_name: 'Favourites', collection_place_id: 900 },
}),
],
})
);
expect(screen.getByText(/Favourites/)).toBeInTheDocument();
expect(screen.queryByText('/b.jpg')).toBeNull();
});
it('FE-COMP-PLACEHISTSECTION-004: shows three at first, then all, then reads more', () => {
const state = show(historyState({ entries: historyEntries(5), hasMore: true }));
expect(screen.getAllByRole('listitem')).toHaveLength(3);
fireEvent.click(screen.getByRole('button', { name: 'placeHistory.showAll' }));
expect(screen.getAllByRole('listitem')).toHaveLength(5);
expect(state.more).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'placeHistory.more' }));
expect(state.more).toHaveBeenCalledTimes(1);
});
it('FE-COMP-PLACEHISTSECTION-005: once all are open and none are left, the button goes', () => {
show(historyState({ entries: historyEntries(4) }));
fireEvent.click(screen.getByRole('button', { name: 'placeHistory.showAll' }));
expect(screen.getAllByRole('listitem')).toHaveLength(4);
expect(screen.queryByRole('button')).toBeNull();
});
});
@@ -0,0 +1,34 @@
// FE-COMP-PLACELOCBADGE-001 to FE-COMP-PLACELOCBADGE-004: where a place is, under its name
// on the cover of a place sheet.
import { render, screen } from '../../../tests/helpers/render';
import PlaceLocationBadge, { coordsText } from './PlaceLocationBadge';
const t = (k: string) => k;
describe('PlaceLocationBadge', () => {
it('FE-COMP-PLACELOCBADGE-001: coordinates read with five decimals', () => {
expect(coordsText(41.890251, 12.4922309)).toBe('41.89025, 12.49223');
expect(coordsText(-3, 0)).toBe('-3.00000, 0.00000');
});
it('FE-COMP-PLACELOCBADGE-002: a placed place shows its address', () => {
render(<PlaceLocationBadge address=" Piazza del Colosseo " lat={41.89} lng={12.49} t={t} />);
const badge = screen.getByText('Piazza del Colosseo').parentElement;
expect(badge).toHaveClass('place-loc-badge');
expect(badge).not.toHaveClass('unplaced');
});
it('FE-COMP-PLACELOCBADGE-003: without an address the coordinates stand in', () => {
render(<PlaceLocationBadge address=" " lat={41.89} lng={12.49} t={t} />);
expect(screen.getByText('41.89000, 12.49000')).toBeInTheDocument();
});
it('FE-COMP-PLACELOCBADGE-004: a place without a position says so and wears the warning pin', () => {
const { rerender } = render(<PlaceLocationBadge address={null} lat={null} lng={12.49} t={t} />);
expect(screen.getByText('places.noCoordinates').parentElement).toHaveClass('place-loc-badge', 'unplaced');
expect(screen.getByLabelText('places.noCoordinates')).toBeInTheDocument();
// An address still shows, but the pin keeps warning.
rerender(<PlaceLocationBadge address="Somewhere" lat={undefined} lng={undefined} t={t} />);
expect(screen.getByText('Somewhere').parentElement).toHaveClass('unplaced');
});
});
@@ -0,0 +1,65 @@
// FE-COMP-PLACEMEDIASECTION-001 to FE-COMP-PLACEMEDIASECTION-004: the pictures and trip files
// of a place in the desktop sheet of All places (PLC-19, PLC-20), against a mocked hook.
import { mediaFile, mediaState, photos } from '../../../tests/helpers/placeExtras';
import { libraryEntry } from '../../../tests/helpers/placesLibrary';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import PlaceMediaSection from './PlaceMediaSection';
import { usePlaceMedia } from './usePlaceMedia';
vi.mock('./usePlaceMedia', () => ({ usePlaceMedia: vi.fn() }));
vi.mock('../Journey/PhotoLightbox', () => ({
default: (p: { photos: { id: string }[]; startIndex: number; label?: string; onClose: () => void }) => (
<div role="dialog" aria-label={p.label}>
<span>{`${p.photos.length} from ${p.startIndex}`}</span>
<button type="button" onClick={p.onClose}>
close lightbox
</button>
</div>
),
}));
const hook = vi.mocked(usePlaceMedia);
const t = (k: string) => k;
function show(state = mediaState()) {
hook.mockReturnValue(state);
render(<PlaceMediaSection entry={libraryEntry()} t={t} />);
return state;
}
beforeEach(() => {
hook.mockReset();
});
describe('PlaceMediaSection', () => {
it('FE-COMP-PLACEMEDIASECTION-001: is not there without pictures or files', () => {
show();
expect(screen.queryByText('places.media.photos')).toBeNull();
expect(screen.queryByText('places.media.files')).toBeNull();
});
it('FE-COMP-PLACEMEDIASECTION-002: a picture opens the lightbox at its place', () => {
const state = show(mediaState({ photos: photos(2) }));
expect(screen.queryByText('places.media.files')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Photo 1' }));
expect(state.setOpen).toHaveBeenCalledWith(1);
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-COMP-PLACEMEDIASECTION-003: shows eight and counts the rest on the last', () => {
show(mediaState({ photos: photos(11) }));
expect(screen.getAllByRole('button')).toHaveLength(8);
expect(screen.getByText('+3')).toBeInTheDocument();
});
it('FE-COMP-PLACEMEDIASECTION-004: the open picture shows in the lightbox, and files link to their trip', () => {
const state = show(mediaState({ photos: photos(3), files: [mediaFile()], open: 2 }));
expect(screen.getByRole('dialog', { name: 'Colosseum' })).toHaveTextContent('3 from 2');
fireEvent.click(screen.getByRole('button', { name: 'close lightbox' }));
expect(state.close).toHaveBeenCalledTimes(1);
const file = screen.getByRole('link', { name: /tickets\.pdf/ });
expect(file).toHaveAttribute('href', '/trips/5/files?file=31');
expect(file).toHaveAttribute('target', '_blank');
expect(file).toHaveTextContent('Rome 2026');
});
});
@@ -368,6 +368,9 @@ describe('PlacesLibraryView: the place sheet', () => {
await modal.onCopy(7, carry);
});
expect(copyToTrip).toHaveBeenCalledWith(7, [900], undefined, carry);
// The copy adds an origin, so the place is read again; a saved note does the same.
expect(captured(seen.lib).reload).toHaveBeenCalledTimes(1);
expect(captured(seen.detail).onNotesSaved).toBe(captured(seen.lib).reload);
act(() => modal.onClose());
expect(screen.queryByTestId('copy-modal')).not.toBeInTheDocument();
@@ -316,7 +316,7 @@ describe('SaveToCollectionModal', () => {
await screen.findByText('Favorites');
expect(screen.queryByRole('button', { name: 'Want to go' })).not.toBeInTheDocument();
expect(screen.getByTitle('Want to go')).toBeInTheDocument();
expect(screen.getByRole('img', { name: 'Want to go' })).toBeInTheDocument();
// Nothing to offer: the only list holding it is one the viewer cannot edit.
expect(screen.queryByRole('button', { name: /Visited everywhere|Mark visited/ })).not.toBeInTheDocument();
});
@@ -99,13 +99,10 @@ describe('StatusBadge', () => {
expect(onChange).toHaveBeenCalledWith('want');
});
it('FE-COMP-STATUSBADGE-010: interactive badge advertises the cycle hint in its title', () => {
it('FE-COMP-STATUSBADGE-010: interactive badge is named by its status, the cycle hint lives in the tooltip', () => {
render(<Badge status="idea" onChange={vi.fn()} />);
// English: 'collections.status.cycleHint' = 'tap to change'
expect(screen.getByRole('button', { name: 'Idea' })).toHaveAttribute(
'title',
'Idea — tap to change',
);
const badge = screen.getByRole('button', { name: 'Idea' });
expect(badge).not.toHaveAttribute('title');
});
// ── Read-only (onChange omitted) ─────────────────────────────────────────────
@@ -116,12 +113,11 @@ describe('StatusBadge', () => {
expect(screen.queryByRole('button')).not.toBeInTheDocument();
});
it('FE-COMP-STATUSBADGE-012: read-only badge uses the plain label as its title (no cycle hint)', () => {
it('FE-COMP-STATUSBADGE-012: read-only badge shows its word and needs no tooltip', () => {
render(<Badge status="visited" />);
const label = screen.getByText('Visited');
const pill = label.parentElement as HTMLElement;
expect(pill).toHaveAttribute('title', 'Visited');
expect(pill.getAttribute('title')).not.toMatch(/tap to change/i);
expect(pill).not.toHaveAttribute('title');
});
it('FE-COMP-STATUSBADGE-013: clicking a read-only badge does not throw', async () => {
@@ -0,0 +1,78 @@
// FE-COMP-TAGFILTER-001 to FE-COMP-TAGFILTER-005
import type { Tag } from '@trek/shared';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import TagFilterDropdown from './TagFilterDropdown';
const t = (k: string, p?: Record<string, unknown>) => (p ? `${k}:${JSON.stringify(p)}` : k);
const tag = (id: number, name: string, color = '#aa0000'): Tag => ({ id, user_id: 1, trip_id: null, name, color });
const TAGS = [tag(1, 'Beach'), tag(2, 'Coffee', '')];
function mount(picked: number[], onToggle = vi.fn()) {
render(<TagFilterDropdown tags={TAGS} picked={picked} onToggle={onToggle} t={t} />);
return onToggle;
}
describe('TagFilterDropdown', () => {
it('FE-COMP-TAGFILTER-001: is not drawn while the reader has no tags', () => {
const { container } = render(<TagFilterDropdown tags={[]} picked={[]} onToggle={vi.fn()} t={t} />);
expect(container).toBeEmptyDOMElement();
});
it('FE-COMP-TAGFILTER-002: the button names all tags, the one picked tag, or the count of picks', () => {
const { rerender } = render(<TagFilterDropdown tags={TAGS} picked={[]} onToggle={vi.fn()} t={t} />);
const all = screen.getByRole('button', { name: 'placeTags.title: placeTags.filterAll' });
expect(all).toHaveClass('is-default');
expect(all).toHaveAttribute('aria-expanded', 'false');
rerender(<TagFilterDropdown tags={TAGS} picked={[2]} onToggle={vi.fn()} t={t} />);
expect(screen.getByRole('button', { name: 'placeTags.title: Coffee' })).not.toHaveClass('is-default');
rerender(<TagFilterDropdown tags={TAGS} picked={[1, 2]} onToggle={vi.fn()} t={t} />);
expect(
screen.getByRole('button', { name: 'placeTags.title: placeTags.filterCount:{"count":2}' })
).toBeInTheDocument();
// A pick whose tag is gone names nothing rather than failing.
rerender(<TagFilterDropdown tags={TAGS} picked={[99]} onToggle={vi.fn()} t={t} />);
expect(screen.getByRole('button', { name: 'placeTags.title:' })).toBeInTheDocument();
});
it('FE-COMP-TAGFILTER-003: opens a list with the picks marked and toggles a tag on a click', () => {
const onToggle = mount([1]);
fireEvent.click(screen.getByRole('button', { name: 'placeTags.title: Beach' }));
expect(screen.getByRole('listbox')).toHaveAttribute('aria-multiselectable', 'true');
expect(screen.getByRole('option', { name: 'Beach' })).toHaveAttribute('aria-selected', 'true');
expect(screen.getByRole('option', { name: 'Coffee' })).toHaveAttribute('aria-selected', 'false');
fireEvent.click(screen.getByRole('option', { name: 'Coffee' }));
expect(onToggle).toHaveBeenCalledWith(2);
// Several picks at once: the list stays open after a pick.
expect(screen.getByRole('listbox')).toBeInTheDocument();
});
it('FE-COMP-TAGFILTER-004: Escape and a press outside close the list, a press inside keeps it', () => {
mount([]);
const button = screen.getByRole('button', { name: 'placeTags.title: placeTags.filterAll' });
fireEvent.click(button);
fireEvent.keyDown(document, { key: 'Enter' });
expect(screen.getByRole('listbox')).toBeInTheDocument();
fireEvent.keyDown(document, { key: 'Escape' });
expect(screen.queryByRole('listbox')).toBeNull();
fireEvent.click(button);
fireEvent.mouseDown(screen.getByRole('listbox'));
expect(screen.getByRole('listbox')).toBeInTheDocument();
fireEvent.mouseDown(document.body);
expect(screen.queryByRole('listbox')).toBeNull();
});
it('FE-COMP-TAGFILTER-005: the button closes the list it opened', () => {
mount([]);
const button = screen.getByRole('button', { name: 'placeTags.title: placeTags.filterAll' });
fireEvent.click(button);
expect(button).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(button);
expect(screen.queryByRole('listbox')).toBeNull();
});
});
@@ -0,0 +1,143 @@
// FE-COMP-TRIPLISTSPILL-001 to FE-COMP-TRIPLISTSPILL-008: the trip map's control for the
// lists a trip draws on, rendered against a stubbed useTripLists result.
import type { Collection, TripCollectionLink } from '@trek/shared';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { TripListsPill } from './TripListsPill';
import type { useTripLists } from './useTripLists';
const navigate = vi.hoisted(() => vi.fn());
vi.mock('react-router', async (importOriginal) => ({
...(await importOriginal<typeof import('react-router')>()),
useNavigate: () => navigate,
}));
type TripLists = ReturnType<typeof useTripLists>;
const t = (k: string, p?: Record<string, unknown>) => (p ? `${k}:${JSON.stringify(p)}` : k);
function link(collectionId: number, over: Partial<TripCollectionLink> = {}): TripCollectionLink {
return {
collection_id: collectionId,
name: `List ${collectionId}`,
color: null,
role: 'owner',
place_count: 3,
linked_by: 1,
created_at: null,
...over,
};
}
function lists(over: Partial<TripLists> = {}): TripLists {
return {
links: [],
canLink: true,
visible: [],
pois: [],
toggle: vi.fn(),
claim: vi.fn(),
pending: null,
cancelPending: vi.fn(),
addPending: vi.fn().mockResolvedValue(undefined),
busy: false,
linkable: [],
loadLinkable: vi.fn(),
link: vi.fn().mockResolvedValue(undefined),
unlink: vi.fn().mockResolvedValue(undefined),
lookOf: new Map(),
...over,
} as TripLists;
}
const openCard = () => fireEvent.click(screen.getByTestId('trip-lists-pill'));
beforeEach(() => navigate.mockReset());
describe('TripListsPill', () => {
it('FE-COMP-TRIPLISTSPILL-001: draws nothing without a linked list or the right to link one', () => {
const { container } = render(<TripListsPill lists={lists({ canLink: false })} t={t} />);
expect(container).toBeEmptyDOMElement();
});
it('FE-COMP-TRIPLISTSPILL-002: opens a card that says nothing is linked yet', () => {
render(<TripListsPill lists={lists()} t={t} />);
expect(screen.queryByRole('dialog')).toBeNull();
openCard();
expect(screen.getByRole('dialog', { name: 'tripLists.title' })).toBeInTheDocument();
expect(screen.getByText('tripLists.none')).toBeInTheDocument();
});
it('FE-COMP-TRIPLISTSPILL-003: each linked list is shown or hidden, opened in Places and unlinked', () => {
const value = lists({ links: [link(9, { name: 'Food' }), link(10, { name: 'Bars' })], visible: [9] });
render(<TripListsPill lists={value} t={t} />);
openCard();
expect(screen.getByText('Food')).toBeInTheDocument();
expect(screen.getAllByText('tripLists.places:{"count":3}')).toHaveLength(2);
const hide = screen.getByRole('button', { name: 'tripLists.hide' });
expect(hide).toHaveAttribute('aria-pressed', 'true');
const show = screen.getByRole('button', { name: 'tripLists.show' });
expect(show).toHaveAttribute('aria-pressed', 'false');
fireEvent.click(show);
expect(value.toggle).toHaveBeenCalledWith(10);
fireEvent.click(screen.getAllByRole('button', { name: 'tripLists.open' })[0]);
expect(navigate).toHaveBeenCalledWith(expect.stringMatching(/\/9$/));
fireEvent.click(screen.getAllByRole('button', { name: 'tripLists.unlink' })[1]);
expect(value.unlink).toHaveBeenCalledWith(10);
});
it('FE-COMP-TRIPLISTSPILL-004: a reader who may not link sees the lists without unlink or link', () => {
render(<TripListsPill lists={lists({ canLink: false, links: [link(9)] })} t={t} />);
openCard();
expect(screen.queryByRole('button', { name: 'tripLists.unlink' })).toBeNull();
expect(screen.queryByText('tripLists.link')).toBeNull();
});
it('FE-COMP-TRIPLISTSPILL-005: linking reads the reader lists, offers the unlinked ones and links the pick', () => {
const value = lists({
linkable: [{ id: 12, name: 'Museums', color: '#0a0', icon: 'star' } as Collection],
});
render(<TripListsPill lists={value} t={t} />);
openCard();
fireEvent.click(screen.getByRole('button', { name: /tripLists\.link/ }));
expect(value.loadLinkable).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole('button', { name: 'Museums' }));
expect(value.link).toHaveBeenCalledWith(12);
// The picker closes again, the way in comes back.
expect(screen.queryByRole('button', { name: 'Museums' })).toBeNull();
expect(screen.getByRole('button', { name: /tripLists\.link/ })).toBeInTheDocument();
});
it('FE-COMP-TRIPLISTSPILL-006: with everything linked the picker says so', () => {
render(<TripListsPill lists={lists({ links: [link(9)] })} t={t} />);
openCard();
fireEvent.click(screen.getByRole('button', { name: /tripLists\.link/ }));
expect(screen.getByText('tripLists.nothingToLink')).toBeInTheDocument();
});
it('FE-COMP-TRIPLISTSPILL-007: Escape and a press outside close the card', () => {
render(<TripListsPill lists={lists()} t={t} />);
openCard();
fireEvent.keyDown(document, { key: 'Enter' });
expect(screen.getByRole('dialog')).toBeInTheDocument();
fireEvent.keyDown(document, { key: 'Escape' });
expect(screen.queryByRole('dialog')).toBeNull();
openCard();
fireEvent.pointerDown(screen.getByRole('dialog'));
expect(screen.getByRole('dialog')).toBeInTheDocument();
fireEvent.pointerDown(document.body);
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-COMP-TRIPLISTSPILL-008: a pending saved place asks before it joins the trip', () => {
const value = lists({ pending: { id: 5, name: 'Bakery' } });
render(<TripListsPill lists={value} t={t} />);
expect(screen.getByText('tripLists.addMessage:{"name":"Bakery"}')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'tripLists.add' }));
expect(value.addPending).toHaveBeenCalledTimes(1);
expect(value.cancelPending).toHaveBeenCalled();
});
});
@@ -0,0 +1,127 @@
// FE-COMP-VISITS-001 to FE-COMP-VISITS-009: the visits of a place in All places and the planner, and the visited tick.
import type { PlaceVisit } from '@trek/shared';
import { libraryEntry } from '../../../tests/helpers/placesLibrary';
import { render, screen } from '../../../tests/helpers/render';
import { visitDate } from './libraryDates';
import TripPlaceVisits from './TripPlaceVisits';
import { usePlaceVisits } from './usePlaceVisits';
import VisitedMark from './VisitedMark';
import VisitsSection from './VisitsSection';
vi.mock('./usePlaceVisits', async (importOriginal) => ({
...(await importOriginal<typeof import('./usePlaceVisits')>()),
usePlaceVisits: vi.fn(),
}));
const hook = vi.mocked(usePlaceVisits);
const t = (k: string, p?: Record<string, unknown>) => (p ? `${k}:${JSON.stringify(p)}` : k);
function visit(over: Partial<PlaceVisit> = {}): PlaceVisit {
return {
visited_on: '2026-07-02',
visited_time: null,
trip: { id: 5, title: 'Rome 2026' },
place_id: 42,
day_id: 3,
day_number: 2,
name: 'Colosseum',
participants: [],
...over,
};
}
function visits(list: PlaceVisit[], lastVisit: string | null = '2026-07-02') {
hook.mockReturnValue({ visits: list, count: list.length, lastVisit, loading: false });
}
const PEOPLE = [
{ id: 1, username: 'anna', avatar_url: null },
{ id: 2, username: 'ben', avatar_url: '/uploads/ben.png' },
];
beforeEach(() => {
hook.mockReset();
});
describe('VisitsSection', () => {
it('FE-COMP-VISITS-001: without visits the section is not there', () => {
visits([]);
const { container } = render(<VisitsSection entry={libraryEntry()} language="en-GB" t={t} />);
expect(container).toBeEmptyDOMElement();
});
it('FE-COMP-VISITS-002: a count without a readable last date shows nothing either', () => {
hook.mockReturnValue({ visits: [visit()], count: 1, lastVisit: 'garbage', loading: false });
const { container } = render(<VisitsSection entry={libraryEntry()} language="en-GB" t={t} />);
expect(container).toBeEmptyDOMElement();
});
it('FE-COMP-VISITS-003: lists every visit with its day and trip under the summary', () => {
visits([
visit({ visited_time: '10:00' }),
visit({ visited_on: '2025-05-01', trip: { id: 6, title: 'Rome 2025' }, day_id: 9 }),
]);
render(<VisitsSection entry={libraryEntry()} language="en-GB" t={t} />);
expect(screen.getByText('visits.title')).toBeInTheDocument();
const last = visitDate('2026-07-02', null, 'en-GB');
expect(screen.getByText(`visits.summary:${JSON.stringify({ count: 2, date: last })}`)).toBeInTheDocument();
expect(screen.getByText(visitDate('2026-07-02', '10:00', 'en-GB') as string)).toBeInTheDocument();
expect(screen.getByText(visitDate('2025-05-01', null, 'en-GB') as string)).toBeInTheDocument();
expect(screen.getByText('Rome 2026')).toBeInTheDocument();
expect(screen.getByText('Rome 2025')).toBeInTheDocument();
expect(hook).toHaveBeenCalledWith({ entry: expect.objectContaining({ key: 'trip:42' }) });
});
it('FE-COMP-VISITS-004: shows who was there only when more than one person was', () => {
visits([visit({ participants: [PEOPLE[0]] }), visit({ day_id: 4, participants: PEOPLE })]);
const { container } = render(<VisitsSection entry={libraryEntry()} language="en-GB" t={t} />);
// One avatar letter for anna and one picture for ben, from the second visit only.
expect(screen.getAllByText('A')).toHaveLength(1);
expect(container.querySelectorAll('img[src="/uploads/ben.png"]')).toHaveLength(1);
});
});
describe('TripPlaceVisits', () => {
const trip = { id: 5, title: 'Rome 2026', start_date: '2026-07-01', end_date: '2026-07-05' };
const place = { id: 42, name: 'Colosseum' };
it('FE-COMP-VISITS-005: reads the visits through the trip place and sums them up', () => {
visits([visit(), visit({ day_id: 4 })]);
render(<TripPlaceVisits trip={trip} place={place} language="en-GB" t={t} />);
const last = visitDate('2026-07-02', null, 'en-GB');
expect(screen.getByText(`visits.summary:${JSON.stringify({ count: 2, date: last })}`)).toBeInTheDocument();
expect(hook).toHaveBeenCalledWith({
entry: expect.objectContaining({
key: 'trip:42',
origins: [expect.objectContaining({ kind: 'trip', trip_id: 5, place_id: 42 })],
}),
});
});
it('FE-COMP-VISITS-006: not shown before the first visit', () => {
visits([], null);
const { container } = render(<TripPlaceVisits trip={trip} place={place} language="en-GB" t={t} />);
expect(container).toBeEmptyDOMElement();
});
});
describe('VisitedMark', () => {
it('FE-COMP-VISITS-007: no tick for a place never visited', () => {
const { container } = render(<VisitedMark count={undefined} t={t} />);
expect(container).toBeEmptyDOMElement();
const zero = render(<VisitedMark count={0} t={t} />);
expect(zero.container).toBeEmptyDOMElement();
});
it('FE-COMP-VISITS-008: one visit is a plain tick named by the count', () => {
render(<VisitedMark count={1} t={t} />);
const mark = screen.getByRole('img', { name: 'visits.visitedTimes:{"count":1}' });
expect(mark).not.toHaveTextContent('1');
});
it('FE-COMP-VISITS-009: several visits show their number beside the tick', () => {
render(<VisitedMark count={3} t={t} />);
expect(screen.getByRole('img', { name: 'visits.visitedTimes:{"count":3}' })).toHaveTextContent('3');
});
});
@@ -1,7 +1,7 @@
// FE-COMP-LIBDATES-001 to FE-COMP-LIBDATES-003
// FE-COMP-LIBDATES-001 to FE-COMP-LIBDATES-004
import { describe, expect, it } from 'vitest';
import { dayDate, tripLine, tripRange } from './libraryDates';
import { dayDate, tripLine, tripRange, visitDate } 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', () => {
@@ -39,4 +39,11 @@ describe('libraryDates', () => {
'collections.library.day{"day":4}'
);
});
it('FE-COMP-LIBDATES-004: a visit names its weekday and year, with the time when there is one', () => {
expect(visitDate('2026-12-02', null, 'en-GB')).toMatch(/^Wed,? 2 Dec 2026$/);
expect(visitDate('2026-12-02', '14:30', 'en-GB')).toMatch(/^Wed,? 2 Dec 2026, 14:30$/);
expect(visitDate(null, '14:30', 'en-GB')).toBeNull();
expect(visitDate(undefined, null, 'en-GB')).toBeNull();
expect(visitDate('not a date', null, 'en-GB')).toBeNull();
});
});
@@ -1,4 +1,4 @@
// FE-COMP-LIBPAIRS-001 to FE-COMP-LIBPAIRS-009
// FE-COMP-LIBPAIRS-001 to FE-COMP-LIBPAIRS-012
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import {
@@ -11,7 +11,7 @@ import {
tripDetail,
tripOrigin,
} from '../../../tests/helpers/placesLibrary';
import { originPairs, saveDraftOf } from './libraryPairs';
import { libraryCarryOptions, originPairs, saveDraftOf } from './libraryPairs';
describe('originPairs', () => {
it('FE-COMP-LIBPAIRS-001: nothing open gives nothing', () => {
@@ -86,3 +86,39 @@ describe('originPairs', () => {
expect(saveDraftOf(origin, detail, undefined).category_id).toBeNull();
});
});
describe('libraryCarryOptions', () => {
it('FE-COMP-LIBPAIRS-010: nothing to carry without an open entry or a picked saved place', () => {
expect(libraryCarryOptions(null, 900)).toBeUndefined();
expect(libraryCarryOptions(bothOrigins(), null)).toBeUndefined();
});
it("FE-COMP-LIBPAIRS-011: offers the saved place's notes and labels and the reader's own tags", () => {
const entry = libraryEntry({
origins: [tripOrigin(), listOrigin()],
tags: [{ id: 3, name: 'Coffee', color: '#f97316' }],
});
const data = libraryDetail(entry, [
tripDetail(),
listDetail({ notes: ' Go early ', labels: [{ id: 7, name: 'Late', color: null }] }),
]);
expect(libraryCarryOptions(data, 900)).toEqual({
hasNotes: true,
tags: [{ id: 7, name: 'Late', color: null }],
personalTags: [{ id: 3, name: 'Coffee', color: '#f97316' }],
});
});
it('FE-COMP-LIBPAIRS-012: blank notes, an unknown saved place and an entry without tags offer nothing', () => {
const entry = libraryEntry({ origins: [listOrigin()] });
const data = libraryDetail(entry, [
listDetail({ notes: ' ', labels: [{ id: 7, name: 'Late', color: '#123456' }] }),
]);
expect(libraryCarryOptions(data, 900)).toEqual({
hasNotes: false,
tags: [{ id: 7, name: 'Late', color: '#123456' }],
personalTags: [],
});
expect(libraryCarryOptions(data, 12345)).toEqual({ hasNotes: false, tags: [], personalTags: [] });
});
});
@@ -0,0 +1,97 @@
// FE-COMP-PLACEEXTRAS-001 to FE-COMP-PLACEEXTRAS-009: the words of the history and
// activities sections of All places (PLC-14, PLC-18).
import { describe, expect, it } from 'vitest';
import { activityCandidate, historyEntry, listTour, placeActivity } from '../../../tests/helpers/placeExtras';
import type { TranslationFn } from '../../types';
import { activityLine, historyEditor, historyLine, historyMeta, historyWhen } from './placeExtrasText';
const t: TranslationFn = (k, p) => (p ? `${k}${JSON.stringify(p)}` : k);
describe('historyLine', () => {
it('FE-COMP-PLACEEXTRAS-001: a text detail shows its old and new value as they were', () => {
expect(historyLine(historyEntry({ field: 'address', old_value: 'Via A', new_value: 'Via B' }), t)).toEqual({
field: 'placeHistory.field.address',
from: 'Via A',
to: 'Via B',
});
expect(historyLine(historyEntry({ old_value: null, new_value: 'Colosseum' }), t)).toEqual({
field: 'placeHistory.field.name',
from: null,
to: 'Colosseum',
});
});
it('FE-COMP-PLACEEXTRAS-002: a picture or opening hours only say that they changed', () => {
for (const field of ['image', 'opening_hours'] as const) {
expect(historyLine(historyEntry({ field, old_value: '/a.jpg', new_value: '/b.jpg' }), t)).toEqual({
field: `placeHistory.field.${field}`,
from: null,
to: null,
});
}
});
it('FE-COMP-PLACEEXTRAS-003: a status reads as the status words, an empty side stays empty', () => {
expect(historyLine(historyEntry({ field: 'status', old_value: 'want', new_value: 'visited' }), t)).toEqual({
field: 'placeHistory.field.status',
from: 'collections.status.want',
to: 'collections.status.visited',
});
expect(historyLine(historyEntry({ field: 'status', old_value: null, new_value: 'idea' }), t).from).toBeNull();
});
});
describe('historyEditor', () => {
it('FE-COMP-PLACEEXTRAS-004: names the person, TREK itself, or a former member', () => {
expect(historyEditor(historyEntry(), t)).toBe('anna');
expect(historyEditor(historyEntry({ automatic: true }), t)).toBe('placeHistory.automatic');
expect(historyEditor(historyEntry({ editor: null }), t)).toBe('placeHistory.formerMember');
});
});
describe('historyWhen', () => {
it('FE-COMP-PLACEEXTRAS-005: a stored UTC time reads as a short date with the year', () => {
const when = historyWhen(historyEntry({ changed_at: '2026-12-02 14:30:00' }), 'en-GB');
expect(when).toMatch(/Dec/);
expect(when).toMatch(/2026/);
// An ISO stamp that already names its zone reads the same way.
expect(historyWhen(historyEntry({ changed_at: '2026-12-02T14:30:00Z' }), 'en-GB')).toBe(when);
});
it('FE-COMP-PLACEEXTRAS-006: no time or an unreadable one says nothing', () => {
expect(historyWhen(historyEntry({ changed_at: null }), 'en-GB')).toBe('');
expect(historyWhen(historyEntry({ changed_at: 'yesterday' }), 'en-GB')).toBe('');
});
});
describe('activityLine', () => {
it('FE-COMP-PLACEEXTRAS-007: a booking names its kind, its trip and its day', () => {
expect(activityLine(placeActivity({ date: '2026-12-02' }), 'en-GB', t)).toMatch(
/^placeActivities\.booking, Rome 2026, Wed,? 2 Dec$/
);
});
it('FE-COMP-PLACEEXTRAS-008: without a date the day number stands in, and a list tour names its list', () => {
expect(activityLine(activityCandidate({ day_number: 3 }), 'en-GB', t)).toBe(
'placeActivities.booking, Rome 2026, collections.library.day{"day":3}'
);
expect(activityLine(listTour(), 'en-GB', t)).toBe('placeActivities.tour, Favourites');
});
it('FE-COMP-PLACEEXTRAS-009: an unreadable date falls back to the day number', () => {
expect(activityLine(placeActivity({ date: 'soon', day_number: 1 }), 'en-GB', t)).toBe(
'placeActivities.booking, Rome 2026, collections.library.day{"day":1}'
);
});
});
describe('historyMeta', () => {
it('joins where, who and when, and leaves out an unknown time', () => {
const when = historyWhen(historyEntry({ changed_at: '2026-12-02 14:30:00' }), 'en-GB');
expect(historyMeta(historyEntry({ changed_at: '2026-12-02 14:30:00' }), t, 'en-GB')).toBe(
`Rome 2026, anna, ${when}`
);
expect(historyMeta(historyEntry({ changed_at: null }), t, 'en-GB')).toBe('Rome 2026, anna');
});
});
@@ -0,0 +1,203 @@
// FE-COMP-ENTRYTAGS-001 to FE-COMP-ENTRYTAGS-011: the reader's own tags on a place of
// All places (PLC-21), behind the desktop sheet, the phone sheet and the tag filter.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { PlacesLibraryEntry, Tag } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { libraryEntry } from '../../../tests/helpers/placesLibrary';
import { placeTagsRepo } from '../../repo/placeTagsRepo';
import { usePlaceTagsStore } from '../../store/placeTagsStore';
import type { TranslationFn } from '../../types';
import { matchTags, useEntryTags, usePersonalTags } from './useEntryTags';
const ws = vi.hoisted(() => ({ listeners: new Set<(event: Record<string, unknown>) => void>() }));
vi.mock('../../api/websocket', () => ({
addListener: (fn: (event: Record<string, unknown>) => void) => ws.listeners.add(fn),
removeListener: (fn: (event: Record<string, unknown>) => void) => ws.listeners.delete(fn),
}));
const toastError = vi.hoisted(() => vi.fn());
vi.mock('../shared/Toast', () => {
const toast = { error: toastError, success: vi.fn(), warning: vi.fn(), info: vi.fn() };
return { useToast: () => toast };
});
const t: TranslationFn = (key) => key;
const tag = (id: number, name: string): Tag => ({ id, user_id: 1, trip_id: null, name, color: '#aa0000' });
const BEACH = tag(1, 'Beach');
const COFFEE = tag(2, 'Coffee');
const WINE = tag(3, 'Wine');
function entryWith(tags: Tag[]): PlacesLibraryEntry {
return libraryEntry({ key: 'trip:42', tags: tags.map(({ id, name, color }) => ({ id, name, color })) });
}
function mount(entry: PlacesLibraryEntry | null, onChanged = vi.fn()) {
const hook = renderHook(() => useEntryTags({ entry, onChanged, t }));
return { ...hook, onChanged };
}
beforeEach(() => {
usePlaceTagsStore.setState({ tags: [BEACH, COFFEE, WINE], loaded: true });
toastError.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
ws.listeners.clear();
});
describe('matchTags', () => {
it('FE-COMP-ENTRYTAGS-001: matches the trimmed, case folded query, and all tags for an empty one', () => {
const all = [BEACH, COFFEE, WINE];
expect(matchTags(all, ' ')).toEqual(all);
expect(matchTags(all, ' ')).not.toBe(all);
expect(matchTags(all, ' fF ')).toEqual([COFFEE]);
expect(matchTags(all, 'zzz')).toEqual([]);
});
});
describe('usePersonalTags', () => {
it('FE-COMP-ENTRYTAGS-002: reads the tags once when they were not loaded yet', async () => {
usePlaceTagsStore.setState({ tags: [], loaded: false });
const list = vi.spyOn(placeTagsRepo, 'list').mockResolvedValue([WINE, BEACH]);
const { result } = renderHook(() => usePersonalTags());
await waitFor(() => expect(result.current).toEqual([BEACH, WINE]));
expect(list).toHaveBeenCalledTimes(1);
});
it('FE-COMP-ENTRYTAGS-003: loaded tags are not read again, and offline leaves the list empty', async () => {
const list = vi.spyOn(placeTagsRepo, 'list');
const { result } = renderHook(() => usePersonalTags());
expect(result.current).toEqual([BEACH, COFFEE, WINE]);
expect(list).not.toHaveBeenCalled();
usePlaceTagsStore.setState({ tags: [], loaded: false });
list.mockRejectedValue(new Error('offline'));
const offline = renderHook(() => usePersonalTags());
await waitFor(() => expect(list).toHaveBeenCalled());
expect(offline.result.current).toEqual([]);
});
it('FE-COMP-ENTRYTAGS-004: listens for tag changes from elsewhere while mounted', async () => {
const list = vi.spyOn(placeTagsRepo, 'list').mockResolvedValue([COFFEE]);
const { result, unmount } = renderHook(() => usePersonalTags());
expect(ws.listeners.size).toBe(1);
act(() => ws.listeners.forEach((fn) => fn({ type: 'tags:changed' })));
await waitFor(() => expect(result.current).toEqual([COFFEE]));
expect(list).toHaveBeenCalledTimes(1);
unmount();
expect(ws.listeners.size).toBe(0);
});
});
describe('useEntryTags', () => {
it('FE-COMP-ENTRYTAGS-005: offers what the place carries and the tags matching the search', () => {
const { result } = mount(entryWith([COFFEE]));
expect(result.current.all).toEqual([BEACH, COFFEE, WINE]);
expect(result.current.assignedIds).toEqual([2]);
expect(result.current.matches).toEqual([BEACH, COFFEE, WINE]);
expect(result.current.canCreate).toBe(false);
act(() => result.current.setQuery(' wi'));
expect(result.current.matches).toEqual([WINE]);
expect(result.current.canCreate).toBe(true);
act(() => result.current.setQuery(' wINe '));
expect(result.current.canCreate).toBe(false);
});
it('FE-COMP-ENTRYTAGS-006: an entry without tags, or none at all, carries nothing', () => {
expect(mount(libraryEntry()).result.current.assigned).toEqual([]);
expect(mount(null).result.current.assignedIds).toEqual([]);
});
it('FE-COMP-ENTRYTAGS-007: toggling puts a tag on or takes it off, then reports the change', async () => {
const setForEntry = vi.spyOn(placeTagsRepo, 'setForEntry').mockResolvedValue(null);
const { result, onChanged } = mount(entryWith([COFFEE]));
await act(() => result.current.toggle(3));
expect(setForEntry).toHaveBeenLastCalledWith('trip:42', [2, 3]);
await act(() => result.current.toggle(2));
expect(setForEntry).toHaveBeenLastCalledWith('trip:42', []);
expect(onChanged).toHaveBeenCalledTimes(2);
expect(result.current.busy).toBe(false);
});
it('FE-COMP-ENTRYTAGS-008: the typed name becomes a new tag on the place, and clears the search', async () => {
const created = tag(9, 'Rooftop');
const create = vi.spyOn(placeTagsRepo, 'create').mockResolvedValue(created);
const setForEntry = vi.spyOn(placeTagsRepo, 'setForEntry').mockResolvedValue(null);
const { result, onChanged } = mount(entryWith([COFFEE]));
act(() => result.current.setQuery(' Rooftop '));
await act(() => result.current.createAndAdd());
expect(create).toHaveBeenCalledWith('Rooftop', undefined);
expect(setForEntry).toHaveBeenCalledWith('trip:42', [2, 9]);
expect(result.current.query).toBe('');
expect(onChanged).toHaveBeenCalledTimes(1);
});
it('FE-COMP-ENTRYTAGS-009: a tag the place already carries is not put on twice, and an empty name or no entry makes none', async () => {
const create = vi.spyOn(placeTagsRepo, 'create').mockResolvedValue(COFFEE);
const setForEntry = vi.spyOn(placeTagsRepo, 'setForEntry').mockResolvedValue(null);
const { result } = mount(entryWith([COFFEE]));
act(() => result.current.setQuery('coffee bar'));
await act(() => result.current.createAndAdd());
expect(create).toHaveBeenCalledTimes(1);
expect(setForEntry).not.toHaveBeenCalled();
act(() => result.current.setQuery(' '));
await act(() => result.current.createAndAdd());
expect(create).toHaveBeenCalledTimes(1);
const none = mount(null);
act(() => none.result.current.setQuery('New'));
await act(() => none.result.current.createAndAdd());
await act(() => none.result.current.toggle(1));
expect(create).toHaveBeenCalledTimes(1);
expect(setForEntry).not.toHaveBeenCalled();
});
it('FE-COMP-ENTRYTAGS-010: renames with the trimmed name, skips a blank one, and deletes a tag everywhere', async () => {
const update = vi.spyOn(placeTagsRepo, 'update').mockResolvedValue(tag(3, 'Natural wine'));
const remove = vi.spyOn(placeTagsRepo, 'remove').mockResolvedValue(undefined);
const { result, onChanged } = mount(entryWith([]));
await act(() => result.current.rename(3, ' Natural wine '));
expect(update).toHaveBeenCalledWith(3, { name: 'Natural wine' });
await act(() => result.current.rename(3, ' '));
expect(update).toHaveBeenCalledTimes(1);
await act(() => result.current.destroy(1));
expect(remove).toHaveBeenCalledWith(1);
expect(usePlaceTagsStore.getState().tags.map((x) => x.name)).toEqual(['Coffee', 'Natural wine']);
expect(onChanged).toHaveBeenCalledTimes(2);
});
it('FE-COMP-ENTRYTAGS-011: a refused change toasts the reason, reports nothing, and one change runs at a time', async () => {
vi.spyOn(placeTagsRepo, 'setForEntry').mockRejectedValueOnce({ response: { data: { error: 'Nope' } } });
const { result, onChanged } = mount(entryWith([]));
await act(() => result.current.toggle(1));
expect(toastError).toHaveBeenCalledWith('Nope');
expect(onChanged).not.toHaveBeenCalled();
vi.spyOn(placeTagsRepo, 'remove').mockRejectedValueOnce(new Error('down'));
await act(() => result.current.destroy(1));
expect(toastError).toHaveBeenLastCalledWith('common.error');
let finish: () => void = () => undefined;
const setForEntry = vi.spyOn(placeTagsRepo, 'setForEntry').mockReturnValue(
new Promise((resolve) => {
finish = () => resolve(null);
})
);
setForEntry.mockClear();
act(() => {
void result.current.toggle(1);
});
expect(result.current.busy).toBe(true);
await act(() => result.current.toggle(2));
expect(setForEntry).toHaveBeenCalledTimes(1);
await act(async () => finish());
await waitFor(() => expect(result.current.busy).toBe(false));
expect(onChanged).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,171 @@
// FE-COMP-ORIGINNOTES-001 to FE-COMP-ORIGINNOTES-011: each trip's and list's own notes on a place of All places.
import { act, renderHook } from '@testing-library/react';
import type { PlacesLibraryDetailResponse } from '@trek/shared';
import { beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
import {
libraryDetail,
libraryEntry,
listDetail,
listOrigin,
tripDetail,
tripOrigin,
} from '../../../tests/helpers/placesLibrary';
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
import { notesOf, useOriginNotes } from './useOriginNotes';
const toastError = vi.hoisted(() => vi.fn());
vi.mock('../shared/Toast', () => {
const toast = { error: toastError, success: vi.fn(), warning: vi.fn(), info: vi.fn() };
return { useToast: () => toast };
});
const t = (key: string) => key;
/** A trip place with a note, a trip place without one and a saved place without one, all writable. */
function threeOrigins(over: { tripNotes?: string | null; canEditSecond?: boolean } = {}): PlacesLibraryDetailResponse {
const entry = libraryEntry({
origins: [
tripOrigin(),
tripOrigin({ trip_id: 6, trip_title: 'Lazio', place_id: 43, can_edit: over.canEditSecond ?? true }),
listOrigin(),
],
});
return libraryDetail(entry, [
tripDetail({ notes: over.tripNotes === undefined ? 'Buy tickets online' : over.tripNotes }),
tripDetail({ place_id: 43 }),
listDetail(),
]);
}
let saveNotes: MockInstance<typeof placesLibraryRepo.saveNotes>;
beforeEach(() => {
toastError.mockReset();
vi.restoreAllMocks();
saveNotes = vi.spyOn(placesLibraryRepo, 'saveNotes').mockResolvedValue(undefined);
});
function setup(data: PlacesLibraryDetailResponse | null = threeOrigins()) {
const onSaved = vi.fn();
const hook = renderHook(() => useOriginNotes({ data, onSaved, t }));
return { ...hook, onSaved };
}
describe('notesOf', () => {
it('FE-COMP-ORIGINNOTES-001: nothing open gives no notes', () => {
expect(notesOf(null)).toEqual([]);
});
it('FE-COMP-ORIGINNOTES-002: the trips come first, then the lists, each named by where it lives', () => {
const notes = notesOf(threeOrigins());
expect(notes.map((n) => [n.key, n.kind, n.source, n.text, n.canEdit])).toEqual([
['trip:42', 'trip', 'Rome 2026', 'Buy tickets online', true],
['trip:43', 'trip', 'Lazio', '', true],
['list:900', 'list', 'Favourites', '', true],
]);
});
it('FE-COMP-ORIGINNOTES-003: an empty note stays out where the reader could not write one, a written one stays', () => {
const entry = libraryEntry({ origins: [tripOrigin({ can_edit: false }), listOrigin({ can_edit: false })] });
const data = libraryDetail(entry, [tripDetail({ notes: ' ' }), listDetail({ notes: 'Ask for Marco' })]);
expect(notesOf(data).map((n) => [n.key, n.canEdit])).toEqual([['list:900', false]]);
});
it('FE-COMP-ORIGINNOTES-004: each note saves where it lives', async () => {
const [trip, , list] = notesOf(threeOrigins());
await trip.save('New');
expect(saveNotes).toHaveBeenLastCalledWith({ kind: 'trip', trip_id: 5, place_id: 42 }, 'New');
await list.save(null);
expect(saveNotes).toHaveBeenLastCalledWith({ kind: 'list', collection_place_id: 900 }, null);
});
});
describe('useOriginNotes', () => {
it('FE-COMP-ORIGINNOTES-005: shows the written notes and offers the empty writable ones as targets', () => {
const { result } = setup();
expect(result.current.notes.map((n) => n.key)).toEqual(['trip:42']);
expect(result.current.targets.map((n) => n.key)).toEqual(['trip:43', 'list:900']);
expect(result.current.editing).toBeNull();
expect(result.current.choosing).toBe(false);
});
it('FE-COMP-ORIGINNOTES-006: "+ Note" with several targets asks where, and toggles the choice', () => {
const { result } = setup();
act(() => result.current.add());
expect(result.current.choosing).toBe(true);
act(() => result.current.add());
expect(result.current.choosing).toBe(false);
});
it('FE-COMP-ORIGINNOTES-007: "+ Note" with one target opens it straight away', () => {
const { result } = setup(threeOrigins({ canEditSecond: false }));
// The second trip is read only, and the list is the one place left.
expect(result.current.targets.map((n) => n.key)).toEqual(['list:900']);
act(() => result.current.add());
expect(result.current.editing).toBe('list:900');
expect(result.current.choosing).toBe(false);
// The note being written shows and is no target any more.
expect(result.current.notes.map((n) => n.key)).toEqual(['trip:42', 'list:900']);
expect(result.current.targets).toEqual([]);
});
it('FE-COMP-ORIGINNOTES-008: editing starts from the stored text, cancel leaves it', () => {
const { result } = setup();
act(() => result.current.add());
act(() => result.current.edit(result.current.notes[0]));
expect(result.current.choosing).toBe(false);
expect(result.current.editing).toBe('trip:42');
expect(result.current.draft).toBe('Buy tickets online');
act(() => result.current.setDraft('Changed'));
act(() => result.current.cancel());
expect(result.current.editing).toBeNull();
expect(saveNotes).not.toHaveBeenCalled();
});
it('FE-COMP-ORIGINNOTES-009: saving stores the draft, closes the editor and reads the place again', async () => {
const { result, onSaved } = setup();
act(() => result.current.edit(result.current.targets[1]));
act(() => result.current.setDraft('Bring water'));
await act(async () => {
await result.current.save();
});
expect(saveNotes).toHaveBeenCalledWith({ kind: 'list', collection_place_id: 900 }, 'Bring water');
expect(result.current.editing).toBeNull();
expect(result.current.busy).toBe(false);
expect(onSaved).toHaveBeenCalledTimes(1);
});
it('FE-COMP-ORIGINNOTES-010: a blank draft clears the note, and nothing saves without an open editor', async () => {
const { result, onSaved } = setup();
await act(async () => {
await result.current.save();
});
expect(saveNotes).not.toHaveBeenCalled();
act(() => result.current.edit(result.current.notes[0]));
act(() => result.current.setDraft(' '));
await act(async () => {
await result.current.save();
});
expect(saveNotes).toHaveBeenCalledWith({ kind: 'trip', trip_id: 5, place_id: 42 }, null);
expect(onSaved).toHaveBeenCalledTimes(1);
});
it('FE-COMP-ORIGINNOTES-011: a refused save toasts the reason and keeps the editor open', async () => {
saveNotes.mockRejectedValueOnce({ response: { data: { error: 'No access' } } });
saveNotes.mockRejectedValueOnce(new Error('offline'));
const { result, onSaved } = setup();
act(() => result.current.edit(result.current.notes[0]));
await act(async () => {
await result.current.save();
});
expect(toastError).toHaveBeenLastCalledWith('No access');
expect(result.current.editing).toBe('trip:42');
expect(result.current.busy).toBe(false);
await act(async () => {
await result.current.save();
});
expect(toastError).toHaveBeenLastCalledWith('common.error');
expect(onSaved).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,228 @@
// FE-COMP-PLACEACTIVITIES-001 to FE-COMP-PLACEACTIVITIES-013: the tours and bookings of a
// place of All places (PLC-18), behind the desktop section and the phone section.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { PlaceLibraryActivitiesResponse, PlacesLibraryEntry } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { activityCandidate, listSource, listTour, placeActivity, tripSource } from '../../../tests/helpers/placeExtras';
import { libraryEntry, listOrigin } from '../../../tests/helpers/placesLibrary';
import { placeActivitiesRepo } from '../../repo/placeActivitiesRepo';
import type { TranslationFn } from '../../types';
import { activityHref, usePlaceActivities } from './usePlaceActivities';
const toastError = vi.hoisted(() => vi.fn());
vi.mock('../shared/Toast', () => {
const toast = { error: toastError, success: vi.fn(), warning: vi.fn(), info: vi.fn() };
return { useToast: () => toast };
});
vi.mock('../../repo/placeActivitiesRepo', () => ({
placeActivitiesRepo: {
libraryEntry: vi.fn(),
tripCandidates: vi.fn(),
savedCandidates: vi.fn(),
linkTrip: vi.fn(),
linkSaved: vi.fn(),
unlink: vi.fn(),
},
}));
const repo = vi.mocked(placeActivitiesRepo);
const t: TranslationFn = (k) => k;
const EMPTY = { activities: [], can_link: true };
function mount(entry: PlacesLibraryEntry | null = libraryEntry()) {
return renderHook(({ e }: { e: PlacesLibraryEntry | null }) => usePlaceActivities({ entry: e, t }), {
initialProps: { e: entry },
});
}
async function mountLoaded(res: PlaceLibraryActivitiesResponse, entry = libraryEntry()) {
repo.libraryEntry.mockResolvedValue(res);
const view = mount(entry);
await waitFor(() => expect(repo.libraryEntry).toHaveBeenCalled());
await waitFor(() => expect(view.result.current.activities).toEqual(res.activities));
return view;
}
beforeEach(() => {
vi.clearAllMocks();
});
describe('activityHref', () => {
it('FE-COMP-PLACEACTIVITIES-001: a booking and a tour open in their trip, a kept tour in its list', () => {
expect(activityHref(placeActivity())).toBe('/trips/5?booking=7');
expect(activityHref({ target: { kind: 'tour', trip_id: 5, tour_id: 8 } })).toBe('/trips/5?tour=8');
expect(activityHref(listTour())).toMatch(/\/9$/);
});
});
describe('usePlaceActivities', () => {
it('FE-COMP-PLACEACTIVITIES-002: reads the entry through its first origin and says whether it may link', async () => {
const view = await mountLoaded({ activities: [placeActivity()], sources: [tripSource()] });
expect(repo.libraryEntry).toHaveBeenCalledWith('trip', 42, expect.any(AbortSignal));
await waitFor(() => expect(view.result.current.canLink).toBe(true));
expect(view.result.current.picking).toBeNull();
expect(view.result.current.busy).toBe(false);
});
it('FE-COMP-PLACEACTIVITIES-003: a list origin reads through its saved place; no origin reads nothing', async () => {
await mountLoaded({ activities: [], sources: [] }, libraryEntry({ origins: [listOrigin()] }));
expect(repo.libraryEntry).toHaveBeenCalledWith('list', 900, expect.any(AbortSignal));
repo.libraryEntry.mockClear();
const empty = mount(libraryEntry({ origins: [] }));
expect(repo.libraryEntry).not.toHaveBeenCalled();
expect(empty.result.current.activities).toEqual([]);
expect(empty.result.current.canLink).toBe(false);
mount(null);
expect(repo.libraryEntry).not.toHaveBeenCalled();
});
it('FE-COMP-PLACEACTIVITIES-004: a failed read shows nothing and offers no link', async () => {
repo.libraryEntry.mockRejectedValue(new Error('offline'));
const view = mount();
await waitFor(() => expect(repo.libraryEntry).toHaveBeenCalled());
expect(view.result.current.activities).toEqual([]);
expect(view.result.current.canLink).toBe(false);
});
it('FE-COMP-PLACEACTIVITIES-005: an origin without the right to link does not count', async () => {
const view = await mountLoaded({ activities: [placeActivity()], sources: [tripSource({ can_link: false })] });
expect(view.result.current.canLink).toBe(false);
});
it('FE-COMP-PLACEACTIVITIES-006: another entry hides the old answer until its own arrives', async () => {
const view = await mountLoaded({ activities: [placeActivity()], sources: [] });
repo.libraryEntry.mockReturnValue(new Promise(() => undefined));
view.rerender({ e: libraryEntry({ origins: [listOrigin()] }) });
expect(view.result.current.activities).toEqual([]);
});
it('FE-COMP-PLACEACTIVITIES-007: the picker reads the candidates of every origin that takes links', async () => {
const view = await mountLoaded({
activities: [],
sources: [
tripSource(),
listSource(),
tripSource({ source: { kind: 'trip', trip_id: 6, place_id: 43 }, can_link: false }),
],
});
const booking = activityCandidate();
const tour = activityCandidate({ key: 'collection_tour:3' });
repo.tripCandidates.mockResolvedValue({ candidates: [booking] });
repo.savedCandidates.mockResolvedValue({ candidates: [tour] });
await act(async () => {
await view.result.current.openPicker();
});
expect(repo.tripCandidates).toHaveBeenCalledTimes(1);
expect(repo.tripCandidates).toHaveBeenCalledWith(5, 42);
expect(repo.savedCandidates).toHaveBeenCalledWith(900);
expect(view.result.current.picking).toEqual([
{ source: tripSource(), candidates: [booking] },
{ source: listSource(), candidates: [tour] },
]);
// Opening reads the entry again.
await waitFor(() => expect(repo.libraryEntry).toHaveBeenCalledTimes(2));
act(() => view.result.current.closePicker());
expect(view.result.current.picking).toBeNull();
});
it('FE-COMP-PLACEACTIVITIES-008: a failed picker read toasts the server message and opens nothing', async () => {
const view = await mountLoaded({ activities: [], sources: [tripSource()] });
repo.tripCandidates.mockRejectedValue({ response: { data: { error: 'No access' } } });
await act(async () => {
await view.result.current.openPicker();
});
expect(toastError).toHaveBeenCalledWith('No access');
expect(view.result.current.picking).toBeNull();
expect(view.result.current.busy).toBe(false);
});
it('FE-COMP-PLACEACTIVITIES-009: linking a booking or a tour to a trip place sends its own id and closes the picker', async () => {
const view = await mountLoaded({ activities: [], sources: [tripSource()] });
repo.tripCandidates.mockResolvedValue({ candidates: [activityCandidate()] });
repo.linkTrip.mockResolvedValue(EMPTY);
await act(async () => {
await view.result.current.openPicker();
});
await act(async () => {
await view.result.current.link(tripSource(), activityCandidate());
});
expect(repo.linkTrip).toHaveBeenLastCalledWith(5, 42, { reservation_id: 7 });
expect(view.result.current.picking).toBeNull();
await act(async () => {
await view.result.current.link(
tripSource(),
activityCandidate({ type: 'tour', target: { kind: 'tour', trip_id: 5, tour_id: 8 } })
);
});
expect(repo.linkTrip).toHaveBeenLastCalledWith(5, 42, { tour_id: 8 });
});
it('FE-COMP-PLACEACTIVITIES-010: a kept tour links to the saved place, never to a trip place', async () => {
const view = await mountLoaded({ activities: [], sources: [tripSource(), listSource()] });
repo.linkSaved.mockResolvedValue(EMPTY);
const keptTour = activityCandidate({
target: { kind: 'collection_tour', collection_id: 9, collection_tour_id: 3 },
});
await act(async () => {
await view.result.current.link(listSource(), keptTour);
});
expect(repo.linkSaved).toHaveBeenCalledWith(900, 3);
await act(async () => {
await view.result.current.link(tripSource(), keptTour);
});
// A booking never reaches a saved place either.
await act(async () => {
await view.result.current.link(listSource(), activityCandidate());
});
expect(repo.linkTrip).not.toHaveBeenCalled();
expect(repo.linkSaved).toHaveBeenCalledTimes(1);
});
it('FE-COMP-PLACEACTIVITIES-011: unlinking takes the link off and reads the entry again', async () => {
const act1 = placeActivity();
const view = await mountLoaded({ activities: [act1], sources: [tripSource()] });
repo.unlink.mockResolvedValue(EMPTY);
await act(async () => {
await view.result.current.unlink(act1);
});
expect(repo.unlink).toHaveBeenCalledWith(act1);
await waitFor(() => expect(repo.libraryEntry).toHaveBeenCalledTimes(2));
});
it('FE-COMP-PLACEACTIVITIES-012: a refused write without a message toasts the general error', async () => {
const view = await mountLoaded({ activities: [placeActivity()], sources: [] });
repo.unlink.mockRejectedValue(new Error('boom'));
await act(async () => {
await view.result.current.unlink(placeActivity());
});
expect(toastError).toHaveBeenCalledWith('common.error');
expect(repo.libraryEntry).toHaveBeenCalledTimes(1);
});
it('FE-COMP-PLACEACTIVITIES-013: a second write while one runs is ignored', async () => {
const view = await mountLoaded({ activities: [placeActivity()], sources: [] });
let finish: (v: typeof EMPTY) => void = () => undefined;
repo.unlink.mockReturnValue(
new Promise((res) => {
finish = res;
})
);
let first: Promise<void> | undefined;
act(() => {
first = view.result.current.unlink(placeActivity());
});
expect(view.result.current.busy).toBe(true);
await act(async () => {
await view.result.current.unlink(placeActivity());
});
expect(repo.unlink).toHaveBeenCalledTimes(1);
await act(async () => {
finish(EMPTY);
await first;
});
expect(view.result.current.busy).toBe(false);
});
});
@@ -0,0 +1,98 @@
// FE-COMP-PLACEHISTORY-001 to FE-COMP-PLACEHISTORY-007: the change history of a place of
// All places (PLC-14), behind the desktop section and the phone section.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { PlaceHistoryPageResponse, PlacesLibraryEntry } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { historyEntries } from '../../../tests/helpers/placeExtras';
import { libraryEntry, listOrigin } from '../../../tests/helpers/placesLibrary';
import { placeHistoryRepo } from '../../repo/placeHistoryRepo';
import { usePlaceHistory } from './usePlaceHistory';
vi.mock('../../repo/placeHistoryRepo', () => ({ placeHistoryRepo: { history: vi.fn() } }));
const history = vi.mocked(placeHistoryRepo.history);
function mount(entry: PlacesLibraryEntry | null = libraryEntry()) {
return renderHook(({ e }: { e: PlacesLibraryEntry | null }) => usePlaceHistory(e), { initialProps: { e: entry } });
}
function page(from: number, count: number, next: string | null): PlaceHistoryPageResponse {
return { entries: historyEntries(count, from), next_cursor: next };
}
beforeEach(() => {
history.mockReset();
});
describe('usePlaceHistory', () => {
it('FE-COMP-PLACEHISTORY-001: reads the first page through the first origin', async () => {
history.mockResolvedValue(page(1, 2, null));
const { result } = mount();
await waitFor(() => expect(result.current.entries).toHaveLength(2));
expect(history).toHaveBeenCalledWith('trip', 42, { limit: 20 }, expect.any(AbortSignal));
expect(result.current.hasMore).toBe(false);
});
it('FE-COMP-PLACEHISTORY-002: a list origin reads through its saved place; no origin reads nothing', async () => {
history.mockResolvedValue(page(1, 1, null));
mount(libraryEntry({ origins: [listOrigin()] }));
await waitFor(() => expect(history).toHaveBeenCalledWith('list', 900, { limit: 20 }, expect.any(AbortSignal)));
history.mockClear();
const { result } = mount(null);
expect(history).not.toHaveBeenCalled();
expect(result.current.entries).toEqual([]);
expect(result.current.hasMore).toBe(false);
});
it('FE-COMP-PLACEHISTORY-003: a failed read shows no history', async () => {
history.mockRejectedValue(new Error('offline'));
const { result } = mount();
await waitFor(() => expect(history).toHaveBeenCalled());
expect(result.current.entries).toEqual([]);
expect(result.current.hasMore).toBe(false);
});
it('FE-COMP-PLACEHISTORY-004: more appends the next page with the cursor', async () => {
history.mockResolvedValueOnce(page(1, 2, '10')).mockResolvedValueOnce(page(3, 1, null));
const { result } = mount();
await waitFor(() => expect(result.current.hasMore).toBe(true));
await act(async () => {
await result.current.more();
});
expect(history).toHaveBeenLastCalledWith('trip', 42, { limit: 20, cursor: '10' });
expect(result.current.entries.map((e) => e.id)).toEqual([1, 2, 3]);
expect(result.current.hasMore).toBe(false);
expect(result.current.loadingMore).toBe(false);
});
it('FE-COMP-PLACEHISTORY-005: more does nothing on the last page', async () => {
history.mockResolvedValue(page(1, 1, null));
const { result } = mount();
await waitFor(() => expect(result.current.entries).toHaveLength(1));
await act(async () => {
await result.current.more();
});
expect(history).toHaveBeenCalledTimes(1);
});
it('FE-COMP-PLACEHISTORY-006: a failed "more" keeps the list and lets another tap try again', async () => {
history.mockResolvedValueOnce(page(1, 2, '10')).mockRejectedValueOnce(new Error('offline'));
const { result } = mount();
await waitFor(() => expect(result.current.hasMore).toBe(true));
await act(async () => {
await result.current.more();
});
expect(result.current.entries).toHaveLength(2);
expect(result.current.hasMore).toBe(true);
expect(result.current.loadingMore).toBe(false);
});
it('FE-COMP-PLACEHISTORY-007: another entry hides the old history until its own arrives', async () => {
history.mockResolvedValueOnce(page(1, 2, null)).mockReturnValueOnce(new Promise(() => undefined));
const view = mount();
await waitFor(() => expect(view.result.current.entries).toHaveLength(2));
view.rerender({ e: libraryEntry({ origins: [listOrigin()] }) });
expect(view.result.current.entries).toEqual([]);
});
});
@@ -0,0 +1,96 @@
// FE-COMP-PLACEMEDIA-001 to FE-COMP-PLACEMEDIA-006: the pictures and files of a place of
// All places (PLC-19, PLC-20), behind the desktop section and the phone section.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { PlacesLibraryEntry } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { journeyPhoto, mediaFile, mediaImage } from '../../../tests/helpers/placeExtras';
import { libraryEntry, listOrigin } from '../../../tests/helpers/placesLibrary';
import { placeVisitsRepo } from '../../repo/placeVisitsRepo';
import { photosOf, usePlaceMedia } from './usePlaceMedia';
vi.mock('../../repo/placeVisitsRepo', () => ({ placeVisitsRepo: { media: vi.fn() } }));
const media = vi.mocked(placeVisitsRepo.media);
function mount(entry: PlacesLibraryEntry | null = libraryEntry()) {
return renderHook(({ e }: { e: PlacesLibraryEntry | null }) => usePlaceMedia(e), { initialProps: { e: entry } });
}
beforeEach(() => {
media.mockReset();
});
describe('photosOf', () => {
it('FE-COMP-PLACEMEDIA-001: the place pictures come first, each address once, captioned by trip or list', () => {
const photos = photosOf({
images: [mediaImage('/a.jpg'), mediaImage('/a.jpg', 'list'), mediaImage('/b.jpg', 'list')],
journey_photos: [],
files: [],
});
expect(photos).toEqual([
{ id: 'img:/a.jpg', src: '/a.jpg', thumbSrc: '/a.jpg', caption: 'Rome 2026' },
{ id: 'img:/b.jpg', src: '/b.jpg', thumbSrc: '/b.jpg', caption: 'Favourites' },
]);
});
it('FE-COMP-PLACEMEDIA-002: journey photos follow with their own sizes, caption or journey title', () => {
const photos = photosOf({
images: [mediaImage('/a.jpg')],
journey_photos: [journeyPhoto(), journeyPhoto({ journey_photo_id: 71, photo_id: 701, caption: ' Sunset ' })],
files: [],
});
expect(photos.slice(1)).toEqual([
{
id: 'jp:70',
src: '/api/photos/700/original',
thumbSrc: '/api/photos/700/thumbnail',
caption: 'Italy journey',
provider: 'local',
mediaType: 'image',
},
expect.objectContaining({ id: 'jp:71', caption: 'Sunset' }),
]);
});
it('FE-COMP-PLACEMEDIA-003: nothing read yet is no pictures', () => {
expect(photosOf(null)).toEqual([]);
});
});
describe('usePlaceMedia', () => {
it('FE-COMP-PLACEMEDIA-004: reads through the first origin and opens and closes a picture', async () => {
media.mockResolvedValue({ images: [mediaImage('/a.jpg')], journey_photos: [], files: [mediaFile()] });
const { result } = mount();
await waitFor(() => expect(result.current.photos).toHaveLength(1));
expect(media).toHaveBeenCalledWith('trip', 42, expect.any(AbortSignal));
expect(result.current.files).toEqual([mediaFile()]);
expect(result.current.open).toBeNull();
act(() => result.current.setOpen(0));
expect(result.current.open).toBe(0);
act(() => result.current.close());
expect(result.current.open).toBeNull();
});
it('FE-COMP-PLACEMEDIA-005: a list origin reads through its saved place; no origin reads nothing', async () => {
media.mockResolvedValue({ images: [], journey_photos: [], files: [] });
mount(libraryEntry({ origins: [listOrigin()] }));
await waitFor(() => expect(media).toHaveBeenCalledWith('list', 900, expect.any(AbortSignal)));
media.mockClear();
const { result } = mount(null);
expect(media).not.toHaveBeenCalled();
expect(result.current.photos).toEqual([]);
expect(result.current.files).toEqual([]);
});
it('FE-COMP-PLACEMEDIA-006: a failed read shows none, and another entry hides the old pictures', async () => {
media.mockResolvedValueOnce({ images: [mediaImage('/a.jpg')], journey_photos: [], files: [] });
const view = mount();
await waitFor(() => expect(view.result.current.photos).toHaveLength(1));
media.mockRejectedValueOnce(new Error('offline'));
view.rerender({ e: libraryEntry({ origins: [listOrigin()] }) });
expect(view.result.current.photos).toEqual([]);
await waitFor(() => expect(media).toHaveBeenCalledTimes(2));
expect(view.result.current.files).toEqual([]);
});
});
@@ -0,0 +1,115 @@
// FE-COMP-PLACEVISITS-001 to FE-COMP-PLACEVISITS-007: a place's visits, read through its first origin.
import { renderHook, waitFor } from '@testing-library/react';
import type { PlaceVisitsForPlaceResponse } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
import { libraryEntry, listOrigin, tripOrigin } from '../../../tests/helpers/placesLibrary';
import { placeVisitsRepo } from '../../repo/placeVisitsRepo';
import { tripPlaceEntry, usePlaceVisits } from './usePlaceVisits';
const VISITS: PlaceVisitsForPlaceResponse = {
visits: [
{
visited_on: '2026-07-02',
visited_time: '10:00',
trip: { id: 5, title: 'Rome 2026' },
place_id: 42,
day_id: 3,
day_number: 2,
name: 'Colosseum',
participants: [],
},
],
visit_count: 1,
last_visit: '2026-07-02',
};
let forPlace: MockInstance<typeof placeVisitsRepo.forPlace>;
beforeEach(() => {
forPlace = vi.spyOn(placeVisitsRepo, 'forPlace').mockResolvedValue(VISITS);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('tripPlaceEntry', () => {
it('FE-COMP-PLACEVISITS-001: a trip place becomes a one-origin entry keyed by the trip place', () => {
const entry = tripPlaceEntry(
{ id: 5, title: 'Rome 2026', start_date: '2026-07-01', end_date: '2026-07-05' },
{ id: 42, name: 'Colosseum', address: 'Piazza', lat: 41.9, lng: 12.5 }
);
expect(entry).toMatchObject({ key: 'trip:42', name: 'Colosseum', address: 'Piazza', lat: 41.9, lng: 12.5 });
expect(entry.origins).toEqual([
{
kind: 'trip',
trip_id: 5,
trip_title: 'Rome 2026',
trip_start: '2026-07-01',
trip_end: '2026-07-05',
place_id: 42,
can_edit: true,
read_only: false,
},
]);
});
it('FE-COMP-PLACEVISITS-002: missing place facts and trip dates turn into nulls', () => {
const entry = tripPlaceEntry({ id: 5, title: 'Rome' }, { id: 42, name: 'Colosseum' });
expect(entry).toMatchObject({ address: null, lat: null, lng: null, category: null, image_url: null });
expect(entry.origins[0]).toMatchObject({ trip_start: null, trip_end: null });
});
});
describe('usePlaceVisits', () => {
it('FE-COMP-PLACEVISITS-003: without an entry nothing is read and nothing loads', () => {
const { result } = renderHook(() => usePlaceVisits({ entry: null }));
expect(result.current).toEqual({ visits: [], count: 0, lastVisit: null, loading: false });
expect(forPlace).not.toHaveBeenCalled();
});
it('FE-COMP-PLACEVISITS-004: reads a trip origin by its trip place and hands back the visits', async () => {
const { result } = renderHook(() => usePlaceVisits({ entry: libraryEntry() }));
expect(result.current.loading).toBe(true);
await waitFor(() => expect(result.current.loading).toBe(false));
expect(forPlace).toHaveBeenCalledWith('trip', 42, expect.any(AbortSignal));
expect(result.current.visits).toEqual(VISITS.visits);
expect(result.current.count).toBe(1);
expect(result.current.lastVisit).toBe('2026-07-02');
});
it('FE-COMP-PLACEVISITS-005: reads a list origin by its saved place', async () => {
const entry = libraryEntry({ key: 'list:900', origins: [listOrigin()] });
const { result } = renderHook(() => usePlaceVisits({ entry }));
await waitFor(() => expect(result.current.loading).toBe(false));
expect(forPlace).toHaveBeenCalledWith('list', 900, expect.any(AbortSignal));
});
it('FE-COMP-PLACEVISITS-006: a failed read shows no visits rather than loading forever', async () => {
forPlace.mockRejectedValue(new Error('offline'));
const { result } = renderHook(() => usePlaceVisits({ entry: libraryEntry() }));
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current).toEqual({ visits: [], count: 0, lastVisit: null, loading: false });
});
it('FE-COMP-PLACEVISITS-007: another entry does not show the last one visits and aborts the old read', async () => {
const { result, rerender } = renderHook(({ entry }) => usePlaceVisits({ entry }), {
initialProps: { entry: libraryEntry() },
});
await waitFor(() => expect(result.current.count).toBe(1));
const firstSignal = forPlace.mock.calls[0][2] as AbortSignal;
let resolveSecond: (r: PlaceVisitsForPlaceResponse) => void = () => undefined;
forPlace.mockReturnValueOnce(
new Promise((resolve) => {
resolveSecond = resolve;
})
);
rerender({ entry: libraryEntry({ key: 'trip:7', origins: [tripOrigin({ place_id: 7 })] }) });
expect(firstSignal.aborted).toBe(true);
expect(result.current).toEqual({ visits: [], count: 0, lastVisit: null, loading: true });
resolveSecond({ visits: [], visit_count: 3, last_visit: '2025-01-01' });
await waitFor(() => expect(result.current.count).toBe(3));
expect(forPlace).toHaveBeenLastCalledWith('trip', 7, expect.any(AbortSignal));
});
});
@@ -15,6 +15,7 @@ import {
} from '../../../tests/helpers/placesLibrary';
import { OnlineOnlyError } from '../../repo/onlineOnly';
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';
import type { TranslationFn } from '../../types';
import { entryHasPosition, firstOrigin, parseEntryKey, usePlacesLibrary } from './usePlacesLibrary';
@@ -61,6 +62,7 @@ beforeEach(() => {
detail.mockReset();
coverPhoto.mockReset();
coverPhoto.mockResolvedValue(null);
useSaveToCollectionStore.setState({ version: 0 });
});
describe('parseEntryKey and entryHasPosition', () => {
@@ -439,3 +441,41 @@ describe('usePlacesLibrary: the cover', () => {
expect(firstOrigin([trip], 'own:9')).toBeNull();
});
});
describe('usePlacesLibrary: personal tags and outside saves', () => {
it('FE-COMP-PLACESLIBHOOK-027: picked tags go to the server, a second pick of one drops it, and reset clears them', async () => {
const { result } = await mountLoaded(libraryPage([]));
expect(result.current.tagIds).toEqual([]);
act(() => {
result.current.toggleTag(4);
result.current.toggleTag(7);
});
expect(result.current.tagIds).toEqual([4, 7]);
expect(result.current.filtered).toBe(true);
await waitFor(() =>
expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, tag_ids: [4, 7] }, expect.any(AbortSignal))
);
act(() => result.current.toggleTag(4));
expect(result.current.tagIds).toEqual([7]);
await waitFor(() =>
expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, tag_ids: [7] }, expect.any(AbortSignal))
);
act(() => result.current.resetFilters());
expect(result.current.tagIds).toEqual([]);
expect(result.current.filtered).toBe(false);
await waitFor(() => expect(list).toHaveBeenLastCalledWith(FIRST_PAGE, expect.any(AbortSignal)));
});
it('FE-COMP-PLACESLIBHOOK-028: a place saved to a list anywhere reads the overview again', async () => {
const { result } = await mountLoaded(libraryPage([]));
expect(list).toHaveBeenCalledTimes(1);
list.mockResolvedValueOnce(libraryPage([libraryEntry()]));
act(() => useSaveToCollectionStore.getState().bumpVersion());
await waitFor(() => expect(result.current.entries).toHaveLength(1));
expect(list).toHaveBeenCalledTimes(2);
});
});
@@ -1,4 +1,4 @@
// FE-COMP-TRIPCOPYHOOK-001 to FE-COMP-TRIPCOPYHOOK-011: the "Copy to trip" picker logic
// FE-COMP-TRIPCOPYHOOK-001 to FE-COMP-TRIPCOPYHOOK-013: the "Copy to trip" picker logic
// behind both the desktop dialog and the phone sheet.
import { act, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi, type Mock, type MockInstance } from 'vitest';
@@ -184,4 +184,40 @@ describe('useTripCopyPicker', () => {
expect(result.current.includeNotes).toBe(false);
expect(result.current.offersCarry).toBe(false);
});
it('FE-COMP-TRIPCOPYHOOK-012: own tags stay private unless picked, and only the offered ones go along', async () => {
const carryOptions = {
hasNotes: false,
tags: [],
personalTags: [
{ id: 3, name: 'Coffee' },
{ id: 4, name: 'Wine' },
],
};
const { result, props } = setup({ carryOptions });
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.offersCarry).toBe(true);
await act(() => result.current.handleCopy(1));
expect(props.onCopy).toHaveBeenLastCalledWith(1, {});
act(() => {
result.current.togglePersonalTag(4);
result.current.togglePersonalTag(99);
result.current.togglePersonalTag(3);
result.current.togglePersonalTag(3);
});
expect(result.current.personalTagIds).toEqual([4, 99]);
await act(() => result.current.handleCopy(2));
expect(props.onCopy).toHaveBeenLastCalledWith(2, { personal_tag_ids: [4] });
});
it('FE-COMP-TRIPCOPYHOOK-013: a reopened picker drops the picked own tags', async () => {
const carryOptions = { hasNotes: false, tags: [], personalTags: [{ id: 3, name: 'Coffee' }] };
const { result, rerender, props } = setup({ carryOptions });
act(() => result.current.togglePersonalTag(3));
expect(result.current.personalTagIds).toEqual([3]);
rerender({ ...props, open: false });
rerender({ ...props, open: true, carryOptions: { hasNotes: false, tags: [], personalTags: [] } });
expect(result.current.personalTagIds).toEqual([]);
expect(result.current.offersCarry).toBe(false);
});
});
@@ -0,0 +1,322 @@
// FE-COMP-TRIPLISTS-001 to FE-COMP-TRIPLISTS-014: the lists a trip draws on (PLC-15) and
// their saved places as pins on the trip map (PLC-16), behind the desktop stage and the phone map.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { Collection, TripCollectionLayerPlace, TripCollectionLink } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { resetAllStores } from '../../../tests/helpers/store';
import { addListener, removeListener } from '../../api/websocket';
import { useCollectionStore } from '../../store/collectionStore';
import { useTripCollectionsStore } from '../../store/tripCollectionsStore';
import { useTripStore } from '../../store/tripStore';
import { SAVED_PLACE_POI_CATEGORY, type Poi } from '../Map/poiCategories';
import { savedPlaceIdOf, savedPlacePoi, useTripLists } from './useTripLists';
const t = (k: string, p?: Record<string, unknown>) => (p ? `${k}:${JSON.stringify(p)}` : k);
const TRIP = 4;
const KEY = `anon:${TRIP}`;
function link(collectionId: number, over: Partial<TripCollectionLink> = {}): TripCollectionLink {
return {
collection_id: collectionId,
name: `List ${collectionId}`,
color: null,
role: 'owner',
place_count: 2,
linked_by: 1,
created_at: null,
...over,
};
}
function layerPlace(id: number, collectionId: number, over: Partial<TripCollectionLayerPlace> = {}) {
return {
id,
collection_id: collectionId,
name: `Place ${id}`,
lat: 1,
lng: 2,
category: null,
status: 'want',
in_trip: false,
trip_place_id: null,
...over,
} satisfies TripCollectionLayerPlace;
}
function list(id: number, over: Partial<Collection> = {}): Collection {
return { id, name: `List ${id}`, color: null, icon: null, ...over } as Collection;
}
let addToast: Mock<NonNullable<Window['__addToast']>>;
let load: Mock;
let loadLayer: Mock;
let linkFn: Mock;
let unlinkFn: Mock;
let loadAll: Mock;
let copyToTrip: Mock;
let refreshPlaces: Mock;
function seedEntry(entry: {
links: TripCollectionLink[];
canLink?: boolean;
layer?: TripCollectionLayerPlace[] | null;
}) {
useTripCollectionsStore.setState({
trips: { [KEY]: { links: entry.links, canLink: entry.canLink ?? true, layer: entry.layer ?? null } },
});
}
function setup(canEdit = true) {
return renderHook(({ edit }: { edit: boolean }) => useTripLists({ tripId: TRIP, canEdit: edit, t }), {
initialProps: { edit: canEdit },
});
}
beforeEach(() => {
resetAllStores();
addToast = vi.fn<NonNullable<Window['__addToast']>>();
window.__addToast = addToast;
load = vi.fn().mockResolvedValue(undefined);
loadLayer = vi.fn().mockResolvedValue([]);
linkFn = vi.fn().mockResolvedValue(undefined);
unlinkFn = vi.fn().mockResolvedValue(undefined);
loadAll = vi.fn().mockResolvedValue(undefined);
copyToTrip = vi.fn().mockResolvedValue({ copied: 1, skipped: [] });
refreshPlaces = vi.fn().mockResolvedValue(undefined);
useTripCollectionsStore.setState({ trips: {}, load, loadLayer, link: linkFn, unlink: unlinkFn });
useCollectionStore.setState({ collections: [], loadAll, copyToTrip } as never);
useTripStore.setState({ refreshPlaces } as never);
});
afterEach(() => {
delete window.__addToast;
});
describe('savedPlacePoi / savedPlaceIdOf', () => {
it('FE-COMP-TRIPLISTS-001: a saved place becomes a saved-place pin in its list look, and maps back to its id', () => {
const poi = savedPlacePoi(layerPlace(7, 9, { name: 'Café', lat: 3, lng: 4 }), { color: '#f00', icon: 'coffee' });
expect(poi).toMatchObject({
osm_id: 'saved:7',
name: 'Café',
lat: 3,
lng: 4,
category: SAVED_PLACE_POI_CATEGORY,
poi_type: SAVED_PLACE_POI_CATEGORY,
source: 'list',
color: '#f00',
icon: 'coffee',
});
expect(savedPlaceIdOf(poi)).toBe(7);
});
it('FE-COMP-TRIPLISTS-002: an empty look leaves colour and icon out; other or broken ids are not ours', () => {
const poi = savedPlacePoi(layerPlace(7, 9), { color: null, icon: '' });
expect(poi).not.toHaveProperty('color');
expect(poi).not.toHaveProperty('icon');
expect(savedPlaceIdOf({ osm_id: 'node/123' })).toBeNull();
expect(savedPlaceIdOf({ osm_id: 'saved:abc' })).toBeNull();
expect(savedPlaceIdOf({ osm_id: 'saved:0' })).toBeNull();
expect(savedPlaceIdOf({ osm_id: 'saved:-3' })).toBeNull();
});
});
describe('useTripLists', () => {
it('FE-COMP-TRIPLISTS-003: reads the links on mount, listens for pushes and stops on unmount', async () => {
const { result, unmount } = setup();
await waitFor(() => expect(load).toHaveBeenCalledWith(TRIP));
expect(addListener).toHaveBeenCalled();
expect(result.current.links).toEqual([]);
expect(result.current.canLink).toBe(false);
expect(result.current.visible).toEqual([]);
expect(result.current.pois).toEqual([]);
unmount();
expect(removeListener).toHaveBeenCalled();
});
it('FE-COMP-TRIPLISTS-004: a failed read of the links stays quiet', async () => {
load.mockRejectedValue(new Error('offline'));
setup();
await waitFor(() => expect(load).toHaveBeenCalled());
await Promise.resolve();
expect(addToast).not.toHaveBeenCalled();
});
it('FE-COMP-TRIPLISTS-005: the layer starts off; showing a list reads it, remembers the choice and pins its places', async () => {
seedEntry({ links: [link(9), link(10)] });
useCollectionStore.setState({ collections: [list(9, { color: '#0a0', icon: 'star' })] });
const { result } = setup();
expect(loadLayer).not.toHaveBeenCalled();
act(() => result.current.toggle(9));
expect(result.current.visible).toEqual([9]);
expect(JSON.parse(localStorage.getItem(`trek:tripListsShown:${TRIP}`) ?? 'null')).toEqual([9]);
await waitFor(() => expect(loadLayer).toHaveBeenCalledWith(TRIP));
act(() => {
useTripCollectionsStore.setState({
trips: {
[KEY]: {
links: [link(9), link(10, { color: '#00f' })],
canLink: true,
layer: [layerPlace(1, 9), layerPlace(2, 9, { in_trip: true }), layerPlace(3, 10)],
},
},
});
});
// Only the shown list, and only what the trip does not have yet.
expect(result.current.pois.map((p) => p.osm_id)).toEqual(['saved:1']);
expect(result.current.pois[0]).toMatchObject({ color: '#0a0', icon: 'star' });
act(() => result.current.toggle(10));
// List 10 is not among the reader's lists, so its link's colour stands in.
expect(result.current.pois.map((p) => p.osm_id)).toEqual(['saved:1', 'saved:3']);
expect(result.current.pois[1]).toMatchObject({ color: '#00f' });
expect(result.current.pois[1]).not.toHaveProperty('icon');
act(() => result.current.toggle(9));
expect(result.current.visible).toEqual([10]);
expect(JSON.parse(localStorage.getItem(`trek:tripListsShown:${TRIP}`) ?? 'null')).toEqual([10]);
});
it('FE-COMP-TRIPLISTS-006: the remembered choice comes back, without what is no longer linked or not a number', () => {
localStorage.setItem(`trek:tripListsShown:${TRIP}`, JSON.stringify([9, 11, 'x', 1.5]));
seedEntry({ links: [link(9)], layer: [layerPlace(1, 9)] });
const { result } = setup();
expect(result.current.visible).toEqual([9]);
expect(result.current.pois.map((p) => p.osm_id)).toEqual(['saved:1']);
// The layer was there already, so it is not read again.
expect(loadLayer).not.toHaveBeenCalled();
});
it('FE-COMP-TRIPLISTS-007: broken or non-list storage shows nothing', () => {
seedEntry({ links: [link(9)] });
localStorage.setItem(`trek:tripListsShown:${TRIP}`, '{not json');
expect(setup().result.current.visible).toEqual([]);
localStorage.setItem(`trek:tripListsShown:${TRIP}`, JSON.stringify({ 9: true }));
expect(setup().result.current.visible).toEqual([]);
});
it('FE-COMP-TRIPLISTS-008: a failed layer read toasts the error', async () => {
loadLayer.mockRejectedValue({ response: { data: { error: 'No layer' } } });
localStorage.setItem(`trek:tripListsShown:${TRIP}`, JSON.stringify([9]));
seedEntry({ links: [link(9)] });
setup();
await waitFor(() => expect(addToast).toHaveBeenCalledWith('No layer', 'error', undefined));
});
it('FE-COMP-TRIPLISTS-009: a tap on a saved pin asks to add it when the reader may edit; other pins pass on', () => {
const { result, rerender } = setup(true);
const saved = { osm_id: 'saved:5', name: 'Bakery' } as Poi;
let claimed = false;
act(() => {
claimed = result.current.claim(saved);
});
expect(claimed).toBe(true);
expect(result.current.pending).toEqual({ id: 5, name: 'Bakery' });
act(() => result.current.cancelPending());
expect(result.current.pending).toBeNull();
expect(result.current.claim({ osm_id: 'node/1', name: 'Café' } as Poi)).toBe(false);
rerender({ edit: false });
act(() => {
claimed = result.current.claim(saved);
});
// Still ours, so the map does nothing else with it, but a reader cannot add it.
expect(claimed).toBe(true);
expect(result.current.pending).toBeNull();
});
it('FE-COMP-TRIPLISTS-010: adding the pending place copies it, toasts, and reads the trip and layer again', async () => {
const { result } = setup();
act(() => {
result.current.claim({ osm_id: 'saved:5', name: 'Bakery' } as Poi);
});
await act(async () => {
await result.current.addPending();
});
expect(copyToTrip).toHaveBeenCalledWith(TRIP, [5]);
expect(addToast).toHaveBeenCalledWith('tripLists.added:{"name":"Bakery"}', 'success', undefined);
expect(refreshPlaces).toHaveBeenCalledWith(TRIP);
expect(loadLayer).toHaveBeenCalledWith(TRIP);
expect(result.current.pending).toBeNull();
expect(result.current.busy).toBe(false);
});
it('FE-COMP-TRIPLISTS-011: a place the trip has already gets an info note; a failed copy toasts and keeps it pending', async () => {
copyToTrip.mockResolvedValueOnce({ copied: 0, skipped: [{ id: 5, name: 'Bakery' }] });
const { result } = setup();
act(() => {
result.current.claim({ osm_id: 'saved:5', name: 'Bakery' } as Poi);
});
await act(async () => {
await result.current.addPending();
});
expect(addToast).toHaveBeenCalledWith('tripLists.alreadyInTrip:{"name":"Bakery"}', 'info', undefined);
copyToTrip.mockRejectedValueOnce({ response: { data: { error: 'Nope' } } });
act(() => {
result.current.claim({ osm_id: 'saved:6', name: 'Bar' } as Poi);
});
await act(async () => {
await result.current.addPending();
});
expect(addToast).toHaveBeenLastCalledWith('Nope', 'error', undefined);
expect(result.current.pending).toEqual({ id: 6, name: 'Bar' });
expect(result.current.busy).toBe(false);
});
it('FE-COMP-TRIPLISTS-012: adding with nothing pending copies nothing', async () => {
const { result } = setup();
await act(async () => {
await result.current.addPending();
});
expect(copyToTrip).not.toHaveBeenCalled();
});
it('FE-COMP-TRIPLISTS-013: linking shows the new list on the map; unlinking goes through the store; failures toast', async () => {
seedEntry({ links: [link(9)] });
useCollectionStore.setState({ collections: [list(9), list(12)] });
const { result } = setup();
expect(result.current.linkable.map((c) => c.id)).toEqual([12]);
linkFn.mockImplementation(async () => {
seedEntry({ links: [link(9), link(12)] });
});
await act(async () => {
await result.current.link(12);
});
expect(linkFn).toHaveBeenCalledWith(TRIP, 12);
expect(result.current.visible).toEqual([12]);
expect(JSON.parse(localStorage.getItem(`trek:tripListsShown:${TRIP}`) ?? 'null')).toEqual([12]);
expect(result.current.linkable).toEqual([]);
await act(async () => {
await result.current.unlink(9);
});
expect(unlinkFn).toHaveBeenCalledWith(TRIP, 9);
unlinkFn.mockRejectedValueOnce(new Error('boom'));
await act(async () => {
await result.current.unlink(12);
});
// No server message, so the generic one.
expect(addToast).toHaveBeenLastCalledWith('common.error', 'error', undefined);
});
it('FE-COMP-TRIPLISTS-014: the reader lists are read once for the picker, a failure toasts', async () => {
const { result } = setup();
act(() => result.current.loadLinkable());
expect(loadAll).toHaveBeenCalledTimes(1);
loadAll.mockRejectedValueOnce({ response: { data: { error: 'Down' } } });
act(() => result.current.loadLinkable());
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Down', 'error', undefined));
act(() => useCollectionStore.setState({ collections: [list(9)] }));
act(() => result.current.loadLinkable());
expect(loadAll).toHaveBeenCalledTimes(2);
});
});
@@ -1,7 +1,7 @@
// FE-COMP-POIAPPEAR-001 to FE-COMP-POIAPPEAR-005
// FE-COMP-POIAPPEAR-001 to FE-COMP-POIAPPEAR-007
import { describe, it, expect } from 'vitest'
import { Coffee, Fuel, MapPin, Signpost } from 'lucide-react'
import { poiAppearance, POI_CATEGORIES, ROADTRIP_POI_CATEGORIES } from './poiCategories'
import { Bookmark, Coffee, Fuel, Heart, MapPin, Signpost } from 'lucide-react'
import { poiAppearance, POI_CATEGORIES, ROADTRIP_POI_CATEGORIES, SAVED_PLACE_POI_CATEGORY } from './poiCategories'
import { POI_DEFAULT_COLOR } from './pluginPoiIcons'
const PLUGIN_KEY = 'plugin:trail-finder/trailheads'
@@ -31,4 +31,15 @@ describe('poiAppearance', () => {
expect(poiAppearance({ category, color: '#2f855a', icon: 'Signpost' })).toEqual({ color: POI_DEFAULT_COLOR, Icon: null })
}
})
it('FE-COMP-POIAPPEAR-006: a saved place of a linked list wears the list symbol in the list colour', () => {
expect(SAVED_PLACE_POI_CATEGORY).toBe('saved-place')
expect(poiAppearance({ category: SAVED_PLACE_POI_CATEGORY, color: '#E11D48', icon: 'Heart' })).toEqual({ color: '#E11D48', Icon: Heart })
})
it('FE-COMP-POIAPPEAR-007: a saved place without a valid #rrggbb colour or known symbol falls back to the accent and a bookmark', () => {
for (const color of [undefined, '', 'red', '#fff', '#12345g', 'var(--x)']) {
expect(poiAppearance({ category: SAVED_PLACE_POI_CATEGORY, color }).color).toBe('var(--accent)')
}
expect(poiAppearance({ category: SAVED_PLACE_POI_CATEGORY, icon: 'NoSuchIcon' }).Icon).toBe(Bookmark)
})
})
@@ -72,7 +72,7 @@ describe('B4A Places pool', () => {
excludePlaceIds: new Set([1]),
})} />)
expect(sidebar.filtered.map(place => place.id)).toEqual([2, 3, 4])
expect(sidebar.filterCounts).toEqual({ all: 3, unplanned: 1, planned: 1, tracks: 1 })
expect(sidebar.filterCounts).toEqual({ all: 3, unplanned: 1, planned: 1, visited: 0, tracks: 1 })
expect(sidebar.hasTracks).toBe(false)
act(() => sidebar.setPlacesSort('name'))
expect(sidebar.filtered.map(place => place.id)).toEqual([3, 4, 2])
@@ -101,7 +101,7 @@ describe('B4A Places pool', () => {
const { rerender } = render(<Host {...props} />)
act(() => { sidebar.setCategoryFilters(new Set(['7'])); sidebar.setSearch('matching') })
expect(sidebar.filtered.map(place => place.id)).toEqual([2])
expect(sidebar.filterCounts).toEqual({ all: 1, unplanned: 1, planned: 0, tracks: 0 })
expect(sidebar.filterCounts).toEqual({ all: 1, unplanned: 1, planned: 0, visited: 0, tracks: 0 })
rerender(<Host {...props} excludePlaceIds={new Set([1, 2])} />)
expect(sidebar.filtered).toEqual([])
expect(sidebar.filterCounts.all).toBe(0)
@@ -66,6 +66,15 @@ describe('places pool helpers', () => {
]);
expect(placesFilterTabs(t, true).map((tab) => tab.id)).toEqual(['all', 'unplanned', 'planned', 'tracks']);
expect(placesFilterTabs(t, true)[3].label).toBe('places.filterTracks');
// Visited (PLC-23) sits before tracks, once the reader has been somewhere on the trip.
expect(placesFilterTabs(t, true, true).map((tab) => tab.id)).toEqual([
'all',
'unplanned',
'planned',
'visited',
'tracks',
]);
expect(placesFilterTabs(t, false, true)[3].label).toBe('places.filterVisited');
});
it('FE-PLANNER-POOL-003: the category filter toggles ids in the trip store, a new set each time', () => {
@@ -1,4 +1,4 @@
// FE-PLANNER-PSHOOK-001 to FE-PLANNER-PSHOOK-060
// FE-PLANNER-PSHOOK-001 to FE-PLANNER-PSHOOK-061
import { http, HttpResponse } from 'msw';
import userEvent from '@testing-library/user-event';
import { render, screen, fireEvent, act, waitFor } from '../../../tests/helpers/render';
@@ -10,6 +10,7 @@ import { useTripStore } from '../../store/tripStore';
import { usePermissionsStore } from '../../store/permissionsStore';
import { useAddonStore } from '../../store/addonStore';
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';
import { usePlaceVisitsStore } from '../../store/placeVisitsStore';
import { ContextMenu } from '../shared/ContextMenu';
import type { Place } from '../../types';
import { usePlacesSidebar, type PlacesSidebarProps, type SidebarState } from './usePlacesSidebar';
@@ -201,7 +202,7 @@ describe('usePlacesSidebar filtering', () => {
expect(S.hasTracks).toBe(false);
expect(names()).toEqual(expect.arrayContaining(['Legacy track', 'Ordinary place']));
expect(names()).not.toContain('Tour place');
expect(S.filterCounts).toEqual({ all: 2, unplanned: 2, planned: 0, tracks: 1 });
expect(S.filterCounts).toEqual({ all: 2, unplanned: 2, planned: 0, visited: 0, tracks: 1 });
expect(S.localities).toEqual([{ country: 'Austria', count: 2, regions: [] }]);
act(() => { S.setRatingFilter(4); });
@@ -219,7 +220,7 @@ describe('usePlacesSidebar filtering', () => {
})} />);
expect(S.hasTracks).toBe(true);
expect(S.filterCounts).toEqual({ all: 2, unplanned: 2, planned: 0, tracks: 2 });
expect(S.filterCounts).toEqual({ all: 2, unplanned: 2, planned: 0, visited: 0, tracks: 2 });
act(() => { S.setFilter('tracks'); });
expect(names()).toEqual(expect.arrayContaining(['Legacy track', 'Dormant Tour']));
});
@@ -776,14 +777,14 @@ describe('usePlacesSidebar filter panel', () => {
const other = buildPlace({ id: 3, name: 'Beta', category_id: null });
const assignments = { '9': [buildAssignment({ place: planned, day_id: 9 })] };
render(<Host {...makeProps({ places: [planned, loose, other], assignments })} />);
expect(S.filterCounts).toEqual({ all: 3, unplanned: 2, planned: 1, tracks: 1 });
expect(S.filterCounts).toEqual({ all: 3, unplanned: 2, planned: 1, visited: 0, tracks: 1 });
act(() => { S.setSearch('alpha'); });
act(() => { S.setRatingFilter(5); });
expect(S.filterCounts).toEqual({ all: 2, unplanned: 1, planned: 1, tracks: 1 });
expect(S.filterCounts).toEqual({ all: 2, unplanned: 1, planned: 1, visited: 0, tracks: 1 });
act(() => { S.setCategoryFilters(new Set(['uncategorized'])); });
expect(S.filterCounts).toEqual({ all: 0, unplanned: 0, planned: 0, tracks: 0 });
expect(S.filterCounts).toEqual({ all: 0, unplanned: 0, planned: 0, visited: 0, tracks: 0 });
});
it('FE-PLANNER-PSHOOK-054: while a day is open "planned" counts that day only', () => {
@@ -806,6 +807,23 @@ describe('usePlacesSidebar filter panel', () => {
expect(S.selectedIds.size).toBe(0);
});
it('FE-PLANNER-PSHOOK-061: the places the reader visited are counted, offered and filtered (PLC-23)', async () => {
const userId = useAuthStore.getState().user?.id;
const entry = { placeIds: [2], places: [] };
const loadTripVisited = vi.fn(async () => {
usePlaceVisitsStore.setState({ visited: { [`${userId}:1`]: entry } });
return entry;
});
usePlaceVisitsStore.setState({ visited: {}, loadTripVisited });
render(<Host {...makeProps({ places: [buildPlace({ id: 1, name: 'Alpha' }), buildPlace({ id: 2, name: 'Beta' })] })} />);
expect(S.hasVisited).toBe(false);
await waitFor(() => expect(S.filterCounts.visited).toBe(1));
expect(loadTripVisited).toHaveBeenCalledWith(1);
expect(S.hasVisited).toBe(true);
act(() => { S.pickFilter('visited'); });
expect(names()).toEqual(['Beta']);
});
});
describe('usePlacesSidebar row menu entries', () => {