UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

106 lines (104 loc) • 4.37 kB
import { OFFLINE_CACHE, OFFLINE_DATA_CACHE, OFFLINE_MESSAGE, OFFLINE_OWNER_KEY, OFFLINE_SAVE_HEADER, OFFLINE_SKIPPED_PREFIXES, WORKER_PATH } from "./service-worker.js"; import { useCurrentUser } from "./auth/isomorphic.js"; import { useEffect, useState, useSyncExternalStore } from "react"; import { useLocation } from "@tanstack/react-router"; //#region src/offline.ts const PAGE_MAX_AGE_MS = 30 * 6e4; /** * Lets the published app open without internet and show the pages and data * the visitor loaded, read only. Saves made offline fail as usual. * * Call it once, in the root route's `RootDocument`. The saved copies are * deleted when another visitor signs in on this browser, or when the visitor * signs out. In the Studio preview it only reports `online`. * * @example * function OfflineBanner() { * const { online } = useOfflineMode() * if (online) return null * return <div role="status">You're offline. Showing the last saved data.</div> * } */ function useOfflineMode(options = {}) { const enabled = options.enabled ?? true; const userId = useCurrentUser()?.id ?? null; const pathname = useLocation({ select: (location$1) => location$1.pathname }); const connected = useSyncExternalStore(subscribeToConnection, () => navigator.onLine, () => true); const [showingCopies, setShowingCopies] = useState(false); useEffect(() => { if (!("serviceWorker" in navigator)) return; const onMessage = (event) => { const data = event.data; if (typeof data !== "object" || data === null || !("type" in data) || data.type !== OFFLINE_MESSAGE) return; setShowingCopies("showingCopies" in data && data.showingCopies === true); }; const onOnline = () => { setShowingCopies(false); navigator.serviceWorker.controller?.postMessage({ type: OFFLINE_MESSAGE, online: true }); }; navigator.serviceWorker.addEventListener("message", onMessage); window.addEventListener("online", onOnline); navigator.serviceWorker.controller?.postMessage({ type: OFFLINE_MESSAGE }); return () => { navigator.serviceWorker.removeEventListener("message", onMessage); window.removeEventListener("online", onOnline); }; }, []); useEffect(() => { if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator) || !("caches" in window)) return; if (!enabled) { deleteCopies().catch(() => {}); return; } if (!connected || showingCopies) return; (async () => { const owner = userId ?? ""; const stored = await (await caches.open(OFFLINE_CACHE)).match(OFFLINE_OWNER_KEY); if (stored === void 0 || await stored.text() !== owner) { await deleteCopies(); await (await caches.open(OFFLINE_CACHE)).put(OFFLINE_OWNER_KEY, new Response(owner)); } await navigator.serviceWorker.register(WORKER_PATH, { scope: "/" }); const cache = await caches.open(OFFLINE_CACHE); const save = (url) => cache.add(new Request(url, { headers: { [OFFLINE_SAVE_HEADER]: "1" } })); const page = await cache.match(pathname); const savedAt = Date.parse(page?.headers.get("date") ?? ""); if (!(Date.now() - savedAt < PAGE_MAX_AGE_MS)) await save(pathname).catch(() => {}); const files = []; for (const entry of performance.getEntriesByType("resource")) { if (!(entry instanceof PerformanceResourceTiming)) continue; if (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest") continue; const url = new URL(entry.name); if (url.origin !== location.origin) continue; if (OFFLINE_SKIPPED_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))) continue; files.push(url.href); } await Promise.all(files.map(async (url) => { if (await cache.match(url) === void 0) await save(url).catch(() => {}); })); })().catch((error) => console.warn("[@softr/sdk] Offline mode could not save this page:", error)); }, [ enabled, userId, pathname, connected, showingCopies ]); return { online: connected && !showingCopies }; } async function deleteCopies() { await Promise.all([caches.delete(OFFLINE_CACHE), caches.delete(OFFLINE_DATA_CACHE)]); } function subscribeToConnection(onChange) { window.addEventListener("online", onChange); window.addEventListener("offline", onChange); return () => { window.removeEventListener("online", onChange); window.removeEventListener("offline", onChange); }; } //#endregion export { useOfflineMode };