Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion apps/web/src/features/recipes/RecipeCreatePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -870,7 +870,10 @@ function RecipeEditPage({ id }: { id: string }) {
(signal: AbortSignal) => getRecipe(id, signal),
[id],
);
const query = useRecipeQuery(id, load, { refreshOnMutation: false });
const query = useRecipeQuery(id, load, {
refreshOnMutation: false,
refreshWhenStale: false,
});
if (query.loading || query.error)
return <RecipeQueryStatus {...query} label="Loading recipe for editing…" />;
if (!query.data)
Expand Down
15 changes: 12 additions & 3 deletions apps/web/src/features/recipes/recipeQueryCache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const TTL_MS = 30_000;
/** How long fetched recipe data counts as fresh (cache and refresh-on-focus). */
export const RECIPE_FRESHNESS_MS = 30_000;
const TTL_MS = RECIPE_FRESHNESS_MS;
const MAX_ENTRIES = 40;
const entries = new Map<string, { data: unknown; expires: number }>();
let generation = 0;
Expand All @@ -8,18 +10,25 @@ export function clearRecipeQueryCache() {
generation += 1;
}

/** Drops one entry so the next read fetches from the API. */
export function forgetRecipeCache(key: string) {
entries.delete(key);
}

export function recipeCacheGeneration() {
return generation;
}

export function readRecipeCache<T>(key: string): { data: T } | undefined {
export function readRecipeCache<T>(
key: string,
): { data: T; fetchedAt: number } | undefined {
const entry = entries.get(key);
if (!entry) return;
if (entry.expires <= Date.now()) {
entries.delete(key);
return;
}
return { data: entry.data as T };
return { data: entry.data as T, fetchedAt: entry.expires - TTL_MS };
}

export function writeRecipeCache(key: string, data: unknown, started: number) {
Expand Down
36 changes: 36 additions & 0 deletions apps/web/src/features/recipes/useRecipeQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,39 @@ it('invalidates cached pages after a mutation while they are unmounted', async (
await waitFor(() => expect(second.result.current.data).toBe('after'));
expect(load).toHaveBeenCalledTimes(2);
});
it('refreshes stale data in the background when the page regains focus', async () => {
const now = vi.spyOn(Date, 'now');
now.mockReturnValue(1_000_000);
const load = vi
.fn<(_: AbortSignal) => Promise<string>>()
.mockResolvedValueOnce('first')
.mockResolvedValueOnce('fresh');
const { result } = renderHook(() => useRecipeQuery('freshness', load));
await waitFor(() => expect(result.current.data).toBe('first'));

// Returning after 10 s: still fresh, no request.
now.mockReturnValue(1_010_000);
act(() => window.dispatchEvent(new Event('focus')));
expect(load).toHaveBeenCalledTimes(1);

// After 31 s the data is stale: refetch, keeping the old data meanwhile.
now.mockReturnValue(1_031_000);
act(() => window.dispatchEvent(new Event('focus')));
expect(result.current.data).toBe('first');
await waitFor(() => expect(result.current.data).toBe('fresh'));
expect(load).toHaveBeenCalledTimes(2);
now.mockRestore();
});
it('never refreshes on focus when refreshWhenStale is off (forms)', async () => {
const now = vi.spyOn(Date, 'now');
now.mockReturnValue(2_000_000);
const load = vi.fn(async () => 'form data');
const { result } = renderHook(() =>
useRecipeQuery('editor', load, { refreshWhenStale: false }),
);
await waitFor(() => expect(result.current.data).toBe('form data'));
now.mockReturnValue(2_100_000);
act(() => window.dispatchEvent(new Event('focus')));
expect(load).toHaveBeenCalledTimes(1);
now.mockRestore();
});
45 changes: 42 additions & 3 deletions apps/web/src/features/recipes/useRecipeQuery.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useAppStore } from '../../store';
import { recipeErrorMessage, useRecipeChanges } from './recipeApi';
import {
readRecipeCache,
writeRecipeCache,
recipeCacheGeneration,
clearRecipeQueryCache,
forgetRecipeCache,
RECIPE_FRESHNESS_MS,
} from './recipeQueryCache';

useAppStore.subscribe((state, previous) => {
Expand All @@ -23,16 +25,29 @@ useRecipeChanges.subscribe((state, previous) => {
export function useRecipeQuery<T>(
key: string,
load: (signal: AbortSignal) => Promise<T>,
{ refreshOnMutation = true } = {},
{
refreshOnMutation = true,
// Refetch stale data when the user comes back to a long-open page.
// Off for forms (the editor), which must never replace typed input.
refreshWhenStale = true,
} = {},
) {
const userId = useAppStore((state) => state.currentUser?.id);
const sessionStatus = useAppStore((state) => state.sessionStatus);
const revision = useRecipeChanges((state) =>
refreshOnMutation ? state.revision : 0,
);
const [attempt, setAttempt] = useState(0);
// Bumped when the page regains focus with stale data (see below).
const [freshnessCheck, setFreshnessCheck] = useState(0);
const fetchedAt = useRef(0);
const identity = JSON.stringify([key, userId]);
const requestKey = JSON.stringify([identity, revision, attempt]);
const requestKey = JSON.stringify([
identity,
revision,
attempt,
freshnessCheck,
]);
const waiting = sessionStatus === 'restoring';
const [state, setState] = useState<{
identity: string;
Expand All @@ -53,6 +68,7 @@ export function useRecipeQuery<T>(
(data) => {
if (!controller.signal.aborted) {
if (!cached) writeRecipeCache(identity, data, generation);
fetchedAt.current = cached ? cached.fetchedAt : Date.now();
setState({ identity, key: requestKey, hasData: true, data });
}
},
Expand All @@ -70,6 +86,29 @@ export function useRecipeQuery<T>(
}, [identity, requestKey, load, waiting, attempt]);
const current = !waiting && state.identity === identity ? state : undefined;
const hasData = current?.hasData ?? false;

/*
* A page left open (e.g. in a background tab) is refreshed when the user
* returns to it, if its data is older than RECIPE_FRESHNESS_MS. The
* refresh runs in the background: the shown data stays until new data
* arrives (`refreshing`), and failures appear as `refreshError`.
*/
useEffect(() => {
if (!refreshWhenStale || !hasData) return;
function refreshIfStale() {
if (document.visibilityState === 'hidden') return;
if (Date.now() - fetchedAt.current < RECIPE_FRESHNESS_MS) return;
forgetRecipeCache(identity);
fetchedAt.current = Date.now(); // Avoid repeats while it loads.
setFreshnessCheck((value) => value + 1);
}
window.addEventListener('focus', refreshIfStale);
document.addEventListener('visibilitychange', refreshIfStale);
return () => {
window.removeEventListener('focus', refreshIfStale);
document.removeEventListener('visibilitychange', refreshIfStale);
};
}, [refreshWhenStale, hasData, identity]);
return {
data: hasData ? current?.data : undefined,
error: !hasData && current?.key === requestKey ? current.error : undefined,
Expand Down