diff --git a/app/views/DirectoryView/hooks/__tests__/useDirectorySearch.test.ts b/app/views/DirectoryView/hooks/__tests__/useDirectorySearch.test.ts new file mode 100644 index 00000000000..343641c657a --- /dev/null +++ b/app/views/DirectoryView/hooks/__tests__/useDirectorySearch.test.ts @@ -0,0 +1,188 @@ +import { act, renderHook, waitFor } from '@testing-library/react-native'; + +import { getDirectory } from '~/lib/services/restApi'; +import { useDirectorySearch } from '../useDirectorySearch'; + +jest.mock('~/lib/services/restApi', () => ({ getDirectory: jest.fn() })); + +const mockGetDirectory = getDirectory as jest.MockedFunction; + +const rooms = (...ids: string[]) => ids.map(_id => ({ _id, name: _id })); + +const pageResponse = (result: ReturnType, total: number) => + ({ success: true, result, total, count: result.length, offset: 0 }) as never; + +const respondWith = (result: ReturnType, total: number) => + mockGetDirectory.mockResolvedValueOnce(pageResponse(result, total)); + +const respondLater = () => { + let respond: (result: ReturnType, total: number) => void = () => {}; + mockGetDirectory.mockReturnValueOnce( + new Promise(resolve => { + respond = (result, total) => resolve(pageResponse(result, total)); + }) + ); + return (result: ReturnType, total: number) => respond(result, total); +}; + +const runDebounced = async (trigger: () => void) => { + await act(async () => { + trigger(); + await jest.runOnlyPendingTimersAsync(); + }); +}; + +const roomIds = (rows: { _id: string }[]) => rows.map(room => room._id); + +describe('useDirectorySearch', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + jest.clearAllMocks(); + }); + + it('keeps one row per room when pages overlap', async () => { + respondWith(rooms('a', 'b', 'c'), 5); + const { result } = renderHook(() => useDirectorySearch('channels')); + await waitFor(() => expect(result.current.data).toHaveLength(3)); + + respondWith(rooms('c', 'd', 'e'), 5); + await runDebounced(result.current.loadMore); + + expect(roomIds(result.current.data)).toEqual(['a', 'b', 'c', 'd', 'e']); + }); + + it('keeps one row per room when a page repeats a room', async () => { + respondWith(rooms('a', 'a', 'b'), 5); + const { result } = renderHook(() => useDirectorySearch('channels')); + await waitFor(() => expect(result.current.data).toHaveLength(2)); + expect(roomIds(result.current.data)).toEqual(['a', 'b']); + + respondWith(rooms('c', 'd'), 5); + await runDebounced(result.current.loadMore); + + expect(mockGetDirectory).toHaveBeenLastCalledWith(expect.objectContaining({ offset: 3 })); + expect(roomIds(result.current.data)).toEqual(['a', 'b', 'c', 'd']); + }); + + it('requests the next page after every row the server returned', async () => { + respondWith(rooms('a', 'b', 'c'), 7); + const { result } = renderHook(() => useDirectorySearch('channels')); + await waitFor(() => expect(result.current.data).toHaveLength(3)); + + respondWith(rooms('c', 'd', 'e'), 7); + await runDebounced(result.current.loadMore); + expect(result.current.data).toHaveLength(5); + + respondWith(rooms('f'), 7); + await runDebounced(result.current.loadMore); + + expect(mockGetDirectory).toHaveBeenLastCalledWith(expect.objectContaining({ offset: 6 })); + expect(result.current.data).toHaveLength(6); + }); + + it('stops loading more once every server row was fetched', async () => { + respondWith(rooms('a', 'b'), 3); + const { result } = renderHook(() => useDirectorySearch('channels')); + await waitFor(() => expect(result.current.data).toHaveLength(2)); + + respondWith(rooms('b'), 3); + await runDebounced(result.current.loadMore); + expect(mockGetDirectory).toHaveBeenCalledTimes(2); + + await runDebounced(result.current.loadMore); + + expect(mockGetDirectory).toHaveBeenCalledTimes(2); + }); + + it('runs a new search even when the list asks for more rows right after it', async () => { + respondWith(rooms('a', 'b'), 10); + const { result } = renderHook(() => useDirectorySearch('channels')); + await waitFor(() => expect(result.current.data).toHaveLength(2)); + + respondWith(rooms('x'), 1); + act(() => result.current.onSearchChangeText('x')); + await runDebounced(result.current.loadMore); + + expect(mockGetDirectory).toHaveBeenLastCalledWith(expect.objectContaining({ text: 'x', offset: 0 })); + expect(roomIds(result.current.data)).toEqual(['x']); + }); + + it('drops a page that arrives after a newer search started', async () => { + respondWith(rooms('a', 'b'), 10); + const { result } = renderHook(() => useDirectorySearch('channels')); + await waitFor(() => expect(result.current.data).toHaveLength(2)); + + const respondToLoadMore = respondLater(); + await runDebounced(result.current.loadMore); + + respondWith(rooms('x'), 1); + await runDebounced(() => result.current.onSearchChangeText('x')); + expect(roomIds(result.current.data)).toEqual(['x']); + + await act(async () => { + respondToLoadMore(rooms('c', 'd'), 10); + await jest.runOnlyPendingTimersAsync(); + }); + + expect(roomIds(result.current.data)).toEqual(['x']); + }); + + it('drops a page that arrives while a newer search waits for its debounce', async () => { + respondWith(rooms('a', 'b'), 10); + const { result } = renderHook(() => useDirectorySearch('channels')); + await waitFor(() => expect(result.current.data).toHaveLength(2)); + + const respondToLoadMore = respondLater(); + await runDebounced(result.current.loadMore); + + act(() => result.current.onSearchChangeText('x')); + await act(async () => { + respondToLoadMore(rooms('c', 'd'), 10); + }); + expect(result.current.data).toEqual([]); + + respondWith(rooms('x'), 1); + await act(async () => { + await jest.runOnlyPendingTimersAsync(); + }); + + expect(mockGetDirectory).toHaveBeenLastCalledWith(expect.objectContaining({ text: 'x', offset: 0 })); + expect(roomIds(result.current.data)).toEqual(['x']); + expect(result.current.loading).toBe(false); + }); + + it('hides the previous type rows while the new type waits for its debounce', async () => { + respondWith(rooms('a', 'b'), 2); + const { result } = renderHook(() => useDirectorySearch('channels')); + await waitFor(() => expect(result.current.data).toHaveLength(2)); + + act(() => result.current.changeType('users')); + + expect(result.current.type).toBe('users'); + expect(result.current.data).toEqual([]); + expect(result.current.loading).toBe(true); + + respondWith(rooms('u'), 1); + await act(async () => { + await jest.runOnlyPendingTimersAsync(); + }); + + expect(mockGetDirectory).toHaveBeenLastCalledWith(expect.objectContaining({ type: 'users', offset: 0 })); + expect(roomIds(result.current.data)).toEqual(['u']); + expect(result.current.loading).toBe(false); + }); + + it('hides the previous search rows while the new text waits for its debounce', async () => { + respondWith(rooms('a', 'b'), 2); + const { result } = renderHook(() => useDirectorySearch('channels')); + await waitFor(() => expect(result.current.data).toHaveLength(2)); + + act(() => result.current.onSearchChangeText('')); + + expect(result.current.data).toEqual([]); + }); +}); diff --git a/app/views/DirectoryView/hooks/useDirectorySearch.ts b/app/views/DirectoryView/hooks/useDirectorySearch.ts index aa7603a5c77..7e0b78bf888 100644 --- a/app/views/DirectoryView/hooks/useDirectorySearch.ts +++ b/app/views/DirectoryView/hooks/useDirectorySearch.ts @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { type IServerRoom } from '~/definitions'; import { announceSearchResultsForAccessibility } from '~/lib/methods/helpers/announceSearchResultsForAccessibility'; @@ -6,24 +6,47 @@ import { useDebounce } from '~/lib/methods/helpers/debounce'; import log, { events, logEvent } from '~/lib/methods/helpers/log'; import { getDirectory } from '~/lib/services/restApi'; +type DirectoryResults = { rooms: IServerRoom[]; fetchedCount: number; total: number }; + +const emptyResults: DirectoryResults = { rooms: [], fetchedCount: 0, total: -1 }; + +const appendPage = (results: DirectoryResults, page: IServerRoom[], total: number): DirectoryResults => { + const ids = new Set(results.rooms.map(room => room._id)); + const newRooms = page.filter(room => { + if (ids.has(room._id)) { + return false; + } + ids.add(room._id); + return true; + }); + return { + rooms: [...results.rooms, ...newRooms], + fetchedCount: results.fetchedCount + page.length, + total + }; +}; + +const hasMore = (results: DirectoryResults) => results.fetchedCount < results.total; + export const useDirectorySearch = (directoryDefaultView: string) => { - const [data, setData] = useState([]); - const [loading, setLoading] = useState(false); + const [results, setResults] = useState(emptyResults); + const [loading, setLoading] = useState(true); const [text, setText] = useState(''); - const [total, setTotal] = useState(-1); const [globalUsers, setGlobalUsers] = useState(true); const [type, setType] = useState(directoryDefaultView); + const searchGeneration = useRef(0); + const newSearchPending = useRef(false); // useDebounce keeps a ref to the latest callback, so this always reads fresh state - const load = useDebounce(async ({ newSearch = false }: { newSearch?: boolean } = {}) => { - if (!newSearch && (loading || data.length === total)) { + const load = useDebounce(async () => { + const newSearch = newSearchPending.current; + newSearchPending.current = false; + if (!newSearch && (loading || !hasMore(results))) { return; } - if (newSearch) { - setData([]); - setTotal(-1); - } + const requestGeneration = searchGeneration.current; + const isStale = () => requestGeneration !== searchGeneration.current; setLoading(true); try { @@ -31,13 +54,15 @@ export const useDirectorySearch = (directoryDefaultView: string) => { text, type, workspace: globalUsers ? 'all' : 'local', - offset: newSearch ? 0 : data.length, + offset: newSearch ? 0 : results.fetchedCount, count: 50, sort: type === 'users' ? { username: 1 } : { usersCount: -1 } }); + if (isStale()) { + return; + } if (directories.success) { - setData(prev => [...(newSearch ? [] : prev), ...(directories.result as IServerRoom[])]); - setTotal(directories.total); + setResults(prev => appendPage(newSearch ? emptyResults : prev, directories.result as IServerRoom[], directories.total)); setLoading(false); // Announce the full total on a fresh search; loadMore pages shouldn't re-announce if (newSearch) { @@ -48,12 +73,23 @@ export const useDirectorySearch = (directoryDefaultView: string) => { } } catch (e) { log(e); - setLoading(false); + if (!isStale()) { + setLoading(false); + } } }, 200); - const search = () => load({ newSearch: true }); - const loadMore = () => load({}); + const startSearch = () => { + searchGeneration.current += 1; + newSearchPending.current = true; + load(); + }; + const search = () => { + setResults(emptyResults); + setLoading(true); + startSearch(); + }; + const loadMore = () => load(); const onSearchChangeText = (newText: string) => { setText(newText); @@ -79,13 +115,12 @@ export const useDirectorySearch = (directoryDefaultView: string) => { search(); }; - // Run the initial search when the hook mounts; `search` is stable, so this fires once useEffect(() => { - search(); + startSearch(); }, []); return { - data, + data: results.rooms, loading, type, globalUsers,