storebound/apps/desktop/src/store.tsx

234 lines
12 KiB
TypeScript

// App data shared by every screen: app folders, accounts, the sidecar, the portfolio (offline check + the last live
// read from the cache), app icons, and background jobs shown as toasts with progress and cancel.
import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import {
type Account, api, type AppInfo, type AppStatus, type CacheEntry, errorText, newJob, onDownload, onProgress, type PortfolioResult, type Project, reads,
type SidecarStatus, type ToolResult,
} from './api';
import { t } from './i18n';
export type ToastKind = 'job' | 'ok' | 'bad' | 'info';
export interface Toast {
id: string;
kind: ToastKind;
title: string;
detail?: string;
/** null: running without a known total. */
progress?: { done: number; total: number } | null;
/** Cancellable job id. */
job?: string;
}
export interface Data {
ready: boolean;
info: AppInfo | null;
projects: Project[];
accounts: Account[];
sidecar: SidecarStatus | null;
sidecarError: string | null;
/** Latest portfolio read (offline check, or live when just read). */
portfolio: PortfolioResult | null;
/** Last live read of the stores (cached across runs). */
live: CacheEntry<PortfolioResult> | null;
portfolioBusy: 'offline' | 'live' | null;
portfolioError: string | null;
icons: Record<string, string | null>;
refreshPortfolio: (live?: boolean) => Promise<void>;
reload: () => Promise<void>;
statusOf: (p: Project) => AppStatus | undefined;
liveOf: (p: Project) => AppStatus | undefined;
toasts: Toast[];
toast: (t: Omit<Toast, 'id'> & { id?: string }) => string;
updateToast: (id: string, patch: Partial<Toast>) => void;
dismiss: (id: string) => void;
cancelJob: (job: string) => void;
}
const Ctx = createContext<Data | null>(null);
export const useData = (): Data => {
const d = useContext(Ctx);
if (!d) throw new Error('useData outside DataProvider');
return d;
};
const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^\S+ \[[^\]]+\] /, '') ?? '';
export function DataProvider({ children }: { children: ReactNode }) {
const [ready, setReady] = useState(false);
const [info, setInfo] = useState<AppInfo | null>(null);
const [projects, setProjects] = useState<Project[]>([]);
const [accounts, setAccounts] = useState<Account[]>([]);
const [sidecar, setSidecar] = useState<SidecarStatus | null>(null);
const [sidecarError, setSidecarError] = useState<string | null>(null);
const [portfolio, setPortfolio] = useState<PortfolioResult | null>(null);
const [live, setLive] = useState<CacheEntry<PortfolioResult> | null>(null);
const [portfolioBusy, setBusy] = useState<Data['portfolioBusy']>(null);
const [portfolioError, setPortfolioError] = useState<string | null>(null);
const [icons, setIcons] = useState<Record<string, string | null>>({});
const [toasts, setToasts] = useState<Toast[]>([]);
const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
const dismiss = useCallback((id: string) => {
setToasts(ts => ts.filter(x => x.id !== id));
const tm = timers.current.get(id);
if (tm) { clearTimeout(tm); timers.current.delete(id); }
}, []);
const autoClose = useCallback((id: string, kind: ToastKind) => {
if (kind === 'job') return;
const old = timers.current.get(id);
if (old) clearTimeout(old);
timers.current.set(id, setTimeout(() => dismiss(id), kind === 'bad' ? 9000 : 4500));
}, [dismiss]);
const toast = useCallback((x: Omit<Toast, 'id'> & { id?: string }) => {
const id = x.id ?? newJob('toast');
setToasts(ts => [...ts.filter(o => o.id !== id), { ...x, id }].slice(-4));
autoClose(id, x.kind);
return id;
}, [autoClose]);
const updateToast = useCallback((id: string, patch: Partial<Toast>) => {
setToasts(ts => ts.map(x => (x.id === id ? { ...x, ...patch } : x)));
if (patch.kind) autoClose(id, patch.kind);
}, [autoClose]);
const cancelJob = useCallback((job: string) => { api.cancel(job).catch(() => {}); }, []);
const reload = useCallback(async () => {
const [p, a] = await Promise.all([api.projects(), api.accounts()]);
setProjects(p);
setAccounts(a);
}, []);
const refreshPortfolio = useCallback(async (liveRead = false) => {
const job = newJob(liveRead ? 'portfolio-live' : 'portfolio');
setBusy(liveRead ? 'live' : 'offline'); setPortfolioError(null);
const tid = liveRead ? toast({ id: job, kind: 'job', title: t('toast.readingStores'), detail: t('toast.readingStoresDetail'), progress: null, job }) : null;
try {
const r = await api.portfolio(liveRead, job);
setPortfolio(r);
if (liveRead) {
setLive({ value: r, at: r.at });
const failed = r.apps.filter(a => a.storeErrors.ios || a.storeErrors.android).length;
if (tid) updateToast(tid, failed ? { kind: 'info', title: t('toast.readDonePartial'), detail: t('toast.readDonePartialDetail', { count: failed }), progress: undefined, job: undefined }
: { kind: 'ok', title: t('toast.readDone'), detail: t('toast.readDoneDetail', { count: r.apps.length }), progress: undefined, job: undefined });
}
} catch (e) {
const msg = errorText(e);
setPortfolioError(msg);
if (tid) updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailed'), detail: msg, progress: undefined, job: undefined });
} finally { setBusy(null); }
}, [toast, updateToast]);
// start: app info, folders, accounts, sidecar, cached live portfolio
useEffect(() => {
api.appInfo().then(setInfo, () => {});
reload().catch(() => {}).finally(() => setReady(true));
api.sidecarStatus().then(s => { setSidecar(s); setSidecarError(null); }, e => setSidecarError(errorText(e)));
api.cached<PortfolioResult>('portfolio.status', '*', { live: true }).then(e => { if (e) setLive(e); }, () => {});
}, [reload]);
useEffect(() => { if (projects.length) refreshPortfolio(false); }, [projects.length, refreshPortfolio]);
// icons: cached first, then read (offline, cheap)
useEffect(() => {
for (const p of projects) {
if (p.id in icons) continue;
setIcons(m => ({ ...m, [p.id]: null }));
api.cached<ToolResult & { data?: { dataUrl: string | null } }>('project.icon', p.id).then(c => {
if (c?.value.data?.dataUrl) setIcons(m => ({ ...m, [p.id]: c.value.data!.dataUrl }));
}, () => {}).finally(() => {
reads.icon(p.id).then(r => setIcons(m => ({ ...m, [p.id]: r.data?.dataUrl ?? m[p.id] ?? null })), () => {});
});
}
}, [projects]); // eslint-disable-line react-hooks/exhaustive-deps
// progress of jobs -> their toasts
useEffect(() => {
const un = onProgress(p => {
if (!p.job) return;
setToasts(ts => ts.map(x => {
if (x.job !== p.job) return x;
if (p.total) return { ...x, progress: { done: p.n ?? 0, total: p.total } };
if (p.line) return { ...x, detail: lastLine(p.line) || x.detail };
return x;
}));
});
const unD = onDownload(e => {
setToasts(ts => ts.map(x => (x.job === e.job && e.stage !== 'done' && e.stage !== 'error' && e.stage !== 'cancelled'
? { ...x, detail: t(`dl.${e.stage}`), progress: e.total ? { done: e.received, total: e.total } : null } : x)));
});
return () => { un.then(f => f()); unD.then(f => f()); };
}, []);
const statusOf = useCallback((p: Project) => portfolio?.apps.find(a => a.project === p.path || a.app?.id === p.path), [portfolio]);
const liveOf = useCallback((p: Project) => {
const cur = portfolio?.apps.find(a => (a.project === p.path || a.app?.id === p.path) && a.release.source === 'live');
return cur ?? live?.value.apps.find(a => a.project === p.path || a.app?.id === p.path);
}, [portfolio, live]);
const value = useMemo<Data>(() => ({
ready, info, projects, accounts, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, icons,
refreshPortfolio, reload, statusOf, liveOf, toasts, toast, updateToast, dismiss, cancelJob,
}), [ready, info, projects, accounts, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, icons, refreshPortfolio, reload, statusOf, liveOf, toasts, toast, updateToast, dismiss, cancelJob]);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}
export interface ReadState<T> {
data: T | null;
/** When `data` was read (from the store or the cache). */
at: string | null;
fromCache: boolean;
loading: boolean;
error: string | null;
/** The command line it ran (shown with errors). */
command: string | null;
refresh: () => Promise<void>;
}
/**
* One read method of one app. The cached value shows at once with its time; offline reads (`network: false`) then
* refresh by themselves, store reads only on demand (they use the account's API quota). A failed read keeps the last
* good value and says so: never an empty "all fine".
*/
export function useRead<T>(projectId: string, method: string, o: { network: boolean; args?: Record<string, unknown>; title?: string }): ReadState<T> {
const d = useData();
const argsKey = JSON.stringify(o.args ?? {});
const [s, set] = useState<Omit<ReadState<T>, 'refresh'>>({ data: null, at: null, fromCache: false, loading: true, error: null, command: null });
const seq = useRef(0);
const refresh = useCallback(async () => {
const my = ++seq.current;
const job = newJob(method);
set(x => ({ ...x, loading: true, error: null }));
const tid = o.network ? d.toast({ id: job, kind: 'job', title: o.title ?? t('toast.reading'), detail: t('toast.readingDetail'), progress: null, job }) : null;
try {
const r = await api.call<ToolResult>(method, projectId, { args: JSON.parse(argsKey) as Record<string, unknown> }, job);
if (my !== seq.current) return;
if (r.ok && r.data !== undefined) {
set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, error: null, command: r.command });
if (tid) d.updateToast(tid, { kind: 'ok', title: t('toast.readOk', { what: o.title ?? method }), detail: undefined, progress: undefined, job: undefined });
} else {
const msg = lastLine(r.output) || t('common.exit', { code: r.exitCode });
set(x => ({ ...x, loading: false, error: msg, command: r.command }));
if (tid) d.updateToast(tid, { kind: 'bad', title: t('toast.readFailedWhat', { what: o.title ?? method }), detail: msg, progress: undefined, job: undefined });
}
} catch (e) {
if (my !== seq.current) return;
const msg = errorText(e);
set(x => ({ ...x, loading: false, error: msg }));
if (tid) d.updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailedWhat', { what: o.title ?? method }), detail: msg, progress: undefined, job: undefined });
}
}, [projectId, method, argsKey, o.network, o.title]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
let alive = true;
set({ data: null, at: null, fromCache: false, loading: true, error: null, command: null });
api.cached<ToolResult>(method, projectId, JSON.parse(argsKey) as Record<string, unknown>).then(c => {
if (!alive) return;
if (c && c.value.data !== undefined) set({ data: c.value.data as T, at: c.at, fromCache: true, loading: !o.network, error: null, command: c.value.command });
else set(x => ({ ...x, loading: !o.network }));
if (!o.network) refresh();
}, () => { if (alive) { set(x => ({ ...x, loading: !o.network })); if (!o.network) refresh(); } });
return () => { alive = false; };
}, [projectId, method, argsKey]); // eslint-disable-line react-hooks/exhaustive-deps
return { ...s, refresh };
}