Something went wrong. Try again.
A social knowledge tool for research trails, built on ATProto semble.so
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import { focusManager } from '@tanstack/react-query';import { atom } from 'tldraw';import { combineOutcomes, type FetchOutcome } from './linkCards';
// Until a batch endpoint exists (#982), timed refreshes are this far apart and// fetch only the links in viewconst TIMED_REFRESH_MS = 600_000;const FAILURES_BEFORE_SHOWN = 2;
function runEvery(callback: () => void, ms: number) { const timer = setInterval(callback, ms); return () => clearInterval(timer);}
// Forced refreshes skip the minute links and frames otherwise stay fresh forexport interface RefreshOptions { force?: boolean; inView?: boolean;}
export interface RefreshLoopDeps { connectionUrls(): string[]; urlsInView(): string[]; fetchLinks( urls: string[], options: { force?: boolean }, ): Promise<FetchOutcome>; // Puts collection frames back to their collections' first pages refreshFrames(options: RefreshOptions): Promise<FetchOutcome>; // Runs the timed refresh every so often; setInterval unless given everyTimedRefresh?(refresh: () => void, ms: number): () => void;}
// Refreshes the board's links and collection frames on open, when the tab is// shown again (at most once a minute) and on a timer while it's visibleexport function attachRefreshLoop(deps: RefreshLoopDeps) { const failed = atom('refresh failed', false); let failuresInARow = 0;
async function refresh(urls: string[], options: RefreshOptions = {}) { const outcome = combineOutcomes( await Promise.all([ urls.length > 0 ? deps.fetchLinks(urls, options) : 'nothing-fetched', deps.refreshFrames(options), ]), ); if (outcome === 'nothing-fetched') return; failuresInARow = outcome === 'fetched' ? 0 : failuresInARow + 1; failed.set(failuresInARow >= FAILURES_BEFORE_SHOWN); }
const everyTimedRefresh = deps.everyTimedRefresh ?? runEvery; let unsubscribe = () => {}; let stopTimer = () => {};
return { failed, // Once the board has loaded start() { // What the board last saved may be from before a change made elsewhere void refresh(deps.connectionUrls(), { force: true }); unsubscribe = focusManager.subscribe((focused) => { if (focused) void refresh(deps.connectionUrls()); }); stopTimer = everyTimedRefresh(() => { if (focusManager.isFocused()) void refresh(deps.urlsInView(), { force: true, inView: true }); }, TIMED_REFRESH_MS); }, detach() { unsubscribe(); stopTimer(); }, };}