Files
openchamber/packages/ui/src/hooks/usePwaInstallPrompt.ts
T
Tom RochetteandBohdan Triapitsyn 1505274f94 perf(stores): defer safeStorage writes off the interaction path (#1941)
* perf(stores): defer safeStorage writes off the interaction path

Session switches funnel every persisted store slice through safeStorage.setItem,
and doing those large JSON.stringify writes synchronously blocked the main
thread for over a second. Add a write-behind buffer that:

- Defers each setItem/removeItem to a later task via setTimeout(0) so the
  click-to-paint path is not blocked.
- Coalesces repeated writes to the same key into a single backing flush.
- Serves pending values from memory so read-after-write stays consistent
  within the deferral window.
- Flushes synchronously on pagehide/beforeunload/visibilitychange/freeze so
  deferred state survives tab close, reload, and the mobile freeze lifecycle.

Adds a test covering write deferral, coalescing, and pending read serving.

* fix(stores): defer persisted JSON serialization

* fix(stores): defer direct safeStorage writes

---------

Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
2026-06-30 11:47:52 +03:00

116 lines
3.5 KiB
TypeScript

import React from 'react';
import { toast } from '@/components/ui';
import { isWebRuntime } from '@/lib/desktop';
import { usePwaDetection } from '@/hooks/usePwaDetection';
import { useI18n } from '@/lib/i18n';
import { getDeferredSafeStorage, getSafeSessionStorage } from '@/stores/utils/safeStorage';
import { shouldShowPwaInstallToast } from '@/components/update/openCodeUpdateDedup';
type InstallPromptOutcome = 'accepted' | 'dismissed';
type BeforeInstallPromptEvent = Event & {
prompt: () => Promise<void>;
userChoice: Promise<{ outcome: InstallPromptOutcome }>;
};
const INSTALL_TOAST_SESSION_KEY = 'pwa-install-toast-shown';
const INSTALL_TOAST_DISMISSED_KEY = 'pwa-install-toast-dismissed';
export const usePwaInstallPrompt = () => {
const { browserTab } = usePwaDetection();
const { t } = useI18n();
const tRef = React.useRef(t);
React.useEffect(() => {
tRef.current = t;
}, [t]);
React.useEffect(() => {
if (typeof window === 'undefined' || !isWebRuntime() || !browserTab) {
return;
}
let deferredPrompt: BeforeInstallPromptEvent | null = null;
let installToastId: string | number | null = null;
const dismissInstallToast = () => {
if (installToastId === null) {
return;
}
toast.dismiss(installToastId);
installToastId = null;
};
const triggerInstall = async () => {
if (!deferredPrompt) {
return;
}
const promptEvent = deferredPrompt;
deferredPrompt = null;
dismissInstallToast();
await promptEvent.prompt();
const { outcome } = await promptEvent.userChoice;
if (outcome === 'accepted') {
toast.success(tRef.current('pwa.installPrompt.started'));
}
};
const onBeforeInstallPrompt = (event: Event) => {
const installEvent = event as BeforeInstallPromptEvent;
if (typeof installEvent.prompt !== 'function') {
return;
}
installEvent.preventDefault();
deferredPrompt = installEvent;
const localStorage = getDeferredSafeStorage();
const sessionStorage = getSafeSessionStorage();
const decision = shouldShowPwaInstallToast({
dismissed: localStorage.getItem(INSTALL_TOAST_DISMISSED_KEY),
sessionShown: sessionStorage.getItem(INSTALL_TOAST_SESSION_KEY),
hasActiveToast: installToastId !== null,
});
if (!decision) {
return;
}
sessionStorage.setItem(INSTALL_TOAST_SESSION_KEY, 'true');
installToastId = toast.info(tRef.current('pwa.installPrompt.description'), {
duration: Infinity,
action: {
label: tRef.current('pwa.installPrompt.action'),
onClick: () => {
void triggerInstall();
},
},
cancel: {
label: tRef.current('pwa.installPrompt.dismiss'),
onClick: () => {
getDeferredSafeStorage().setItem(INSTALL_TOAST_DISMISSED_KEY, 'true');
dismissInstallToast();
},
},
});
};
const onAppInstalled = () => {
deferredPrompt = null;
dismissInstallToast();
toast.success(tRef.current('pwa.installPrompt.installed'));
};
window.addEventListener('beforeinstallprompt', onBeforeInstallPrompt as EventListener);
window.addEventListener('appinstalled', onAppInstalled);
return () => {
dismissInstallToast();
window.removeEventListener('beforeinstallprompt', onBeforeInstallPrompt as EventListener);
window.removeEventListener('appinstalled', onAppInstalled);
};
}, [browserTab]);
};