mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 10:44:23 +00:00
feat(offline): force-offline mode, selective sync and a conflict queue
A force-offline override routes every read to the cache and every write to the queue; preparing for offline downloads trip data, documents and map tiles up front and waits for them to finish. Map tiles and individual trips can be left out of the cache. Queued edits carry the version they were based on so the queue can surface server conflicts for a keep-mine / keep-theirs decision; chained offline edits to one entity no longer conflict with each other, and evicting a trip preserves its unsynced writes.
This commit is contained in:
@@ -8,6 +8,8 @@
|
||||
import { offlineDb } from '../db/offlineDb'
|
||||
import { apiClient } from '../api/client'
|
||||
import { isAuthed } from './authGate'
|
||||
import { isEffectivelyOffline } from './networkMode'
|
||||
import { getOfflinePrefs } from './offlinePrefs'
|
||||
import type { QueuedMutation } from '../db/offlineDb'
|
||||
import type { Table } from 'dexie'
|
||||
|
||||
@@ -62,6 +64,22 @@ function isRetryableStatus(status: number | undefined): boolean {
|
||||
return status === 401 || status === 408 || status === 425 || status === 429
|
||||
}
|
||||
|
||||
/** Pull the server's current entity out of a 409 response body ({ server: {...} }). */
|
||||
function extractConflictServer(err: unknown): unknown {
|
||||
const data = (err as { response?: { data?: unknown } })?.response?.data
|
||||
if (data && typeof data === 'object' && 'server' in data) {
|
||||
return (data as { server: unknown }).server
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Write a server entity into its Dexie table (used when "theirs" wins a conflict). */
|
||||
async function applyServerEntity(mutation: QueuedMutation, server: unknown): Promise<void> {
|
||||
if (!mutation.resource || !server || typeof server !== 'object' || !('id' in server)) return
|
||||
const table = getTable(mutation.resource)
|
||||
if (table) await table.put(server)
|
||||
}
|
||||
|
||||
export const mutationQueue = {
|
||||
/**
|
||||
* Add a mutation to the queue.
|
||||
@@ -89,12 +107,19 @@ export const mutationQueue = {
|
||||
* 4xx responses are marked failed and skipped.
|
||||
*/
|
||||
async flush(): Promise<void> {
|
||||
if (_flushing || !navigator.onLine || !isAuthed()) return
|
||||
if (_flushing || isEffectivelyOffline() || !isAuthed()) return
|
||||
_flushing = true
|
||||
// tempId → realId learned during this flush, so a dependent edit/delete
|
||||
// queued against an offline-created entity (still holding the negative id)
|
||||
// can be rewritten to the server id before it is replayed.
|
||||
const idMap = new Map<number, number>()
|
||||
// resource:entityId → freshest updated_at applied during this flush. A second
|
||||
// queued edit of the same entity must send THIS token, not the stale one its
|
||||
// snapshot was loaded with, or it would 409 against our own first edit (#1135).
|
||||
const tokenMap = new Map<string, string>()
|
||||
// Set when a conflict auto-resolved as "mine wins": the mutation is re-queued
|
||||
// without its base token, so one more pass overwrites the server cleanly.
|
||||
let needsRetry = false
|
||||
try {
|
||||
const pending = await offlineDb.mutationQueue
|
||||
.where('status')
|
||||
@@ -128,11 +153,20 @@ export const mutationQueue = {
|
||||
}
|
||||
|
||||
try {
|
||||
// Send the optimistic-concurrency token when we have one so the server
|
||||
// can reject a stale overwrite (409). Absent header => unconditional
|
||||
// write (back-compat with servers / resources that don't check it).
|
||||
// A newer token learned earlier in THIS flush (an earlier edit of the
|
||||
// same entity) overrides the snapshot's stale base.
|
||||
const headers: Record<string, string> = { 'X-Idempotency-Key': mutation.id }
|
||||
const tokenKey = mutation.resource !== undefined && reqEntityId !== undefined ? `${mutation.resource}:${reqEntityId}` : undefined
|
||||
const baseToken = (tokenKey && tokenMap.get(tokenKey)) || mutation.baseUpdatedAt
|
||||
if (baseToken) headers['X-Base-Updated-At'] = baseToken
|
||||
const response = await apiClient.request({
|
||||
method: mutation.method,
|
||||
url: reqUrl,
|
||||
data: mutation.body,
|
||||
headers: { 'X-Idempotency-Key': mutation.id },
|
||||
headers,
|
||||
})
|
||||
|
||||
// Apply canonical server response to Dexie
|
||||
@@ -161,6 +195,29 @@ export const mutationQueue = {
|
||||
})
|
||||
}
|
||||
await table.put(entity)
|
||||
// Advance the base-version token of any other queued edits to the
|
||||
// same entity to the value we just wrote. Without this, a second
|
||||
// offline edit of the same place/item still carries the pre-flush
|
||||
// token and would 409 against our OWN just-applied first edit —
|
||||
// self-conflicting and risking loss of the later edit (#1135).
|
||||
const newToken = (entity as { updated_at?: unknown }).updated_at
|
||||
if (typeof newToken === 'string') {
|
||||
// In-memory: consulted when the sibling is replayed later in this
|
||||
// same flush (its snapshot still holds the stale base).
|
||||
if (mutation.resource) tokenMap.set(`${mutation.resource}:${realId}`, newToken)
|
||||
// Durable: survives a flush boundary / reload if the sibling is
|
||||
// not reached this pass.
|
||||
await offlineDb.mutationQueue
|
||||
.where('tripId')
|
||||
.equals(mutation.tripId)
|
||||
.filter(m =>
|
||||
m.id !== mutation.id &&
|
||||
m.resource === mutation.resource &&
|
||||
m.entityId === realId &&
|
||||
(m.status === 'pending' || m.status === 'syncing'),
|
||||
)
|
||||
.modify(m => { m.baseUpdatedAt = newToken })
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (mutation.method === 'DELETE' && mutation.resource && reqEntityId !== undefined) {
|
||||
@@ -172,6 +229,37 @@ export const mutationQueue = {
|
||||
await offlineDb.mutationQueue.delete(mutation.id)
|
||||
} catch (err: unknown) {
|
||||
const httpStatus = (err as { response?: { status: number } })?.response?.status
|
||||
|
||||
// 409 = the entity changed on the server since this offline edit was
|
||||
// made. This is NOT a dropped change like other 4xx — resolve it per
|
||||
// the user's strategy instead of failing it. Deliberately scoped to
|
||||
// edits: an offline DELETE is "delete wins" by design (no CAS on the
|
||||
// delete path), so it never reaches here. See the wiki Offline doc.
|
||||
if (httpStatus === 409 && mutation.method !== 'DELETE') {
|
||||
const server = extractConflictServer(err)
|
||||
const strategy = getOfflinePrefs().conflictStrategy
|
||||
if (strategy === 'server') {
|
||||
// Theirs wins: adopt the server's version locally, drop our write.
|
||||
await applyServerEntity(mutation, server)
|
||||
await offlineDb.mutationQueue.delete(mutation.id)
|
||||
} else if (strategy === 'mine') {
|
||||
// Mine wins: re-queue without the base token so the next pass
|
||||
// overwrites unconditionally.
|
||||
await offlineDb.mutationQueue.update(mutation.id, {
|
||||
status: 'pending', baseUpdatedAt: null, conflictServer: undefined,
|
||||
attempts: mutation.attempts + 1, lastError: null,
|
||||
})
|
||||
needsRetry = true
|
||||
} else {
|
||||
// Ask: park it as a conflict for the user to resolve.
|
||||
await offlineDb.mutationQueue.update(mutation.id, {
|
||||
status: 'conflict', conflictServer: server ?? null, conflictAt: Date.now(),
|
||||
attempts: mutation.attempts + 1, lastError: 'conflict',
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const isTerminal =
|
||||
httpStatus !== undefined && httpStatus >= 400 && httpStatus < 500 && !isRetryableStatus(httpStatus)
|
||||
if (isTerminal) {
|
||||
@@ -200,6 +288,12 @@ export const mutationQueue = {
|
||||
} finally {
|
||||
_flushing = false
|
||||
}
|
||||
// A "mine wins" auto-resolution dropped its base token; one more pass now
|
||||
// overwrites the server unconditionally. Bounded: the retried write carries
|
||||
// no token, so it cannot 409 for the same reason.
|
||||
if (needsRetry && !isEffectivelyOffline()) {
|
||||
await this.flush()
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -237,6 +331,45 @@ export const mutationQueue = {
|
||||
.count()
|
||||
},
|
||||
|
||||
/** Count unresolved sync conflicts (offline edits the server rejected as stale). */
|
||||
async conflictCount(): Promise<number> {
|
||||
return offlineDb.mutationQueue
|
||||
.where('status')
|
||||
.equals('conflict')
|
||||
.count()
|
||||
},
|
||||
|
||||
/** All unresolved conflicts, newest first, optionally scoped to one trip. */
|
||||
async conflicts(tripId?: number): Promise<QueuedMutation[]> {
|
||||
const all = await offlineDb.mutationQueue.where('status').equals('conflict').toArray()
|
||||
const scoped = tripId === undefined ? all : all.filter(m => m.tripId === tripId)
|
||||
return scoped.sort((a, b) => (b.conflictAt ?? 0) - (a.conflictAt ?? 0))
|
||||
},
|
||||
|
||||
/**
|
||||
* Resolve a conflict by keeping the local (offline) edit: re-queue it without
|
||||
* the base token so the next flush overwrites the server unconditionally.
|
||||
*/
|
||||
async resolveKeepMine(id: string): Promise<void> {
|
||||
const m = await offlineDb.mutationQueue.get(id)
|
||||
if (!m || m.status !== 'conflict') return
|
||||
await offlineDb.mutationQueue.update(id, {
|
||||
status: 'pending', baseUpdatedAt: null, conflictServer: undefined, conflictAt: undefined, lastError: null,
|
||||
})
|
||||
await this.flush()
|
||||
},
|
||||
|
||||
/**
|
||||
* Resolve a conflict by keeping the server's version: adopt it into the local
|
||||
* cache and drop the queued write.
|
||||
*/
|
||||
async resolveKeepServer(id: string): Promise<void> {
|
||||
const m = await offlineDb.mutationQueue.get(id)
|
||||
if (!m || m.status !== 'conflict') return
|
||||
await applyServerEntity(m, m.conflictServer)
|
||||
await offlineDb.mutationQueue.delete(id)
|
||||
},
|
||||
|
||||
/** Reset internal flushing flag and timestamp counters — useful in tests. */
|
||||
_resetFlushing(): void {
|
||||
_flushing = false
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Network mode — the single source of truth for whether the app should behave
|
||||
* as if it were offline right now.
|
||||
*
|
||||
* Two inputs combine here:
|
||||
* - the real browser state (`navigator.onLine`)
|
||||
* - a user-controlled "force offline" override (the Settings → Offline toggle)
|
||||
*
|
||||
* The repo layer, the mutation queue and the sync triggers all gate on
|
||||
* `isEffectivelyOffline()` instead of reading `navigator.onLine` directly, so a
|
||||
* forced-offline session routes every read to the Dexie cache and every write to
|
||||
* the mutation queue exactly as a genuine disconnection would. The override is
|
||||
* persisted so it survives a reload (a user who forced offline before boarding a
|
||||
* plane stays offline after the PWA is relaunched).
|
||||
*
|
||||
* Forcing offline does NOT pretend the network is gone for everything: it is the
|
||||
* caller's job (Settings → Offline) to pre-download first and only then flip the
|
||||
* switch. See tripSyncManager.prepareForOffline().
|
||||
*/
|
||||
|
||||
const STORAGE_KEY = 'trek_forced_offline'
|
||||
|
||||
let _forced = readPersisted()
|
||||
const listeners = new Set<() => void>()
|
||||
|
||||
function readPersisted(): boolean {
|
||||
try {
|
||||
return typeof localStorage !== 'undefined' && localStorage.getItem(STORAGE_KEY) === '1'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function persist(v: boolean): void {
|
||||
try {
|
||||
if (v) localStorage.setItem(STORAGE_KEY, '1')
|
||||
else localStorage.removeItem(STORAGE_KEY)
|
||||
} catch {
|
||||
/* private mode / quota — the in-memory flag still governs this session */
|
||||
}
|
||||
}
|
||||
|
||||
function notify(): void {
|
||||
listeners.forEach(fn => {
|
||||
try { fn() } catch { /* a listener throwing must not break the others */ }
|
||||
})
|
||||
}
|
||||
|
||||
/** True when the user has manually forced the app into offline mode. */
|
||||
export function isForcedOffline(): boolean {
|
||||
return _forced
|
||||
}
|
||||
|
||||
/** Flip the manual force-offline override and notify subscribers. */
|
||||
export function setForcedOffline(v: boolean): void {
|
||||
if (_forced === v) return
|
||||
_forced = v
|
||||
persist(v)
|
||||
notify()
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the app should treat itself as offline: either the browser is
|
||||
* genuinely offline OR the user forced offline mode. This is the flag the
|
||||
* offline read/write paths must gate on.
|
||||
*/
|
||||
export function isEffectivelyOffline(): boolean {
|
||||
return _forced || !navigator.onLine
|
||||
}
|
||||
|
||||
/** Convenience inverse of {@link isEffectivelyOffline}. */
|
||||
export function isEffectivelyOnline(): boolean {
|
||||
return !isEffectivelyOffline()
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to network-mode changes (force-offline toggled, or the browser's own
|
||||
* online/offline events). Returns an unsubscribe function. Registers the global
|
||||
* browser listeners lazily on first subscription.
|
||||
*/
|
||||
export function onNetworkModeChange(fn: () => void): () => void {
|
||||
ensureBrowserListeners()
|
||||
listeners.add(fn)
|
||||
return () => listeners.delete(fn)
|
||||
}
|
||||
|
||||
let _browserListenersBound = false
|
||||
function ensureBrowserListeners(): void {
|
||||
if (_browserListenersBound || typeof window === 'undefined') return
|
||||
_browserListenersBound = true
|
||||
window.addEventListener('online', notify)
|
||||
window.addEventListener('offline', notify)
|
||||
}
|
||||
|
||||
/** Reset state — test helper only. */
|
||||
export function _resetNetworkMode(): void {
|
||||
_forced = false
|
||||
listeners.clear()
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Offline preferences — device-local choices about WHAT gets stored offline and
|
||||
* HOW sync conflicts are resolved (discussion #1135, asks 2 and 3).
|
||||
*
|
||||
* These live in localStorage rather than the server user-settings because they
|
||||
* are inherently per-device: how much storage a phone should spend on map tiles,
|
||||
* or which trips to keep on this particular device, has nothing to do with the
|
||||
* account and everything to do with the hardware in the user's hand.
|
||||
*
|
||||
* cacheTiles — global on/off for pre-downloading map tiles. Off keeps
|
||||
* the cache to trip data + documents only ("not the whole
|
||||
* world map"). See tripSyncManager / clearTileCache.
|
||||
* disabledTripIds — trips the user explicitly excluded from offline storage.
|
||||
* Everything else that is date-eligible is cached.
|
||||
* conflictStrategy — what to do when an offline edit collides with a newer
|
||||
* server change: 'ask' surfaces a per-conflict picker,
|
||||
* 'mine'/'server' resolve automatically.
|
||||
*/
|
||||
|
||||
export type ConflictStrategy = 'ask' | 'mine' | 'server'
|
||||
|
||||
export interface OfflinePrefs {
|
||||
cacheTiles: boolean
|
||||
disabledTripIds: number[]
|
||||
conflictStrategy: ConflictStrategy
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'trek_offline_prefs'
|
||||
|
||||
const DEFAULTS: OfflinePrefs = {
|
||||
cacheTiles: true,
|
||||
disabledTripIds: [],
|
||||
conflictStrategy: 'ask',
|
||||
}
|
||||
|
||||
let _prefs: OfflinePrefs = read()
|
||||
const listeners = new Set<() => void>()
|
||||
|
||||
function read(): OfflinePrefs {
|
||||
try {
|
||||
const raw = typeof localStorage !== 'undefined' ? localStorage.getItem(STORAGE_KEY) : null
|
||||
if (!raw) return { ...DEFAULTS }
|
||||
const parsed = JSON.parse(raw) as Partial<OfflinePrefs>
|
||||
return {
|
||||
cacheTiles: typeof parsed.cacheTiles === 'boolean' ? parsed.cacheTiles : DEFAULTS.cacheTiles,
|
||||
disabledTripIds: Array.isArray(parsed.disabledTripIds) ? parsed.disabledTripIds.filter(n => typeof n === 'number') : [],
|
||||
conflictStrategy: parsed.conflictStrategy === 'mine' || parsed.conflictStrategy === 'server' ? parsed.conflictStrategy : 'ask',
|
||||
}
|
||||
} catch {
|
||||
return { ...DEFAULTS }
|
||||
}
|
||||
}
|
||||
|
||||
function write(next: OfflinePrefs): void {
|
||||
_prefs = next
|
||||
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)) } catch { /* best-effort */ }
|
||||
listeners.forEach(fn => { try { fn() } catch { /* isolate listeners */ } })
|
||||
}
|
||||
|
||||
/** Current snapshot (a copy — callers must not mutate it in place). */
|
||||
export function getOfflinePrefs(): OfflinePrefs {
|
||||
return { ..._prefs, disabledTripIds: [..._prefs.disabledTripIds] }
|
||||
}
|
||||
|
||||
export function setCacheTiles(on: boolean): void {
|
||||
if (_prefs.cacheTiles === on) return
|
||||
write({ ..._prefs, cacheTiles: on })
|
||||
}
|
||||
|
||||
export function setConflictStrategy(strategy: ConflictStrategy): void {
|
||||
if (_prefs.conflictStrategy === strategy) return
|
||||
write({ ..._prefs, conflictStrategy: strategy })
|
||||
}
|
||||
|
||||
/** True when this trip should be cached offline (i.e. not explicitly disabled). */
|
||||
export function isTripOfflineEnabled(tripId: number): boolean {
|
||||
return !_prefs.disabledTripIds.includes(tripId)
|
||||
}
|
||||
|
||||
/** Turn offline storage for a single trip on or off. */
|
||||
export function setTripOfflineEnabled(tripId: number, on: boolean): void {
|
||||
const has = _prefs.disabledTripIds.includes(tripId)
|
||||
if (on && !has) return
|
||||
if (!on && has) return
|
||||
const disabledTripIds = on
|
||||
? _prefs.disabledTripIds.filter(id => id !== tripId)
|
||||
: [..._prefs.disabledTripIds, tripId]
|
||||
write({ ..._prefs, disabledTripIds })
|
||||
}
|
||||
|
||||
/** Subscribe to preference changes. Returns an unsubscribe function. */
|
||||
export function onOfflinePrefsChange(fn: () => void): () => void {
|
||||
listeners.add(fn)
|
||||
return () => listeners.delete(fn)
|
||||
}
|
||||
|
||||
/** Reset to defaults — test helper only. */
|
||||
export function _resetOfflinePrefs(): void {
|
||||
_prefs = { ...DEFAULTS }
|
||||
listeners.clear()
|
||||
}
|
||||
@@ -14,12 +14,15 @@
|
||||
*/
|
||||
import { mutationQueue } from './mutationQueue'
|
||||
import { tripSyncManager } from './tripSyncManager'
|
||||
import { isEffectivelyOnline, onNetworkModeChange } from './networkMode'
|
||||
import { setPreReconnectHook, setRefetchCallback, getActiveTrips } from '../api/websocket'
|
||||
import { useTripStore } from '../store/tripStore'
|
||||
|
||||
const PERIODIC_MS = 30_000
|
||||
|
||||
let _intervalId: ReturnType<typeof setInterval> | null = null
|
||||
let _unsubscribeNetworkMode: (() => void) | null = null
|
||||
let _wasEffectivelyOnline = isEffectivelyOnline()
|
||||
let _registered = false
|
||||
|
||||
/** Pull the latest server state for every open trip into the Zustand store. */
|
||||
@@ -36,6 +39,11 @@ function rehydrateActiveTrips() {
|
||||
* edits made while we were offline appear without navigating away.
|
||||
*/
|
||||
function onOnline() {
|
||||
// A real browser reconnect must NOT override a user-forced offline session:
|
||||
// syncAll would re-seed Dexie from the server and wipe un-flushed optimistic
|
||||
// edits from the cache/UI. Stay put until the user lifts the switch (which
|
||||
// routes through onNetworkMode → here with the force flag already cleared).
|
||||
if (!isEffectivelyOnline()) return
|
||||
mutationQueue.flush()
|
||||
.catch(console.error)
|
||||
.finally(() => {
|
||||
@@ -46,18 +54,30 @@ function onOnline() {
|
||||
|
||||
/** Tab became visible — flush only; don't trigger a potentially expensive syncAll. */
|
||||
function onVisibility() {
|
||||
if (!document.hidden && navigator.onLine) {
|
||||
if (!document.hidden && isEffectivelyOnline()) {
|
||||
mutationQueue.flush().catch(console.error)
|
||||
}
|
||||
}
|
||||
|
||||
/** Periodic heartbeat — drain any lingering pending mutations. */
|
||||
function onPeriodic() {
|
||||
if (navigator.onLine) {
|
||||
if (isEffectivelyOnline()) {
|
||||
mutationQueue.flush().catch(console.error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The force-offline toggle (or a browser online/offline event) changed the
|
||||
* effective network mode. Coming back online — whether the network returned or
|
||||
* the user lifted the force-offline switch — behaves like a real reconnection:
|
||||
* flush queued writes, then re-seed and re-hydrate.
|
||||
*/
|
||||
function onNetworkMode() {
|
||||
const nowOnline = isEffectivelyOnline()
|
||||
if (nowOnline && !_wasEffectivelyOnline) onOnline()
|
||||
_wasEffectivelyOnline = nowOnline
|
||||
}
|
||||
|
||||
export function registerSyncTriggers(): void {
|
||||
if (_registered) return
|
||||
_registered = true
|
||||
@@ -73,6 +93,10 @@ export function registerSyncTriggers(): void {
|
||||
|
||||
window.addEventListener('online', onOnline)
|
||||
document.addEventListener('visibilitychange', onVisibility)
|
||||
// React to the force-offline toggle (and browser online/offline) so lifting
|
||||
// the switch immediately flushes + re-seeds like a real reconnection.
|
||||
_wasEffectivelyOnline = isEffectivelyOnline()
|
||||
_unsubscribeNetworkMode = onNetworkModeChange(onNetworkMode)
|
||||
_intervalId = setInterval(onPeriodic, PERIODIC_MS)
|
||||
}
|
||||
|
||||
@@ -84,6 +108,10 @@ export function unregisterSyncTriggers(): void {
|
||||
setRefetchCallback(null)
|
||||
window.removeEventListener('online', onOnline)
|
||||
document.removeEventListener('visibilitychange', onVisibility)
|
||||
if (_unsubscribeNetworkMode) {
|
||||
_unsubscribeNetworkMode()
|
||||
_unsubscribeNetworkMode = null
|
||||
}
|
||||
if (_intervalId !== null) {
|
||||
clearInterval(_intervalId)
|
||||
_intervalId = null
|
||||
|
||||
@@ -143,11 +143,16 @@ export async function prefetchTiles(
|
||||
tileUrlTemplate: string,
|
||||
minZoom = 10,
|
||||
maxZoom = 16,
|
||||
awaitAll = false,
|
||||
): Promise<number> {
|
||||
if (!navigator.onLine) return 0
|
||||
if (!('serviceWorker' in navigator) || !navigator.serviceWorker.controller) return 0
|
||||
|
||||
let fetched = 0
|
||||
// When awaitAll is set (the "prepare for offline" path), we wait for every tile
|
||||
// request to settle so the caller's progress bar only completes once the tiles
|
||||
// are actually downloaded into the SW cache — not merely dispatched.
|
||||
const inflight: Promise<unknown>[] = []
|
||||
|
||||
for (let z = minZoom; z <= maxZoom; z++) {
|
||||
const minX = lngToTileX(bbox.minLng, z)
|
||||
@@ -161,16 +166,32 @@ export async function prefetchTiles(
|
||||
for (let x = minX; x <= maxX; x++) {
|
||||
for (let y = minY; y <= maxY; y++) {
|
||||
const url = buildTileUrl(tileUrlTemplate, z, x, y)
|
||||
// Fire-and-forget: SW CacheFirst handler stores the response
|
||||
fetch(url, { mode: 'no-cors' }).catch(() => {})
|
||||
// SW CacheFirst handler stores the response. Fire-and-forget unless the
|
||||
// caller asked to await completion.
|
||||
const p = fetch(url, { mode: 'no-cors' }).catch(() => {})
|
||||
if (awaitAll) inflight.push(p)
|
||||
fetched++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (awaitAll && inflight.length) await Promise.allSettled(inflight)
|
||||
return fetched
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop the pre-downloaded map-tile cache. Called when the user turns off
|
||||
* "store map tiles offline" (#1135 ask 2) so the bulk tile storage — the real
|
||||
* "whole world map" concern — is reclaimed immediately.
|
||||
*/
|
||||
export async function clearTileCache(): Promise<void> {
|
||||
try {
|
||||
if (typeof caches !== 'undefined') await caches.delete('map-tiles')
|
||||
} catch {
|
||||
/* Cache Storage unavailable (no SW / private mode) — nothing to clear */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Full pipeline: compute bbox → guard → prefetch → update syncMeta.
|
||||
* Designed to be called fire-and-forget from tripSyncManager.
|
||||
@@ -179,6 +200,7 @@ export async function prefetchTilesForTrip(
|
||||
tripId: number,
|
||||
places: Place[],
|
||||
tileUrlTemplate?: string,
|
||||
awaitAll = false,
|
||||
): Promise<void> {
|
||||
const template = tileUrlTemplate || DEFAULT_TILE_URL
|
||||
const bbox = computeBbox(places)
|
||||
@@ -194,7 +216,7 @@ export async function prefetchTilesForTrip(
|
||||
// tile providers that don't send CORS headers. To stop the browser evicting
|
||||
// these tiles under the inflated quota, we request persistent storage at app
|
||||
// init instead (sync/persistentStorage.ts).
|
||||
const fetched = await prefetchTiles(bbox, template)
|
||||
const fetched = await prefetchTiles(bbox, template, 10, 16, awaitAll)
|
||||
|
||||
// Update syncMeta with bbox and tile count
|
||||
const meta = await offlineDb.syncMeta.get(tripId)
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
} from '../db/offlineDb'
|
||||
import { prefetchTilesForTrip } from './tilePrefetcher'
|
||||
import { isAuthed } from './authGate'
|
||||
import { getOfflinePrefs, isTripOfflineEnabled } from './offlinePrefs'
|
||||
import { useSettingsStore } from '../store/settingsStore'
|
||||
import type { Trip, Day, Place, PackingItem, TodoItem, BudgetItem, Reservation, TripFile, Accommodation, TripMember } from '../types'
|
||||
|
||||
@@ -130,26 +131,46 @@ async function cacheFilesForTrip(files: TripFile[]): Promise<void> {
|
||||
|
||||
// ── Public API ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Progress callback payload for a {@link tripSyncManager.prepareForOffline} run. */
|
||||
export interface PrepareProgress {
|
||||
/** Current stage. 'done' fires once at the end. */
|
||||
phase: 'trips' | 'files' | 'tiles' | 'done'
|
||||
/** 1-based index of the trip currently processed in this phase. */
|
||||
current: number
|
||||
/** Total trips to process in this phase. */
|
||||
total: number
|
||||
/** Name of the trip currently processed (for the UI). */
|
||||
label?: string
|
||||
}
|
||||
|
||||
let _syncing = false
|
||||
|
||||
/**
|
||||
* Decide which trips to cache and which to drop, honouring both the date rule
|
||||
* and the user's per-trip offline choices (#1135 ask 2). Returns the trips to
|
||||
* sync; clears Dexie for stale or user-disabled trips as a side effect.
|
||||
*/
|
||||
async function reconcileTrips(trips: Trip[]): Promise<Trip[]> {
|
||||
const stale = trips.filter(isStale)
|
||||
// Trips the user turned off explicitly are evicted regardless of date.
|
||||
const disabled = trips.filter(t => !isTripOfflineEnabled(t.id))
|
||||
await Promise.all([...stale, ...disabled].map(t => clearTripData(t.id).catch(console.error)))
|
||||
return trips.filter(t => shouldCache(t) && isTripOfflineEnabled(t.id))
|
||||
}
|
||||
|
||||
export const tripSyncManager = {
|
||||
/**
|
||||
* Sync all cache-eligible trips.
|
||||
* Evicts stale trips. Caches file blobs in the background.
|
||||
* No-ops when offline.
|
||||
* Evicts stale and user-disabled trips. Caches file blobs + map tiles in the
|
||||
* background. No-ops when offline.
|
||||
*/
|
||||
async syncAll(): Promise<void> {
|
||||
if (_syncing || !navigator.onLine || !isAuthed()) return
|
||||
_syncing = true
|
||||
try {
|
||||
const { trips } = await tripsApi.list() as { trips: Trip[] }
|
||||
const toSync = await reconcileTrips(trips)
|
||||
|
||||
// Evict stale trips first
|
||||
const stale = trips.filter(isStale)
|
||||
await Promise.all(stale.map(t => clearTripData(t.id).catch(console.error)))
|
||||
|
||||
// Sync eligible trips
|
||||
const toSync = trips.filter(shouldCache)
|
||||
for (const trip of toSync) {
|
||||
try {
|
||||
await syncTrip(trip.id)
|
||||
@@ -163,19 +184,82 @@ export const tripSyncManager = {
|
||||
categoriesApi.list().then(d => upsertCategories(d.categories)).catch(() => {})
|
||||
|
||||
// Cache file blobs + map tiles in background (don't block syncAll)
|
||||
const cacheTiles = getOfflinePrefs().cacheTiles
|
||||
const tileUrl = useSettingsStore.getState().settings.map_tile_url || undefined
|
||||
for (const trip of toSync) {
|
||||
const files = await offlineDb.tripFiles.where('trip_id').equals(trip.id).toArray()
|
||||
cacheFilesForTrip(files).catch(console.error)
|
||||
|
||||
const places = await offlineDb.places.where('trip_id').equals(trip.id).toArray()
|
||||
prefetchTilesForTrip(trip.id, places, tileUrl).catch(console.error)
|
||||
if (cacheTiles) {
|
||||
const places = await offlineDb.places.where('trip_id').equals(trip.id).toArray()
|
||||
prefetchTilesForTrip(trip.id, places, tileUrl).catch(console.error)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
_syncing = false
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* "Prepare for offline" (#1135 ask 1): a fully-awaited sync the user runs while
|
||||
* still online so everything they need is guaranteed on-device before they go
|
||||
* offline. Unlike syncAll, this AWAITS file-blob and map-tile downloads and
|
||||
* reports progress, so the UI can show a real completion state instead of
|
||||
* resolving the moment the requests are merely dispatched.
|
||||
*
|
||||
* Returns the number of trips prepared.
|
||||
*/
|
||||
async prepareForOffline(onProgress?: (p: PrepareProgress) => void): Promise<number> {
|
||||
if (_syncing || !navigator.onLine || !isAuthed()) return 0
|
||||
_syncing = true
|
||||
try {
|
||||
const { trips } = await tripsApi.list() as { trips: Trip[] }
|
||||
const toSync = await reconcileTrips(trips)
|
||||
const total = toSync.length
|
||||
|
||||
// 1) Trip bundles (structured data).
|
||||
let i = 0
|
||||
for (const trip of toSync) {
|
||||
onProgress?.({ phase: 'trips', current: ++i, total, label: trip.title })
|
||||
try {
|
||||
await syncTrip(trip.id)
|
||||
} catch (err) {
|
||||
console.error(`[tripSync] prepare failed for trip ${trip.id}:`, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Global user data (tags + categories) — awaited here.
|
||||
await Promise.all([
|
||||
tagsApi.list().then(d => upsertTags(d.tags)).catch(() => {}),
|
||||
categoriesApi.list().then(d => upsertCategories(d.categories)).catch(() => {}),
|
||||
])
|
||||
|
||||
// 2) File blobs — awaited so "prepared" really means downloaded.
|
||||
i = 0
|
||||
for (const trip of toSync) {
|
||||
onProgress?.({ phase: 'files', current: ++i, total, label: trip.title })
|
||||
const files = await offlineDb.tripFiles.where('trip_id').equals(trip.id).toArray()
|
||||
await cacheFilesForTrip(files).catch(console.error)
|
||||
}
|
||||
|
||||
// 3) Map tiles — awaited, and only when the user opted to store them.
|
||||
if (getOfflinePrefs().cacheTiles) {
|
||||
const tileUrl = useSettingsStore.getState().settings.map_tile_url || undefined
|
||||
i = 0
|
||||
for (const trip of toSync) {
|
||||
onProgress?.({ phase: 'tiles', current: ++i, total, label: trip.title })
|
||||
const places = await offlineDb.places.where('trip_id').equals(trip.id).toArray()
|
||||
await prefetchTilesForTrip(trip.id, places, tileUrl, true).catch(console.error)
|
||||
}
|
||||
}
|
||||
|
||||
onProgress?.({ phase: 'done', current: total, total })
|
||||
return total
|
||||
} finally {
|
||||
_syncing = false
|
||||
}
|
||||
},
|
||||
|
||||
/** Reset syncing flag — useful in tests. */
|
||||
_resetSyncing(): void {
|
||||
_syncing = false
|
||||
|
||||
Reference in New Issue
Block a user