fix(emoji-board): cancel in-flight gif searches and debounce timers (#1562)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

gif search never aborted its requests so a slow response could land
after you closed the picker or typed something newer and overwrite the
results. now aborts and ignores stale ones.

useDebounce also never cleared its timer on unmount, now it does and
returns a cancel().

Fixes #

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
7w1 authored and GitHub committed 2026-08-06 03:17:07 +00:00
commit c4cc35c19d
5 files changed
+244 -21

No files matched your search

+14 -5
View File
@@ -1,5 +1,5 @@
import type {
ChangeEventHandler,
ChangeEvent,
FocusEventHandler,
MouseEventHandler,
ReactNode,
@@ -527,7 +527,8 @@ export function EmojiBoard({
loading: gifsLoading,
error: gifsError,
searchGifs,
} = useGifSearch(favoriteGifs, showGifPicker, gifSearch);
cancelSearch: cancelGifSearch,
} = useGifSearch(favoriteGifs, showGifPicker && gifTab, gifSearch);
const [emojiGroupItems, stickerGroupItems, gifGroupItems] = useGroups(tab, imagePacks, gifs);
const [showFavoritesOnly, setShowFavoritesOnly] = useState(true);
const groupsByTab = {
@@ -555,9 +556,9 @@ export function EmojiBoard({
const groups = groupsByTab[tab];
const renderItem = useItemRenderer(tab, saveStickerEmojiBandwidth);
const handleOnChange: ChangeEventHandler<HTMLInputElement> = useDebounce(
const handleOnChange = useDebounce(
useCallback(
(evt) => {
(evt: ChangeEvent<HTMLInputElement>) => {
const term = evt.target.value;
if (tab === EmojiBoardTab.Gif) {
if (term) {
@@ -565,6 +566,7 @@ export function EmojiBoard({
searchGifs(term);
} else {
setShowFavoritesOnly(true);
cancelGifSearch();
resetGifSearch();
}
} else if (term) {
@@ -573,7 +575,7 @@ export function EmojiBoard({
resetEmojiSearch();
}
},
[emojiSearch, resetEmojiSearch, searchGifs, resetGifSearch, tab]
[cancelGifSearch, emojiSearch, resetEmojiSearch, searchGifs, resetGifSearch, tab]
),
{ wait: 200 }
);
@@ -585,6 +587,13 @@ export function EmojiBoard({
else resetGifSearch();
}, [gifTab, initialGifSearch, searchGifs, resetGifSearch]);
useEffect(() => {
if (!showGifPicker || !gifTab) {
handleOnChange.cancel();
cancelGifSearch();
}
}, [cancelGifSearch, gifTab, handleOnChange, showGifPicker]);
const contentScrollRef = useRef<HTMLDivElement>(null);
const virtualBaseRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
@@ -0,0 +1,134 @@
import { act, renderHook } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { useGifSearch } from './useGifSearch';
const { fetchMock } = vi.hoisted(() => ({
fetchMock: vi.fn<(input: string, init?: RequestInit) => Promise<Response>>(),
}));
vi.mock('$utils/fetch', () => ({ fetch: fetchMock }));
vi.mock('$hooks/useClientConfig', () => ({
useClientConfig: () => ({ gifs: { klipyApiKey: 'test-key' } }),
}));
type Deferred<T> = {
promise: Promise<T>;
resolve: (value: T) => void;
reject: (reason?: unknown) => void;
};
const deferred = <T,>(): Deferred<T> => {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((promiseResolve, promiseReject) => {
resolve = promiseResolve;
reject = promiseReject;
});
return { promise, resolve, reject };
};
const responseFor = (id: string): Response =>
new Response(
JSON.stringify({
data: {
data: [
{
id,
title: id,
file: { xs: { gif: { url: `https://${id}.preview` } } },
},
],
},
}),
{ status: 200 }
);
const flushPromises = async () => {
await Promise.resolve();
await Promise.resolve();
};
afterEach(() => {
fetchMock.mockReset();
});
describe('useGifSearch', () => {
it('keeps stale success, error, and finally handlers from changing the latest request', async () => {
const first = deferred<Response>();
const second = deferred<Response>();
fetchMock.mockImplementation((url: string) =>
url.includes('q=first') ? first.promise : second.promise
);
const { result } = renderHook(() => useGifSearch([], true, vi.fn<() => void>()));
act(() => {
void result.current.searchGifs('first');
void result.current.searchGifs('second');
});
const firstSignal = fetchMock.mock.calls[0]?.[1]?.signal as AbortSignal;
expect(firstSignal.aborted).toBe(true);
first.reject(new Error('stale failure'));
await act(async () => {
await flushPromises();
});
expect(result.current.loading).toBe(true);
expect(result.current.error).toBeNull();
second.resolve(responseFor('second'));
await act(async () => {
await flushPromises();
});
expect(result.current.gifs.gifs[0]?.id).toBe('second');
expect(result.current.loading).toBe(false);
first.resolve(responseFor('first'));
await act(async () => {
await flushPromises();
});
expect(result.current.gifs.gifs[0]?.id).toBe('second');
});
it('aborts and invalidates a request when cancelled or closed', async () => {
const request = deferred<Response>();
fetchMock.mockReturnValue(request.promise);
const { result, rerender } = renderHook(
({ open }) => useGifSearch([], open, vi.fn<() => void>()),
{ initialProps: { open: true } }
);
act(() => {
void result.current.searchGifs('query');
});
const signal = fetchMock.mock.calls[0]?.[1]?.signal as AbortSignal;
rerender({ open: false });
expect(signal.aborted).toBe(true);
expect(result.current.loading).toBe(false);
request.resolve(responseFor('stale'));
await act(async () => {
await flushPromises();
});
expect(result.current.gifs.gifs).toEqual([]);
});
it('aborts the active request on unmount', () => {
const request = deferred<Response>();
fetchMock.mockReturnValue(request.promise);
const { result, unmount } = renderHook(() => useGifSearch([], true, vi.fn<() => void>()));
act(() => {
void result.current.searchGifs('query');
});
const signal = fetchMock.mock.calls[0]?.[1]?.signal as AbortSignal;
unmount();
expect(signal.aborted).toBe(true);
});
});
+49 -9
View File
@@ -1,4 +1,4 @@
import { useCallback, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { AsyncSearchHandler } from '$utils/AsyncSearch';
import { fetch } from '$utils/fetch';
import { useClientConfig } from '$hooks/useClientConfig';
@@ -57,14 +57,34 @@ export function useGifSearch(
const [error, setError] = useState<string | null>(null);
const clientConfig = useClientConfig();
const klipyApiKey = clientConfig.gifs?.klipyApiKey ?? '';
const requestGenerationRef = useRef(0);
const abortControllerRef = useRef<AbortController>();
const mountedRef = useRef(true);
const showGifPickerRef = useRef(showGifPicker);
showGifPickerRef.current = showGifPicker;
const cancelRequest = useCallback(() => {
requestGenerationRef.current += 1;
abortControllerRef.current?.abort();
abortControllerRef.current = undefined;
}, []);
const cancelSearch = useCallback(() => {
cancelRequest();
if (mountedRef.current) setLoading(false);
}, [cancelRequest]);
const searchGifs = useCallback(
async (query: string) => {
if (!showGifPicker) {
if (!mountedRef.current || !showGifPickerRef.current) {
return;
}
const trimmedQuery = query.trim();
cancelRequest();
const generation = requestGenerationRef.current;
const controller = new AbortController();
abortControllerRef.current = controller;
setLoading(true);
setError(null);
@@ -77,30 +97,50 @@ export function useGifSearch(
url.searchParams.set('q', trimmedQuery);
url.searchParams.set('per_page', '50'); // TODO: infinite scroll?
const response = await fetch(url.toString());
const response = await fetch(url.toString(), { signal: controller.signal });
if (response.status === 200) {
const data = (await response.json()) as KlipySearchResponse;
const results = data.data?.data;
setSearchResults(results ? results.map(parseKlipyResult) : []);
if (generation === requestGenerationRef.current && mountedRef.current) {
setSearchResults(results ? results.map(parseKlipyResult) : []);
}
} else {
throw new Error(`HTTP ${response.status}`);
}
} catch {
setError('Failed to search GIFs');
setSearchResults([]);
if (generation === requestGenerationRef.current && mountedRef.current) {
setError('Failed to search GIFs');
setSearchResults([]);
}
} finally {
setLoading(false);
if (generation === requestGenerationRef.current && mountedRef.current) {
abortControllerRef.current = undefined;
setLoading(false);
}
}
},
[klipyApiKey, showGifPicker, gifSearch]
[cancelRequest, klipyApiKey, gifSearch]
);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
cancelRequest();
};
}, [cancelRequest]);
useEffect(() => {
if (!showGifPicker) cancelSearch();
}, [cancelSearch, showGifPicker]);
const gifs = useMemo(
() => ({ gifs: searchResults, favorites: favoriteGifs }),
[searchResults, favoriteGifs]
);
return { gifs, loading, error, searchGifs };
return { gifs, loading, error, searchGifs, cancelSearch };
}
+29
View File
@@ -97,4 +97,33 @@ describe('useDebounce', () => {
expect(fn).toHaveBeenCalledOnce();
expect(fn).toHaveBeenCalledWith('go');
});
it('cancels a pending callback explicitly', () => {
const fn = vi.fn<(arg: string) => void>();
const { result } = renderHook(() => useDebounce(fn, { wait: 200 }));
act(() => {
result.current('cancelled');
result.current.cancel();
vi.advanceTimersByTime(200);
});
expect(fn).not.toHaveBeenCalled();
});
it('cancels a pending callback when unmounted', () => {
const fn = vi.fn<(arg: string) => void>();
const { result, unmount } = renderHook(() => useDebounce(fn, { wait: 200 }));
act(() => {
result.current('cancelled');
});
unmount();
act(() => {
vi.advanceTimersByTime(200);
});
expect(fn).not.toHaveBeenCalled();
});
});
+18 -7
View File
@@ -1,23 +1,32 @@
import { useCallback, useRef } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';
export interface DebounceOptions {
wait?: number;
immediate?: boolean;
}
export type DebounceCallback<T extends unknown[]> = (...args: T) => void;
export type DebouncedCallback<T extends unknown[]> = DebounceCallback<T> & {
cancel: () => void;
};
export function useDebounce<T extends unknown[]>(
callback: DebounceCallback<T>,
options?: DebounceOptions
): DebounceCallback<T> {
): DebouncedCallback<T> {
const timeoutIdRef = useRef<number>();
const { wait, immediate } = options ?? {};
const cancel = useCallback(() => {
if (timeoutIdRef.current !== undefined) {
clearTimeout(timeoutIdRef.current);
timeoutIdRef.current = undefined;
}
}, []);
const debounceCallback = useCallback(
(...cbArgs: T) => {
if (timeoutIdRef.current) {
clearTimeout(timeoutIdRef.current);
timeoutIdRef.current = undefined;
if (timeoutIdRef.current !== undefined) {
cancel();
} else if (immediate) {
callback(...cbArgs);
}
@@ -27,8 +36,10 @@ export function useDebounce<T extends unknown[]>(
timeoutIdRef.current = undefined;
}, wait);
},
[callback, wait, immediate]
[callback, cancel, wait, immediate]
);
return debounceCallback;
useEffect(() => cancel, [cancel]);
return useMemo(() => Object.assign(debounceCallback, { cancel }), [debounceCallback, cancel]);
}