// FE-COMP-PLACESLIBHOOK-001 to FE-COMP-PLACESLIBHOOK-026: the "All places" logic behind // the desktop view and the phone screen (PLC-07, PLC-08). import { act, renderHook, waitFor } from '@testing-library/react'; import type { PlacesLibraryDetailResponse, PlacesLibraryPageResponse } from '@trek/shared'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { libraryDetail, libraryEntry, libraryInfo, libraryPage, listDetail, listOrigin, tripDetail, } from '../../../tests/helpers/placesLibrary'; import { OnlineOnlyError } from '../../repo/onlineOnly'; import { placesLibraryRepo } from '../../repo/placesLibraryRepo'; import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'; import type { TranslationFn } from '../../types'; import { entryHasPosition, firstOrigin, parseEntryKey, usePlacesLibrary } from './usePlacesLibrary'; vi.mock('../../repo/placesLibraryRepo', () => ({ placesLibraryRepo: { list: vi.fn(), detail: vi.fn(), coverPhoto: vi.fn() }, })); const list = vi.mocked(placesLibraryRepo.list); const detail = vi.mocked(placesLibraryRepo.detail); const coverPhoto = vi.mocked(placesLibraryRepo.coverPhoto); // A stable identity t: the hook's failure handler depends on it. const t: TranslationFn = (key) => key; const FIRST_PAGE = { sort: 'name', limit: 60 }; function deferred() { let resolve: (value: T) => void = () => undefined; const promise = new Promise((res) => { resolve = res; }); return { promise, resolve }; } function apiError(message: string) { return { response: { data: { error: message } } }; } function mount(active = true) { return renderHook(({ on }: { on: boolean }) => usePlacesLibrary({ active: on, t }), { initialProps: { on: active }, }); } async function mountLoaded(page: PlacesLibraryPageResponse = libraryPage([libraryEntry()])) { list.mockResolvedValue(page); const view = mount(); await waitFor(() => expect(view.result.current.loading).toBe(false)); return view; } beforeEach(() => { list.mockReset(); detail.mockReset(); coverPhoto.mockReset(); coverPhoto.mockResolvedValue(null); useSaveToCollectionStore.setState({ version: 0 }); }); describe('parseEntryKey and entryHasPosition', () => { it('FE-COMP-PLACESLIBHOOK-001: reads a trip or list key and refuses anything else', () => { expect(parseEntryKey('trip:42')).toEqual({ kind: 'trip', id: 42 }); expect(parseEntryKey('list:900')).toEqual({ kind: 'list', id: 900 }); expect(parseEntryKey('own:3')).toBeNull(); expect(parseEntryKey('trip:abc')).toBeNull(); expect(parseEntryKey('trip:4:5')).toBeNull(); }); it('FE-COMP-PLACESLIBHOOK-002: an entry is a map point only with two finite coordinates', () => { expect(entryHasPosition({ lat: 41.9, lng: 12.5 })).toBe(true); expect(entryHasPosition({ lat: 0, lng: 0 })).toBe(true); expect(entryHasPosition({ lat: null, lng: 12.5 })).toBe(false); expect(entryHasPosition({ lat: 41.9, lng: null })).toBe(false); expect(entryHasPosition({ lat: Number.NaN, lng: 12.5 })).toBe(false); expect(entryHasPosition({ lat: 41.9, lng: Number.POSITIVE_INFINITY })).toBe(false); }); }); describe('usePlacesLibrary: the first page', () => { it('FE-COMP-PLACESLIBHOOK-003: asks nothing while inactive and loads once it becomes active', async () => { list.mockResolvedValue(libraryPage([])); const { rerender, result } = mount(false); expect(list).not.toHaveBeenCalled(); expect(result.current.loading).toBe(false); rerender({ on: true }); await waitFor(() => expect(list).toHaveBeenCalledTimes(1)); }); it('FE-COMP-PLACESLIBHOOK-004: loads the first page with its total, counts and cursor', async () => { const pending = deferred(); list.mockReturnValue(pending.promise); const { result } = mount(); expect(result.current.loading).toBe(true); expect(list).toHaveBeenCalledWith(FIRST_PAGE, expect.any(AbortSignal)); const placed = libraryEntry({ key: 'trip:1', name: 'Pantheon' }); const unplaced = libraryEntry({ key: 'list:2', name: 'Somewhere', lat: null, lng: null }); await act(async () => { pending.resolve( libraryPage([placed, unplaced], { total: 7, counts: { all: 7, trip: 4, list: 3 }, next_cursor: 'c1' }) ); await pending.promise; }); expect(result.current.loading).toBe(false); expect(result.current.entries).toEqual([placed, unplaced]); expect(result.current.mappable).toEqual([placed]); expect(result.current.total).toBe(7); expect(result.current.counts).toEqual({ all: 7, trip: 4, list: 3 }); expect(result.current.hasMore).toBe(true); expect(result.current.error).toBeNull(); expect(result.current.offline).toBe(false); }); it('FE-COMP-PLACESLIBHOOK-005: without a connection it says offline instead of failing', async () => { list.mockRejectedValue(new OnlineOnlyError()); const { result } = mount(); await waitFor(() => expect(result.current.offline).toBe(true)); expect(result.current.error).toBeNull(); expect(result.current.loading).toBe(false); }); it("FE-COMP-PLACESLIBHOOK-006: a failure shows the server's message, else the generic error", async () => { list.mockRejectedValueOnce(apiError('Library is down')); const { result } = mount(); await waitFor(() => expect(result.current.error).toBe('Library is down')); list.mockRejectedValueOnce(new Error('network')); act(() => result.current.reload()); await waitFor(() => expect(result.current.error).toBe('common.error')); expect(result.current.offline).toBe(false); }); it('FE-COMP-PLACESLIBHOOK-007: reload asks for the first page again and clears an earlier error', async () => { list.mockRejectedValueOnce(apiError('Boom')); const { result } = mount(); await waitFor(() => expect(result.current.error).toBe('Boom')); list.mockResolvedValueOnce(libraryPage([libraryEntry()])); act(() => result.current.reload()); await waitFor(() => expect(result.current.entries).toHaveLength(1)); expect(result.current.error).toBeNull(); expect(list).toHaveBeenCalledTimes(2); }); }); describe('usePlacesLibrary: filters and search', () => { it('FE-COMP-PLACESLIBHOOK-008: each filter goes to the server and marks the overview as filtered', async () => { const { result } = await mountLoaded(libraryPage([])); expect(result.current.filtered).toBe(false); act(() => result.current.setKind('trip')); await waitFor(() => expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, kind: 'trip' }, expect.any(AbortSignal)) ); expect(result.current.filtered).toBe(true); act(() => { result.current.setCategoryId(3); result.current.setStatus('want'); result.current.setSort('updated'); }); await waitFor(() => expect(list).toHaveBeenLastCalledWith( { kind: 'trip', category_id: 3, status: 'want', sort: 'updated', limit: 60 }, expect.any(AbortSignal) ) ); expect(result.current.kind).toBe('trip'); expect(result.current.categoryId).toBe(3); expect(result.current.status).toBe('want'); expect(result.current.sort).toBe('updated'); }); it('FE-COMP-PLACESLIBHOOK-009: clearing the filters keeps the order but drops every filter', async () => { const { result } = await mountLoaded(libraryPage([])); act(() => { result.current.setKind('list'); result.current.setStatus('visited'); result.current.setSort('updated'); result.current.setSearch('rome'); }); await waitFor(() => expect(result.current.filtered).toBe(true)); act(() => result.current.resetFilters()); expect(result.current.search).toBe(''); expect(result.current.kind).toBe('all'); expect(result.current.categoryId).toBe('all'); expect(result.current.status).toBe('all'); expect(result.current.sort).toBe('updated'); expect(result.current.filtered).toBe(false); await waitFor(() => expect(list).toHaveBeenLastCalledWith({ sort: 'updated', limit: 60 }, expect.any(AbortSignal))); }); it('FE-COMP-PLACESLIBHOOK-010: typing settles before it asks, trimmed, and only the last word asks', async () => { const { result } = await mountLoaded(libraryPage([])); act(() => result.current.setSearch('ro')); act(() => result.current.setSearch(' rome ')); expect(result.current.search).toBe(' rome '); expect(list).toHaveBeenCalledTimes(1); expect(result.current.filtered).toBe(false); await waitFor(() => expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, q: 'rome' }, expect.any(AbortSignal))); expect(list).toHaveBeenCalledTimes(2); expect(list).not.toHaveBeenCalledWith(expect.objectContaining({ q: 'ro' }), expect.anything()); expect(result.current.filtered).toBe(true); }); it('FE-COMP-PLACESLIBHOOK-011: a filter change drops the page still on its way', async () => { const stale = deferred(); list.mockReturnValueOnce(stale.promise); const { result } = mount(); const firstSignal = list.mock.calls[0]?.[1]; const fresh = libraryEntry({ key: 'trip:2', name: 'Fresh' }); list.mockResolvedValueOnce(libraryPage([fresh])); act(() => result.current.setKind('trip')); expect(firstSignal?.aborted).toBe(true); await waitFor(() => expect(result.current.entries).toEqual([fresh])); await act(async () => { stale.resolve(libraryPage([libraryEntry({ key: 'trip:1', name: 'Stale' })])); await stale.promise; }); expect(result.current.entries).toEqual([fresh]); expect(result.current.loading).toBe(false); }); }); describe('usePlacesLibrary: more pages', () => { it('FE-COMP-PLACESLIBHOOK-012: "more" appends the next page from the cursor without doubles', async () => { const { result } = await mountLoaded( libraryPage([libraryEntry({ key: 'trip:1' }), libraryEntry({ key: 'trip:2' })], { total: 3, next_cursor: 'c1', }) ); list.mockResolvedValueOnce( libraryPage([libraryEntry({ key: 'trip:2' }), libraryEntry({ key: 'trip:3' })], { next_cursor: null }) ); await act(async () => { await result.current.loadMore(); }); expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, cursor: 'c1' }, expect.any(AbortSignal)); expect(result.current.entries.map((e) => e.key)).toEqual(['trip:1', 'trip:2', 'trip:3']); expect(result.current.hasMore).toBe(false); expect(result.current.loadingMore).toBe(false); expect(result.current.total).toBe(3); }); it('FE-COMP-PLACESLIBHOOK-013: "more" asks nothing when there is no next page', async () => { const { result } = await mountLoaded(libraryPage([libraryEntry()])); await act(async () => { await result.current.loadMore(); }); expect(list).toHaveBeenCalledTimes(1); }); it('FE-COMP-PLACESLIBHOOK-014: "more" shows its loading state and a failure as the error', async () => { const { result } = await mountLoaded(libraryPage([libraryEntry()], { next_cursor: 'c1' })); const next = deferred(); list.mockReturnValueOnce(next.promise.then(() => Promise.reject(apiError('Page gone')))); let call: Promise = Promise.resolve(); act(() => { call = result.current.loadMore(); }); expect(result.current.loadingMore).toBe(true); await act(async () => { next.resolve(libraryPage([])); await call; }); expect(result.current.loadingMore).toBe(false); expect(result.current.error).toBe('Page gone'); expect(result.current.entries).toHaveLength(1); }); it('FE-COMP-PLACESLIBHOOK-025: a filter changed while "more" loads frees the button again', async () => { const { result } = await mountLoaded(libraryPage([libraryEntry()], { next_cursor: 'c1' })); const next = deferred(); list.mockReturnValueOnce(next.promise); act(() => { void result.current.loadMore(); }); expect(result.current.loadingMore).toBe(true); list.mockResolvedValue(libraryPage([libraryEntry()])); act(() => result.current.setKind('trip')); expect(result.current.loadingMore).toBe(false); }); it('FE-COMP-PLACESLIBHOOK-015: "more" without a connection says offline', async () => { const { result } = await mountLoaded(libraryPage([libraryEntry()], { next_cursor: 'c1' })); list.mockRejectedValueOnce(new OnlineOnlyError()); await act(async () => { await result.current.loadMore(); }); expect(result.current.offline).toBe(true); expect(result.current.error).toBeNull(); }); }); describe('usePlacesLibrary: the open entry', () => { it('FE-COMP-PLACESLIBHOOK-016: opening an entry loads what its origin keeps; opening it again closes it', async () => { const { result } = await mountLoaded(); const answer = libraryDetail(libraryEntry({ image_url: '/uploads/own.jpg' }), [tripDetail()]); const pending = deferred(); detail.mockReturnValueOnce(pending.promise); act(() => result.current.open('trip:42')); expect(result.current.selectedKey).toBe('trip:42'); expect(result.current.detailLoading).toBe(true); expect(detail).toHaveBeenCalledWith('trip', 42, expect.any(AbortSignal)); await act(async () => { pending.resolve(answer); await pending.promise; }); expect(result.current.detail).toBe(answer); expect(result.current.detailLoading).toBe(false); act(() => result.current.open('trip:42')); expect(result.current.selectedKey).toBeNull(); expect(result.current.detail).toBeNull(); }); it('FE-COMP-PLACESLIBHOOK-017: show keeps an entry open, close shuts it, a saved place is asked as a list one', async () => { const { result } = await mountLoaded(); detail.mockResolvedValue(libraryDetail(libraryEntry({ key: 'list:900', origins: [listOrigin()] }), [listDetail()])); act(() => result.current.show('list:900')); act(() => result.current.show('list:900')); expect(result.current.selectedKey).toBe('list:900'); await waitFor(() => expect(result.current.detail?.entry.key).toBe('list:900')); expect(detail).toHaveBeenCalledTimes(1); expect(detail).toHaveBeenCalledWith('list', 900, expect.any(AbortSignal)); act(() => result.current.close()); expect(result.current.selectedKey).toBeNull(); expect(result.current.detail).toBeNull(); expect(result.current.cover).toBeNull(); }); it('FE-COMP-PLACESLIBHOOK-018: a key it cannot read loads nothing', async () => { const { result } = await mountLoaded(); act(() => result.current.open('own:5')); expect(result.current.selectedKey).toBe('own:5'); expect(detail).not.toHaveBeenCalled(); expect(result.current.detail).toBeNull(); }); it('FE-COMP-PLACESLIBHOOK-019: a failed detail closes the entry and shows the error', async () => { const { result } = await mountLoaded(); detail.mockRejectedValueOnce(apiError('Place is gone')); act(() => result.current.open('trip:42')); await waitFor(() => expect(result.current.error).toBe('Place is gone')); expect(result.current.selectedKey).toBeNull(); expect(result.current.detail).toBeNull(); }); it('FE-COMP-PLACESLIBHOOK-020: a detail without a connection says offline', async () => { const { result } = await mountLoaded(); detail.mockRejectedValueOnce(new OnlineOnlyError()); act(() => result.current.open('trip:42')); await waitFor(() => expect(result.current.offline).toBe(true)); expect(result.current.selectedKey).toBeNull(); }); it('FE-COMP-PLACESLIBHOOK-021: reload asks for the open entry again too', async () => { const { result } = await mountLoaded(); detail.mockResolvedValue(libraryDetail(libraryEntry(), [tripDetail()])); act(() => result.current.open('trip:42')); await waitFor(() => expect(result.current.detail).not.toBeNull()); act(() => result.current.reload()); await waitFor(() => expect(detail).toHaveBeenCalledTimes(2)); expect(list).toHaveBeenCalledTimes(2); }); }); describe('usePlacesLibrary: the cover', () => { it("FE-COMP-PLACESLIBHOOK-022: the entry's own image wins, else the first origin image", async () => { const { result } = await mountLoaded(); detail.mockResolvedValueOnce(libraryDetail(libraryEntry({ image_url: '/uploads/entry.jpg' }), [tripDetail()])); act(() => result.current.open('trip:42')); await waitFor(() => expect(result.current.cover).toBe('/uploads/entry.jpg')); act(() => result.current.close()); detail.mockResolvedValueOnce( libraryDetail(libraryEntry({ key: 'trip:7', origins: [] }), [ tripDetail(), listDetail({ info: libraryInfo({ image_url: '/uploads/list.jpg' }) }), ]) ); act(() => result.current.open('trip:7')); await waitFor(() => expect(result.current.cover).toBe('/uploads/list.jpg')); expect(coverPhoto).not.toHaveBeenCalled(); }); it("FE-COMP-PLACESLIBHOOK-023: without an image of its own it asks the provider's photo", async () => { const { result } = await mountLoaded(); const entry = libraryEntry(); coverPhoto.mockResolvedValueOnce('https://photos.example/colosseum.jpg'); detail.mockResolvedValueOnce(libraryDetail(entry, [tripDetail()])); act(() => result.current.open('trip:42')); await waitFor(() => expect(result.current.cover).toBe('https://photos.example/colosseum.jpg')); expect(coverPhoto).toHaveBeenCalledWith(entry); }); it('FE-COMP-PLACESLIBHOOK-024: a failed photo lookup leaves the gradient', async () => { const { result } = await mountLoaded(); coverPhoto.mockRejectedValueOnce(new Error('no photo')); detail.mockResolvedValueOnce(libraryDetail(libraryEntry(), [tripDetail()])); act(() => result.current.open('trip:42')); await waitFor(() => expect(coverPhoto).toHaveBeenCalledTimes(1)); await act(async () => { await Promise.resolve(); }); expect(result.current.cover).toBeNull(); expect(result.current.detail).not.toBeNull(); }); it('FE-COMP-PLACESLIBHOOK-026: an own place opens through its first use', () => { const trip = libraryEntry({ key: 'own:3' }); expect(firstOrigin([trip], 'own:3')).toEqual( trip.origins[0].kind === 'trip' ? { kind: 'trip', id: trip.origins[0].place_id } : { kind: 'list', id: trip.origins[0].collection_place_id } ); expect(firstOrigin([trip], 'own:9')).toBeNull(); }); }); 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); }); });