fix(offline): the PWA starts offline again and the download does what it says

Four separate defects sat behind "offline mode is broken".

The app shell. On the first online launch after a version bump, App.tsx
deleted EVERY Cache Storage bucket and unregistered EVERY service worker,
then reloaded. That is exactly wrong for a Workbox autoUpdate build, which
swaps its precache atomically on install and never leaves an empty one.
Between the purge and the completion of a fresh 22 MB precache the origin
had no shell at all; anyone who closed the app or lost signal inside that
window could no longer start the PWA offline. It also threw away the map
tiles and documents the user had downloaded on purpose. It now asks the
worker to fetch the new build and reloads once it has taken over. The
version marker also moves inside the guarded path, because it was written
after the purge and outside its try: a throwing setItem left the caches
gone, the marker unwritten and the reload unreached, repeating on every
launch.

The reported version is validated before it reaches this device's storage and
before it is compared against the stored marker, so a value that is not a
release tag can neither be persisted nor start an update on every launch.

The session. loadUser's offline branch kept the persisted session but
never called onAuthSuccess, the only caller of setAuthed(true), and the
mutation queue's flush, syncAll and prepareForOffline are all gated on it.
A session that launched without network could therefore never sync again
for the rest of its life, even after the signal returned: the offline
settings buttons spun and returned instantly having done nothing, and
queued edits never uploaded. It also left reads pointed at the anonymous
database instead of the user's own.

The date rule. A trip is only cached when it has not ended, and one that
ended over a week ago is actively evicted. The per-trip switch was an
opt-out list, so ticking a finished trip changed nothing at all. For
anyone whose trips are all in the past, "Download for offline use" stored
none of them, reported success, and the cache stayed at zero. Switching a
trip on now pins it, which overrides both the skip and the eviction, and
the switch shows the honest position rather than promising storage that
never happens.

What the screen says. A sync that never started (already running, offline,
signed out) was indistinguishable from one that stored everything: the
progress bar painted full and a green "Ready for offline use" appeared over
a run of nothing. Both syncs now report why they stopped and the screen
says so. A rejected Dexie read no longer renders as "No trips cached yet",
and the clear button stays reachable when the database holds data that no
bookkeeping row points at. A run that rejects outright says so too: the trip
list it starts from is a plain fetch, so a network blip took the whole thing
down and left the last progress frame on screen looking like a finished
download. The 401-with-HTML branch in the API client now
confirms a reachable proxy before tearing the worker down, since several of
TREK's own routes answer 401 with a text/html body.

Both settings shells move onto one shared hook rather than growing the same
logic twice, and the tile prefetch caps its depth when the browser refused
persistent storage. Opaque tiles are billed at about 7 MB each, and an
origin that is not exempt from eviction loses its whole bucket, precached
shell included, which Workbox then never refills because sw.js has not
changed.

