diff --git a/src/composable/cloud-sync.ts b/src/composable/cloud-sync.ts index 6d871ca..cb384a1 100644 --- a/src/composable/cloud-sync.ts +++ b/src/composable/cloud-sync.ts @@ -88,6 +88,70 @@ function mergeData(server: Record, mine: Record): Reco return out; } +// ================= 自动上传:同步键数据一变化就推到云端 ================= +let autoPending: ReturnType | undefined; +let autoBusy = false; + +function shouldAutoSync(k: string): boolean { + return SYNC_KEYS.includes(k) || k.startsWith('gen-history:'); +} + +/** push-only sync: merge local into server WITHOUT writing back (protects the fresh local value) */ +async function pushUpOnly() { + if (autoBusy) { + scheduleAutoSync(); // busy -> retry after + return; + } + autoBusy = true; + try { + const mine = collectLocal(); + const { status, body } = await apiFetch('/user/data'); + if (status !== 200) { + return; + } + const server = body.data?.data ?? {}; + const merged = mergeData(server, mine); + await apiFetch('/user/data', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ data: merged }), + }); + } + catch { /* offline etc. */ } + finally { + autoBusy = false; + } +} + +function scheduleAutoSync() { + if (autoPending) { + clearTimeout(autoPending); + } + autoPending = setTimeout(() => { + if (useUserAuth().isLoggedIn.value) { + pushUpOnly().catch(() => {}); + } + }, 3000); +} + +// wrap localStorage so any write to a synced key schedules an upload +if (typeof localStorage !== 'undefined') { + const origSet = localStorage.setItem.bind(localStorage); + const origRemove = localStorage.removeItem.bind(localStorage); + localStorage.setItem = (k: string, v: string) => { + origSet(k, v); + if (shouldAutoSync(k)) { + scheduleAutoSync(); + } + }; + localStorage.removeItem = (k: string) => { + origRemove(k); + if (shouldAutoSync(k)) { + scheduleAutoSync(); + } + }; +} + export function useCloudSync() { const { isLoggedIn } = useUserAuth();