Invites and fixed image caching
This commit is contained in:
1 parent
1706a906f0
commit
693a30f437
7 files changed
+193
-5
No files matched your search
+25
-3
@@ -1,3 +1,4 @@
|
||||
import { usePhotoRefresh } from './usePhotoRefresh';
|
||||
import { FlockSwitcher } from './FlockSwitcher';
|
||||
import { combineLocationOwnerMarkers } from './birdTimeline';
|
||||
import { BehaviorJournal } from './BehaviorJournal';
|
||||
@@ -2284,6 +2285,27 @@ function App() {
|
||||
const [expandedSettingsSection, setExpandedSettingsSection] = useState<SettingsSection | null>(null);
|
||||
|
||||
const flockBirds = useMemo(() => sortBirdsByName([...birds, ...memorializedBirds]), [birds, memorializedBirds]);
|
||||
const handlePhotoError = usePhotoRefresh({
|
||||
apiBaseUrl, token: authToken, workspaceId: workspace?.id, publicProfileCode,
|
||||
fallback: defaultBirdPhoto,
|
||||
onPhotos: (photos) => {
|
||||
const urls = new Map(photos.map((photo) => [photo.id, photo.photoDataUrl]));
|
||||
const update = (current: Bird[]) => current.map((bird) => urls.has(bird.id)
|
||||
? { ...bird, photoDataUrl: urls.get(bird.id) ?? null } : bird);
|
||||
setBirds(update);
|
||||
setMemorializedBirds(update);
|
||||
setPublicProfile((current) => current && urls.has(current.id)
|
||||
? { ...current, photoDataUrl: urls.get(current.id) ?? null } : current);
|
||||
// Renew the editor preview only if it still matches the saved photo.
|
||||
// Never replace an uploaded/cropped photo or a deliberate removal.
|
||||
const editingBird = [...birds, ...memorializedBirds].find((bird) => bird.id === editingBirdId);
|
||||
if (editingBird && urls.has(editingBirdId)) {
|
||||
setBirdForm((current) => current.photoDataUrl === editingBird.photoDataUrl
|
||||
? { ...current, photoDataUrl: urls.get(editingBirdId) ?? '' } : current);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const selectedBird = useMemo(
|
||||
() => flockBirds.find((bird) => bird.id === selectedBirdId) ?? null,
|
||||
[flockBirds, selectedBirdId],
|
||||
@@ -5698,7 +5720,7 @@ function App() {
|
||||
|
||||
if (shouldShowPublicProfilePage) {
|
||||
return (
|
||||
<main className="auth-shell public-profile-shell">
|
||||
<main className="auth-shell public-profile-shell" onErrorCapture={handlePhotoError}>
|
||||
<section className="panel public-profile-card">
|
||||
<a className="public-profile-logo-link" href="/" aria-label="Go to FlockPal sign in">
|
||||
<img className="public-profile-logo" src={flockPalLandingArt} alt="FlockPal" />
|
||||
@@ -5895,7 +5917,7 @@ function App() {
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<main className="app-shell">
|
||||
<main className="app-shell" onErrorCapture={handlePhotoError}>
|
||||
<section className="hero-card">
|
||||
<p>Loading flock data...</p>
|
||||
</section>
|
||||
@@ -6006,7 +6028,7 @@ function App() {
|
||||
);
|
||||
|
||||
return (
|
||||
<main className="app-shell">
|
||||
<main className="app-shell" onErrorCapture={handlePhotoError}>
|
||||
<div className="side-rail">
|
||||
<div className="brand-lockup">
|
||||
<img className="side-nav-logo" src={flockPalLandingArt} alt="FlockPal" />
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
export type PhotoRecord = { id: string; photoDataUrl: string | null };
|
||||
export const PHOTO_REFRESH_INTERVAL_MS = 5 * 60_000;
|
||||
|
||||
// One request for all mounted photos; throttle failures without blocking later recovery.
|
||||
export function createPhotoRefresher({ load, apply, now = Date.now }: {
|
||||
load: (signal: AbortSignal) => Promise<PhotoRecord[]>;
|
||||
apply: (photos: PhotoRecord[]) => void;
|
||||
now?: () => number;
|
||||
}) {
|
||||
const controller = new AbortController();
|
||||
let inFlight = false;
|
||||
let lastAttempt = -Infinity;
|
||||
return {
|
||||
async refresh() {
|
||||
if (controller.signal.aborted || inFlight || now() - lastAttempt < 30_000) return;
|
||||
inFlight = true;
|
||||
lastAttempt = now();
|
||||
try {
|
||||
const photos = await load(controller.signal);
|
||||
if (!controller.signal.aborted) apply(photos);
|
||||
} catch {
|
||||
// Keep existing photos on transient failures; retry on the next focus/timer/error.
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
},
|
||||
dispose() { controller.abort(); },
|
||||
};
|
||||
}
|
||||
|
||||
export function isExpiringPhotoUrl(src: string) {
|
||||
try {
|
||||
const url = new URL(src, window.location.href);
|
||||
return /\/birds\/[^/]+\/photo$/.test(url.pathname) && url.searchParams.has('token');
|
||||
} catch { return false; }
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useEffect, useRef, type SyntheticEvent } from 'react';
|
||||
import { createPhotoRefresher, isExpiringPhotoUrl, PHOTO_REFRESH_INTERVAL_MS, type PhotoRecord } from './photoRefresh';
|
||||
|
||||
export function usePhotoRefresh({ apiBaseUrl, token, workspaceId, publicProfileCode, onPhotos, fallback }: {
|
||||
apiBaseUrl: string; token: string; workspaceId?: number; publicProfileCode: string;
|
||||
onPhotos: (photos: PhotoRecord[]) => void; fallback: string;
|
||||
}) {
|
||||
const apply = useRef(onPhotos);
|
||||
apply.current = onPhotos;
|
||||
const refresh = useRef<(() => Promise<void>) | null>(null);
|
||||
useEffect(() => {
|
||||
if (!publicProfileCode && (!token || !workspaceId)) return;
|
||||
const refresher = createPhotoRefresher({
|
||||
load: async (signal) => {
|
||||
const path = publicProfileCode ? `/public/birds/${encodeURIComponent(publicProfileCode)}` : '/birds';
|
||||
const response = await fetch(`${apiBaseUrl}${path}`, {
|
||||
signal, cache: 'no-store',
|
||||
headers: publicProfileCode ? {} : { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!response.ok) throw new Error('Unable to refresh photos.');
|
||||
const data = await response.json();
|
||||
return publicProfileCode ? (data.bird ? [data.bird] : []) : [...(data.birds ?? []), ...(data.memorializedBirds ?? [])];
|
||||
},
|
||||
apply: (photos) => apply.current(photos),
|
||||
});
|
||||
refresh.current = refresher.refresh;
|
||||
const onResume = () => { if (document.visibilityState === 'visible') void refresher.refresh(); };
|
||||
const timer = window.setInterval(onResume, PHOTO_REFRESH_INTERVAL_MS);
|
||||
window.addEventListener('focus', onResume);
|
||||
window.addEventListener('online', onResume);
|
||||
document.addEventListener('visibilitychange', onResume);
|
||||
return () => {
|
||||
refresher.dispose();
|
||||
refresh.current = null;
|
||||
window.clearInterval(timer);
|
||||
window.removeEventListener('focus', onResume);
|
||||
window.removeEventListener('online', onResume);
|
||||
document.removeEventListener('visibilitychange', onResume);
|
||||
};
|
||||
}, [apiBaseUrl, token, workspaceId, publicProfileCode]);
|
||||
|
||||
return (event: SyntheticEvent) => {
|
||||
const image = event.target;
|
||||
if (!(image instanceof Element)) return;
|
||||
const attribute = image.localName === 'img' ? 'src' : image.localName === 'image' ? 'href' : null;
|
||||
if (!attribute || !isExpiringPhotoUrl(image.getAttribute(attribute) ?? '')) return;
|
||||
image.setAttribute(attribute, fallback);
|
||||
void refresh.current?.();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createPhotoRefresher } from '../src/photoRefresh.ts';
|
||||
|
||||
test('simultaneous image errors share a refresh, then can renew again after cooldown', async () => {
|
||||
let now = 0;
|
||||
let calls = 0;
|
||||
let finish!: (photos: { id: string; photoDataUrl: string }[]) => void;
|
||||
const applied: unknown[] = [];
|
||||
const refresher = createPhotoRefresher({
|
||||
now: () => now,
|
||||
load: async () => { calls++; return new Promise((resolve) => { finish = resolve; }); },
|
||||
apply: (photos) => applied.push(photos),
|
||||
});
|
||||
const first = refresher.refresh();
|
||||
await refresher.refresh();
|
||||
assert.equal(calls, 1);
|
||||
finish([{ id: 'bird', photoDataUrl: 'renewed' }]);
|
||||
await first;
|
||||
assert.equal(applied.length, 1);
|
||||
await refresher.refresh();
|
||||
assert.equal(calls, 1);
|
||||
now = 30_000;
|
||||
const next = refresher.refresh();
|
||||
finish([]);
|
||||
await next;
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test('logout or flock switching aborts requests and discards stale photo responses', async () => {
|
||||
let finish!: (photos: { id: string; photoDataUrl: string }[]) => void;
|
||||
let signal!: AbortSignal;
|
||||
let applied = false;
|
||||
const refresher = createPhotoRefresher({
|
||||
load: async (requestSignal) => { signal = requestSignal; return new Promise((resolve) => { finish = resolve; }); },
|
||||
apply: () => { applied = true; },
|
||||
});
|
||||
const pending = refresher.refresh();
|
||||
refresher.dispose();
|
||||
finish([{ id: 'old-flock-bird', photoDataUrl: 'stale' }]);
|
||||
await pending;
|
||||
assert.equal(signal.aborted, true);
|
||||
assert.equal(applied, false);
|
||||
});
|
||||
|
||||
test('a failed refresh can recover on a later timer, focus, or reconnect', async () => {
|
||||
let now = 0;
|
||||
let attempts = 0;
|
||||
let applied = false;
|
||||
const refresher = createPhotoRefresher({
|
||||
now: () => now,
|
||||
load: async () => { if (++attempts === 1) throw new Error('offline'); return []; },
|
||||
apply: () => { applied = true; },
|
||||
});
|
||||
await refresher.refresh();
|
||||
assert.equal(applied, false);
|
||||
now = 30_000;
|
||||
await refresher.refresh();
|
||||
assert.equal(applied, true);
|
||||
});
|
||||
Reference in new issue
Block a user