From 827547e622f833d6341b72364f48eacbfed3c4a3 Mon Sep 17 00:00:00 2001 From: personal82555 Date: Mon, 12 Oct 2026 10:23:05 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BA=91=E5=90=8C=E6=AD=A5=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E5=AE=9E=E6=97=B6=E8=87=AA=E5=8A=A8=E4=B8=8A=E4=BC=A0?= =?UTF-8?q?=20=E2=80=94=20=E6=94=B6=E8=97=8F/=E6=9C=80=E8=BF=91=E4=BD=BF?= =?UTF-8?q?=E7=94=A8/=E7=BD=91=E7=AB=99=E6=94=B6=E8=97=8F/=E7=94=9F?= =?UTF-8?q?=E6=88=90=E8=AE=B0=E5=BD=95=E4=B8=80=E5=8F=98=E5=8C=963?= =?UTF-8?q?=E7=A7=92=E5=86=85=E8=87=AA=E5=8A=A8=E6=8E=A8=E9=80=81=E4=BA=91?= =?UTF-8?q?=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/composable/cloud-sync.ts | 64 ++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) 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();