Closes #2228
This commit is contained in:
Maurice
2026-09-04 12:16:00 +02:00
committed by Maurice
parent d77f1c1758
commit 1b71b8633d
42 changed files with 1101 additions and 390 deletions
@@ -1,4 +1,4 @@
// FE-COMP-OFFLINETAB-001 to FE-COMP-OFFLINETAB-024
// FE-COMP-OFFLINETAB-001 to FE-COMP-OFFLINETAB-028
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -21,16 +21,17 @@ const h = vi.hoisted(() => {
const syncMetaToArray = vi.fn();
const tripsGet = vi.fn();
const tripsToArray = vi.fn();
const tripsCount = vi.fn();
const placeCount = vi.fn();
const fileCount = vi.fn();
const counted = (fn: (id: number) => Promise<number>) => ({
where: () => ({ equals: (id: number) => ({ count: () => fn(id) }) }),
});
return {
syncMetaToArray, tripsGet, tripsToArray, placeCount, fileCount,
syncMetaToArray, tripsGet, tripsToArray, tripsCount, placeCount, fileCount,
fakeDb: {
syncMeta: { toArray: syncMetaToArray },
trips: { get: tripsGet, toArray: tripsToArray },
trips: { get: tripsGet, toArray: tripsToArray, count: tripsCount },
places: counted(placeCount),
tripFiles: counted(fileCount),
},
@@ -104,6 +105,7 @@ const conflict = (over: Partial<QueuedMutation> = {}): QueuedMutation => ({
/** Seed the Dexie cache with the given (trip, meta) pairs. */
function cache(rows: { trip: Trip; meta?: Partial<SyncMeta>; places?: number; files?: number }[]): void {
h.syncMetaToArray.mockResolvedValue(rows.map(r => meta(r.trip.id, r.meta)));
h.tripsCount.mockResolvedValue(rows.length);
h.tripsGet.mockImplementation(async (id: number) => rows.find(r => r.trip.id === id)?.trip);
h.placeCount.mockImplementation(async (id: number) => rows.find(r => r.trip.id === id)?.places ?? 0);
h.fileCount.mockImplementation(async (id: number) => rows.find(r => r.trip.id === id)?.files ?? 0);
@@ -130,6 +132,7 @@ beforeEach(() => {
h.syncMetaToArray.mockResolvedValue([]);
h.tripsGet.mockResolvedValue(undefined);
h.tripsToArray.mockResolvedValue([]);
h.tripsCount.mockResolvedValue(0);
h.placeCount.mockResolvedValue(0);
h.fileCount.mockResolvedValue(0);
h.pendingCount.mockResolvedValue(0);
@@ -138,8 +141,8 @@ beforeEach(() => {
h.clearAll.mockResolvedValue(undefined);
h.clearTripData.mockResolvedValue(undefined);
h.clearTileCache.mockResolvedValue(undefined);
h.prepareForOffline.mockResolvedValue(undefined);
h.syncAll.mockResolvedValue(undefined);
h.prepareForOffline.mockResolvedValue({ status: 'done', trips: 1 });
h.syncAll.mockResolvedValue({ status: 'done', trips: 1 });
h.resolveKeepMine.mockResolvedValue(undefined);
h.resolveKeepServer.mockResolvedValue(undefined);
@@ -284,6 +287,7 @@ describe('OfflineTab', () => {
cb({ phase: 'files', current: 1, total: 4, label: 'Paris' });
await new Promise<void>(resolve => { release = resolve; });
cb({ phase: 'done', current: 4, total: 4 });
return { status: 'done', trips: 4 };
});
render(<OfflineTab />);
@@ -294,7 +298,7 @@ describe('OfflineTab', () => {
expect(screen.getByRole('button', { name: 'Downloading…' })).toBeDisabled();
await act(async () => { release(); });
expect(await screen.findByText('Ready for offline use')).toBeInTheDocument();
expect(await screen.findByText('Stored 4 trip(s) on this device')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Download for offline use' })).toBeEnabled();
});
@@ -304,6 +308,7 @@ describe('OfflineTab', () => {
h.prepareForOffline.mockImplementation(async (cb: (p: PrepareProgress) => void) => {
cb({ phase: 'tiles', current: 0, total: 0 });
await new Promise<void>(resolve => { release = resolve; });
return { status: 'done', trips: 1 };
});
render(<OfflineTab />);
@@ -322,6 +327,7 @@ describe('OfflineTab', () => {
h.prepareForOffline.mockImplementation(async (cb: (p: PrepareProgress) => void) => {
cb({ phase: 'trips', current: 1, total: 4 });
await new Promise<void>(resolve => { release = resolve; });
return { status: 'done', trips: 4 };
});
render(<OfflineTab />);
@@ -380,7 +386,7 @@ describe('OfflineTab', () => {
it('FE-COMP-OFFLINETAB-017: Re-sync shows the syncing label while it runs', async () => {
const user = userEvent.setup();
let release!: () => void;
h.syncAll.mockImplementation(() => new Promise<void>(resolve => { release = resolve; }));
h.syncAll.mockImplementation(() => new Promise(resolve => { release = () => resolve({ status: 'done', trips: 1 }); }));
render(<OfflineTab />);
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
@@ -408,21 +414,69 @@ describe('OfflineTab', () => {
expect(h.clearTileCache).toHaveBeenCalledTimes(1);
});
it('FE-COMP-OFFLINETAB-019: switching a trip off evicts it, switching it back on re-syncs', async () => {
it('FE-COMP-OFFLINETAB-019: switching a finished trip on pins and re-syncs it, switching it off evicts it', async () => {
const user = userEvent.setup();
render(<OfflineTab />);
// Both fixture trips ended in 2025, so the date rule would skip them: the
// switch has to read "off" rather than promising storage that never happens.
const toggle = await screen.findByRole('button', { name: 'Tokyo' });
expect(toggle).toHaveAttribute('aria-pressed', 'true');
expect(screen.getAllByText('Stored offline')).toHaveLength(2);
await user.click(toggle);
expect(h.clearTripData).toHaveBeenCalledWith(2);
await waitFor(() => expect(screen.getByText('Not stored')).toBeInTheDocument());
expect(toggle).toHaveAttribute('aria-pressed', 'false');
expect(screen.getAllByText(/Not stored · Finished/)).toHaveLength(2);
await user.click(toggle);
await waitFor(() => expect(h.syncAll).toHaveBeenCalledTimes(1));
expect(h.clearTripData).toHaveBeenCalledTimes(1);
expect(getOfflinePrefs().pinnedTripIds).toEqual([2]);
await waitFor(() => expect(screen.getByRole('button', { name: 'Tokyo' })).toHaveAttribute('aria-pressed', 'true'));
await user.click(screen.getByRole('button', { name: 'Tokyo' }));
expect(h.clearTripData).toHaveBeenCalledWith(2);
// Turning it off releases the pin, so "off then on" cannot leave it pinned.
expect(getOfflinePrefs().pinnedTripIds).toEqual([]);
});
it('FE-COMP-OFFLINETAB-025: an ongoing trip is stored without needing a pin', async () => {
const soon = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);
const ongoing = buildTrip({ id: 7, title: 'Lisbon', start_date: '2025-01-01', end_date: soon });
server.use(http.get('/api/trips', () => HttpResponse.json({ trips: [ongoing] })));
render(<OfflineTab />);
const toggle = await screen.findByRole('button', { name: 'Lisbon' });
expect(toggle).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByText('Stored offline')).toBeInTheDocument();
expect(getOfflinePrefs().pinnedTripIds).toEqual([]);
});
it('FE-COMP-OFFLINETAB-026: a sync that never ran says so instead of reporting success', async () => {
const user = userEvent.setup();
h.prepareForOffline.mockResolvedValue({ status: 'skipped', reason: 'busy' });
render(<OfflineTab />);
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
await user.click(screen.getByRole('button', { name: 'Download for offline use' }));
expect(await screen.findByText('A sync is already running. Try again in a moment.')).toBeInTheDocument();
expect(screen.queryByText(/Stored .* trip/)).not.toBeInTheDocument();
});
it('FE-COMP-OFFLINETAB-028: a download that throws is reported instead of leaving the last frame up', async () => {
const user = userEvent.setup();
h.prepareForOffline.mockRejectedValue(new Error('network went away'));
render(<OfflineTab />);
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
await user.click(screen.getByRole('button', { name: 'Download for offline use' }));
expect(await screen.findByText('The download could not finish. Check your connection and try again.')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Download for offline use' })).toBeEnabled();
});
it('FE-COMP-OFFLINETAB-027: an unreadable offline database is reported, not shown as empty', async () => {
h.syncMetaToArray.mockRejectedValue(new Error('DatabaseClosedError'));
render(<OfflineTab />);
expect(await screen.findByText(/Could not read this device’s offline storage/)).toBeInTheDocument();
expect(screen.queryByText('No trips cached yet. Connect to the internet to sync.')).not.toBeInTheDocument();
});
it('FE-COMP-OFFLINETAB-020: the per-trip section disappears when there are no trips at all', async () => {
@@ -478,6 +532,7 @@ describe('OfflineTab', () => {
await waitFor(() => expect(screen.getByRole('button', { name: 'Clear cache' })).toBeEnabled());
h.syncMetaToArray.mockResolvedValue([]);
h.tripsCount.mockResolvedValue(0);
await user.click(screen.getByRole('button', { name: 'Clear cache' }));
expect(h.clearAll).toHaveBeenCalledTimes(1);
+28 -159
View File
@@ -6,33 +6,18 @@
* - What to store: a map-tiles toggle plus a per-trip on/off.
* - Sync conflicts: a keep-mine / keep-theirs resolver and a default strategy.
* - Cache stats + clear.
*
* All of the logic lives in `useOfflineSettings`, shared with the phone twin
* `MSettingsOffline`; this file is the desktop markup over it.
*/
import React, { useState, useEffect, useCallback } from 'react'
import { RefreshCw, Trash2, Database, CloudOff, Download, Check, GitMerge, Map as MapIcon } from 'lucide-react'
import React from 'react'
import { RefreshCw, Trash2, Database, CloudOff, Download, Check, GitMerge, Map as MapIcon, AlertTriangle } from 'lucide-react'
import Section from './Section'
import ToggleSwitch from './ToggleSwitch'
import { offlineDb, clearAll, clearTripData } from '../../db/offlineDb'
import { tripsApi } from '../../api/client'
import { tripSyncManager, type PrepareProgress } from '../../sync/tripSyncManager'
import { mutationQueue } from '../../sync/mutationQueue'
import { clearTileCache } from '../../sync/tilePrefetcher'
import { isEffectivelyOffline } from '../../sync/networkMode'
import {
getOfflinePrefs, setCacheTiles, setConflictStrategy,
isTripOfflineEnabled, setTripOfflineEnabled, onOfflinePrefsChange,
type ConflictStrategy,
} from '../../sync/offlinePrefs'
import { useNetworkMode } from '../../hooks/useNetworkMode'
import { useOfflineSettings, offlineNoticeKey, isOfflineNoticeWarning } from './useOfflineSettings'
import { useTranslation } from '../../i18n'
import type { SyncMeta, QueuedMutation } from '../../db/offlineDb'
import type { Trip } from '../../types'
interface CachedTripRow {
trip: Trip
meta: SyncMeta
placeCount: number
fileCount: number
}
import type { ConflictStrategy } from '../../sync/offlinePrefs'
import type { QueuedMutation } from '../../db/offlineDb'
function conflictName(m: QueuedMutation): string {
const body = (m.body ?? {}) as { name?: unknown }
@@ -44,132 +29,14 @@ function conflictName(m: QueuedMutation): string {
export default function OfflineTab(): React.ReactElement {
const { t } = useTranslation()
const { offline, forced, setForced } = useNetworkMode()
const [rows, setRows] = useState<CachedTripRow[]>([])
const [allTrips, setAllTrips] = useState<Trip[]>([])
const [pendingCount, setPendingCount] = useState(0)
const [failedCount, setFailedCount] = useState(0)
const [conflicts, setConflicts] = useState<QueuedMutation[]>([])
const [syncing, setSyncing] = useState(false)
const [clearing, setClearing] = useState(false)
const [loading, setLoading] = useState(true)
const [preparing, setPreparing] = useState(false)
const [progress, setProgress] = useState<PrepareProgress | null>(null)
const [prefs, setPrefs] = useState(getOfflinePrefs())
useEffect(() => onOfflinePrefsChange(() => setPrefs(getOfflinePrefs())), [])
const load = useCallback(async () => {
setLoading(true)
try {
const [metas, pending, failed, conflictList] = await Promise.all([
offlineDb.syncMeta.toArray(),
mutationQueue.pendingCount(),
mutationQueue.failedCount(),
mutationQueue.conflicts(),
])
setPendingCount(pending)
setFailedCount(failed)
setConflicts(conflictList)
const result: CachedTripRow[] = []
for (const meta of metas) {
const trip = await offlineDb.trips.get(meta.tripId)
if (!trip) continue
const [placeCount, fileCount] = await Promise.all([
offlineDb.places.where('trip_id').equals(meta.tripId).count(),
offlineDb.tripFiles.where('trip_id').equals(meta.tripId).count(),
])
result.push({ trip, meta, placeCount, fileCount })
}
result.sort((a, b) => (a.trip.start_date ?? '').localeCompare(b.trip.start_date ?? ''))
setRows(result)
// The per-trip storage toggles are driven by the FULL trip list, not just
// the cached ones, so a trip turned off stays visible and re-enableable.
try {
const trips = isEffectivelyOffline()
? await offlineDb.trips.toArray()
: await tripsApi.list().then(r => (r as { trips: Trip[] }).trips).catch(() => offlineDb.trips.toArray())
trips.sort((a, b) => (a.start_date ?? '').localeCompare(b.start_date ?? ''))
setAllTrips(trips)
} catch {
setAllTrips([])
}
} finally {
setLoading(false)
}
}, [])
useEffect(() => { load() }, [load])
const runPrepare = useCallback(async () => {
setPreparing(true)
setProgress(null)
try {
await tripSyncManager.prepareForOffline(p => setProgress(p))
await load()
} finally {
setPreparing(false)
}
}, [load])
async function handleToggleForce() {
if (!forced) {
// Turning offline mode on: download everything first (while still online),
// then engage so the app has all it needs before the network drops.
if (navigator.onLine) await runPrepare()
setForced(true)
} else {
// Back online: lifting the switch flushes the queue + re-syncs (syncTriggers).
setForced(false)
}
}
async function handleResync() {
setSyncing(true)
try {
await tripSyncManager.syncAll()
await load()
} finally {
setSyncing(false)
}
}
async function handleClear() {
if (!window.confirm(t('settings.offline.clearConfirm'))) return
setClearing(true)
try {
await clearAll()
await load()
} finally {
setClearing(false)
}
}
async function handleToggleTiles() {
const next = !prefs.cacheTiles
setCacheTiles(next)
// Turning tiles off reclaims the bulk tile storage straight away.
if (!next) await clearTileCache()
}
async function handleToggleTrip(tripId: number) {
const next = !isTripOfflineEnabled(tripId)
setTripOfflineEnabled(tripId, next)
if (!next) {
await clearTripData(tripId)
await load()
} else if (navigator.onLine) {
tripSyncManager.syncAll().then(load).catch(() => {})
}
}
async function resolveConflict(id: string, keepMine: boolean) {
if (keepMine) await mutationQueue.resolveKeepMine(id)
else await mutationQueue.resolveKeepServer(id)
await load()
}
const {
offline, forced,
rows, allTrips, pendingCount, failedCount, conflicts,
syncing, clearing, loading, preparing, progress, notice, prefs, canClear,
runPrepare, handleToggleForce, handleResync, handleClear,
handleToggleTiles, tripStorageState, handleToggleTrip, resolveConflict,
handleConflictStrategy,
} = useOfflineSettings()
const formatDate = (d: string | null | undefined) =>
d ? new Date(d).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }) : '—'
@@ -237,9 +104,10 @@ export default function OfflineTab(): React.ReactElement {
</div>
</div>
)}
{!preparing && progress?.phase === 'done' && (
<div className="text-content-muted" style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 'calc(12px * var(--fs-scale-body, 1))', marginTop: 10, color: '#10b981' }}>
<Check size={14} /> {t('settings.offline.prepare.done')}
{!preparing && notice && notice.kind !== 'load-failed' && (
<div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 'calc(12px * var(--fs-scale-body, 1))', marginTop: 10, color: isOfflineNoticeWarning(notice) ? 'var(--warning)' : 'var(--success)' }}>
{isOfflineNoticeWarning(notice) ? <AlertTriangle size={14} /> : <Check size={14} />}
{t(offlineNoticeKey(notice), notice.kind === 'stored' ? { count: notice.trips } : undefined)}
</div>
)}
</div>
@@ -273,7 +141,7 @@ export default function OfflineTab(): React.ReactElement {
control={
<select
value={prefs.conflictStrategy}
onChange={e => setConflictStrategy(e.target.value as ConflictStrategy)}
onChange={e => handleConflictStrategy(e.target.value as ConflictStrategy)}
className="border border-edge bg-surface-secondary text-content"
style={{ padding: '6px 10px', borderRadius: 8, fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
>
@@ -302,7 +170,7 @@ export default function OfflineTab(): React.ReactElement {
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{allTrips.map((trip) => {
const on = isTripOfflineEnabled(trip.id)
const { on, dateEligible } = tripStorageState(trip)
return (
<div key={trip.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
<div style={{ minWidth: 0 }}>
@@ -311,9 +179,10 @@ export default function OfflineTab(): React.ReactElement {
</div>
<div className="text-content-muted" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))' }}>
{on ? t('settings.offline.storage.tripOn') : t('settings.offline.storage.tripOff')}
{!dateEligible && ` · ${t('settings.offline.storage.tripFinished')}`}
</div>
</div>
<ToggleSwitch on={on} onToggle={() => handleToggleTrip(trip.id)} label={trip.title} />
<ToggleSwitch on={on} onToggle={() => handleToggleTrip(trip)} label={trip.title} />
</div>
)
})}
@@ -335,10 +204,10 @@ export default function OfflineTab(): React.ReactElement {
<div style={{ display: 'flex', gap: 8 }}>
<button type="button"
onClick={handleClear}
disabled={clearing || rows.length === 0}
onClick={() => { if (window.confirm(t('settings.offline.clearConfirm'))) void handleClear() }}
disabled={clearing || !canClear}
className="border border-edge bg-surface-secondary text-[#ef4444]"
style={btnStyle(clearing || rows.length === 0)}
style={btnStyle(clearing || !canClear)}
>
<Trash2 size={14} />
{t('settings.offline.clear')}
@@ -349,7 +218,7 @@ export default function OfflineTab(): React.ReactElement {
<p className="text-content-muted" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{t('settings.offline.loading')}</p>
) : rows.length === 0 ? (
<p className="text-content-muted" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>
{t('settings.offline.empty')}
{t(notice?.kind === 'load-failed' ? 'settings.offline.notice.loadFailed' : 'settings.offline.empty')}
</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
@@ -0,0 +1,282 @@
/**
* Shared state for the offline settings screen (#1135), used by both the desktop
* `OfflineTab` and its phone twin `MSettingsOffline`. The two shells render very
* different markup over identical logic, so the logic lives here once, the same
* arrangement as `useInstanceSettings` / `useRangeBypass`.
*
* It also carries the honesty fixes from #2228: a sync that never started is
* reported as such instead of silently painting a finished progress bar, a
* failed read of the offline database surfaces instead of rendering as "nothing
* cached", and a trip the user switches on is pinned so the date rule cannot
* quietly refuse to store it.
*/
import { useCallback, useEffect, useState } from 'react'
import { offlineDb, clearAll, clearTripData } from '../../db/offlineDb'
import { tripsApi } from '../../api/client'
import { tripSyncManager, isDateEligible, type PrepareProgress, type SyncOutcome } from '../../sync/tripSyncManager'
import { mutationQueue } from '../../sync/mutationQueue'
import { clearTileCache } from '../../sync/tilePrefetcher'
import { isEffectivelyOffline } from '../../sync/networkMode'
import {
getOfflinePrefs, setCacheTiles, setConflictStrategy,
setTripOfflineEnabled, setTripPinned, onOfflinePrefsChange,
type ConflictStrategy,
} from '../../sync/offlinePrefs'
import { useNetworkMode } from '../../hooks/useNetworkMode'
import type { SyncMeta, QueuedMutation } from '../../db/offlineDb'
import type { Trip } from '../../types'
export interface CachedTripRow {
trip: Trip
meta: SyncMeta
placeCount: number
fileCount: number
}
/** How a trip's storage switch should read, and why. */
export interface TripStorageState {
/** The switch position: is this trip kept on the device? */
on: boolean
/** The user asked for it explicitly, overriding the date rule. */
pinned: boolean
/** The date rule would keep it on its own (ongoing, future, or open-ended). */
dateEligible: boolean
}
/**
* The last thing a download / re-sync run did. `null` while nothing has been
* run yet. The screen shows no banner in that state.
*/
export type OfflineNotice =
| { kind: 'stored'; trips: number }
| { kind: 'skipped'; reason: 'busy' | 'offline' | 'signed-out' }
| { kind: 'sync-failed' }
| { kind: 'load-failed' }
/**
* The message a notice reads as. Shared so both shells say the same thing and
* only the chrome around it differs.
*/
export function offlineNoticeKey(notice: OfflineNotice): string {
if (notice.kind === 'load-failed') return 'settings.offline.notice.loadFailed'
if (notice.kind === 'sync-failed') return 'settings.offline.notice.failed'
if (notice.kind === 'skipped') {
if (notice.reason === 'busy') return 'settings.offline.notice.busy'
if (notice.reason === 'offline') return 'settings.offline.notice.offline'
return 'settings.offline.notice.signedOut'
}
return notice.trips > 0 ? 'settings.offline.notice.stored' : 'settings.offline.notice.nothing'
}
/** A notice that reports a problem rather than a result. */
export function isOfflineNoticeWarning(notice: OfflineNotice): boolean {
return notice.kind !== 'stored' || notice.trips === 0
}
function noticeFor(outcome: SyncOutcome): OfflineNotice {
return outcome.status === 'done'
? { kind: 'stored', trips: outcome.trips }
: { kind: 'skipped', reason: outcome.reason }
}
export function useOfflineSettings() {
const { offline, forced, setForced } = useNetworkMode()
const [rows, setRows] = useState<CachedTripRow[]>([])
const [allTrips, setAllTrips] = useState<Trip[]>([])
const [storedTripCount, setStoredTripCount] = useState(0)
const [pendingCount, setPendingCount] = useState(0)
const [failedCount, setFailedCount] = useState(0)
const [conflicts, setConflicts] = useState<QueuedMutation[]>([])
const [syncing, setSyncing] = useState(false)
const [clearing, setClearing] = useState(false)
const [loading, setLoading] = useState(true)
const [preparing, setPreparing] = useState(false)
const [progress, setProgress] = useState<PrepareProgress | null>(null)
const [notice, setNotice] = useState<OfflineNotice | null>(null)
const [prefs, setPrefs] = useState(getOfflinePrefs())
useEffect(() => onOfflinePrefsChange(() => setPrefs(getOfflinePrefs())), [])
const load = useCallback(async () => {
setLoading(true)
try {
const [metas, storedTrips, pending, failed, conflictList] = await Promise.all([
offlineDb.syncMeta.toArray(),
offlineDb.trips.count(),
mutationQueue.pendingCount(),
mutationQueue.failedCount(),
mutationQueue.conflicts(),
])
setStoredTripCount(storedTrips)
setPendingCount(pending)
setFailedCount(failed)
setConflicts(conflictList)
const result: CachedTripRow[] = []
for (const meta of metas) {
const trip = await offlineDb.trips.get(meta.tripId)
if (!trip) continue
const [placeCount, fileCount] = await Promise.all([
offlineDb.places.where('trip_id').equals(meta.tripId).count(),
offlineDb.tripFiles.where('trip_id').equals(meta.tripId).count(),
])
result.push({ trip, meta, placeCount, fileCount })
}
result.sort((a, b) => (a.trip.start_date ?? '').localeCompare(b.trip.start_date ?? ''))
setRows(result)
// The per-trip storage toggles are driven by the FULL trip list, not just
// the cached ones, so a trip turned off stays visible and re-enableable.
try {
const trips = isEffectivelyOffline()
? await offlineDb.trips.toArray()
: await tripsApi.list().then(r => (r as { trips: Trip[] }).trips).catch(() => offlineDb.trips.toArray())
trips.sort((a, b) => (a.start_date ?? '').localeCompare(b.start_date ?? ''))
setAllTrips(trips)
} catch {
setAllTrips([])
}
} catch (err) {
// A Dexie read that rejects (a closed handle, a failed upgrade) used to
// leave every list at its initial empty value, so a broken offline
// database was indistinguishable from an empty one: the screen read
// "No trips cached yet" and gave the user nothing to act on (#2228).
console.error('[offline] could not read the offline database:', err)
setNotice({ kind: 'load-failed' })
} finally {
setLoading(false)
}
}, [])
useEffect(() => { load() }, [load])
const runPrepare = useCallback(async () => {
setPreparing(true)
setProgress(null)
setNotice(null)
try {
const outcome = await tripSyncManager.prepareForOffline(p => setProgress(p))
setNotice(noticeFor(outcome))
// A run that never started never reported progress either; clearing it
// keeps the bar from painting "finished" over a download that did not
// happen.
if (outcome.status !== 'done') setProgress(null)
} catch (err) {
// The trip list this starts from is a plain fetch, so a network blip
// rejects the whole run. Reporting that beats leaving the last progress
// frame on screen as if the download had completed.
console.error('[offline] the download could not finish:', err)
setProgress(null)
setNotice({ kind: 'sync-failed' })
} finally {
setPreparing(false)
}
await load()
}, [load])
const handleToggleForce = useCallback(async () => {
if (!forced) {
// Turning offline mode on: download everything first (while still online),
// then engage so the app has all it needs before the network drops.
if (!isEffectivelyOffline()) await runPrepare()
setForced(true)
} else {
// Back online: lifting the switch flushes the queue + re-syncs (syncTriggers).
setForced(false)
}
}, [forced, runPrepare, setForced])
const handleResync = useCallback(async () => {
setSyncing(true)
setNotice(null)
try {
setNotice(noticeFor(await tripSyncManager.syncAll()))
} catch (err) {
console.error('[offline] the sync could not finish:', err)
setNotice({ kind: 'sync-failed' })
} finally {
setSyncing(false)
}
await load()
}, [load])
/** Wipes the offline database. Each shell asks for confirmation its own way. */
const handleClear = useCallback(async () => {
setClearing(true)
try {
await clearAll()
setNotice(null)
await load()
} finally {
setClearing(false)
}
}, [load])
const handleToggleTiles = useCallback(async () => {
const next = !prefs.cacheTiles
setCacheTiles(next)
// Turning tiles off reclaims the bulk tile storage straight away.
if (!next) await clearTileCache()
}, [prefs.cacheTiles])
/**
* How a trip's switch should read. A finished trip is only stored when the
* user pinned it, so reporting the raw opt-out flag would show "on" over a
* trip the sync deliberately skips, which is what made the whole feature
* look broken for anyone whose trips are all in the past (#2228).
*/
const tripStorageState = useCallback((trip: Trip): TripStorageState => {
const dateEligible = isDateEligible(trip)
const pinned = prefs.pinnedTripIds.includes(trip.id)
const allowed = !prefs.disabledTripIds.includes(trip.id)
return { on: allowed && (pinned || dateEligible), pinned, dateEligible }
}, [prefs.pinnedTripIds, prefs.disabledTripIds])
const handleToggleTrip = useCallback(async (trip: Trip) => {
const next = !tripStorageState(trip).on
setTripOfflineEnabled(trip.id, next)
// Switching a finished trip on has to pin it, or the date rule would skip
// it on the next sync and evict it a week after it ended.
setTripPinned(trip.id, next && !isDateEligible(trip))
if (!next) {
await clearTripData(trip.id)
await load()
return
}
if (isEffectivelyOffline()) {
setNotice({ kind: 'skipped', reason: 'offline' })
return
}
try {
setNotice(noticeFor(await tripSyncManager.syncAll()))
} catch (err) {
console.error('[offline] the sync could not finish:', err)
setNotice({ kind: 'sync-failed' })
}
await load()
}, [load, tripStorageState])
const resolveConflict = useCallback(async (id: string, keepMine: boolean) => {
if (keepMine) await mutationQueue.resolveKeepMine(id)
else await mutationQueue.resolveKeepServer(id)
await load()
}, [load])
const handleConflictStrategy = useCallback((strategy: ConflictStrategy) => {
setConflictStrategy(strategy)
}, [])
return {
offline, forced,
rows, allTrips, pendingCount, failedCount, conflicts,
syncing, clearing, loading, preparing, progress, notice, prefs, storedTripCount,
// Clearable once the database actually holds something, not only once a
// sync wrote its bookkeeping row: a download that died between writing the
// trip and writing its syncMeta left `rows` empty over a non-empty Dexie,
// and the clear button was disabled on exactly the state that needed it.
canClear: storedTripCount > 0 || pendingCount > 0,
load, runPrepare, handleToggleForce, handleResync, handleClear,
handleToggleTiles, tripStorageState, handleToggleTrip, resolveConflict,
handleConflictStrategy,
}
}