Skip to content

Commit 07a7f10

Browse files
committed
feat: add usePWAUpdate composable and hook up in main.ts
- Add usePWAUpdate composable (singleton SW registration, periodic update checks, autoUpdate support) - Call usePWAUpdate({ autoUpdate: true }) in main.ts - Import style.css as JS side-effect in main.ts Assisted-by: Zed:claude-sonnet-4-6
1 parent 09e64bf commit 07a7f10

2 files changed

Lines changed: 59 additions & 0 deletions

File tree

src/composables/usePWAUpdate.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { registerSW } from "virtual:pwa-register";
2+
import { ref } from "vue";
3+
4+
interface UsePWAUpdateOptions {
5+
/** Whether to automatically reload the app when a new version is detected. @default false */
6+
autoUpdate?: boolean;
7+
/** Interval in seconds to check for updates. Set to 0 to disable. @default 86400 (24 hours) */
8+
updateInterval?: number;
9+
}
10+
11+
// Singleton state — shared across all callers
12+
const needRefresh = ref(false);
13+
const offlineReady = ref(false);
14+
let updateSW: ((reloadPage?: boolean) => Promise<void>) | undefined;
15+
let registered = false;
16+
let intervalId: ReturnType<typeof setInterval> | undefined;
17+
18+
export function usePWAUpdate(options: UsePWAUpdateOptions = {}) {
19+
const { autoUpdate = false, updateInterval = 60 * 60 * 24 } = options;
20+
21+
const updateApp = async () => {
22+
if (updateSW) {
23+
try {
24+
await updateSW(true);
25+
needRefresh.value = false;
26+
} catch (error) {
27+
console.error("PWA: Failed to update app:", error);
28+
}
29+
}
30+
};
31+
32+
if (!registered) {
33+
registered = true;
34+
updateSW = registerSW({
35+
immediate: true,
36+
onNeedRefresh() {
37+
needRefresh.value = true;
38+
if (autoUpdate) updateApp();
39+
},
40+
onOfflineReady() {
41+
offlineReady.value = true;
42+
},
43+
onRegistered(registration) {
44+
if (registration && updateInterval > 0 && !intervalId) {
45+
intervalId = setInterval(() => registration.update(), updateInterval * 1000);
46+
}
47+
},
48+
onRegisterError(error) {
49+
console.error("PWA: Service worker registration error:", error);
50+
},
51+
});
52+
}
53+
54+
return { needRefresh, offlineReady, updateApp };
55+
}

src/main.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
import { createApp } from "vue";
22

3+
import "./style.css";
34
import App from "./App.vue";
5+
import { usePWAUpdate } from "./composables/usePWAUpdate";
46
import { setupECharts } from "./echartsSetup";
57
import { router } from "./router";
68

9+
usePWAUpdate({ autoUpdate: true });
10+
711
setupECharts();
812

913
createApp(App).use(router).mount("#app");

0 commit comments

Comments
 (0)