feat(offline): make the web UI usable without a reachable backend
Three tiers of offline support, all scoped to the active backend's localStorage namespace (mirroring the auth slice): Tier 1 — persist client state. queue + player slices are saved (queue entries/index/source; player track/position/volume/repeat/shuffle) and rehydrated on load, so a reload with no backend restores where the user left off. Playback never auto-resumes (browsers block autoplay). Retires the DEMO_QUEUE and isQueueOpen:true stubs. Tier 2 — persist the RTK Query cache. Last-seen library/albums/artists are snapshotted (fulfilled queries only) and replayed via RTKQ's extractRehydrationInfo at startup, so the library renders read-only when the backend is down. ConnectionStatus tooltip flags cached data offline. No server data is copied into a slice — the cache feeds itself back. Tier 3 — service worker audio + cover cache (PWA). Audio streams are cached keyed by content id (token stripped), range-aware (synthetic 206 slicing), with a 500MB LRU cap, so already-played tracks play fully offline. Cover art uses stale-while-revalidate in its own bounded cache. Module worker (ESM); pure helpers split into sw-core.js and unit-tested. Web app manifest enables "Install app". Player source badge now reflects real cached state. tsc clean, lint clean, 19 new tests pass, production build verified. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -4,6 +4,8 @@ import authReducer from './slices/auth';
|
||||
import playerReducer from './slices/player';
|
||||
import queueReducer from './slices/queue';
|
||||
import uiReducer from './slices/ui';
|
||||
import { loadPlayerState, loadQueueState, startPersistence } from './persist';
|
||||
import { rehydrateApiCache, startApiPersistence } from './rtkqPersist';
|
||||
|
||||
export const store = configureStore({
|
||||
reducer: {
|
||||
@@ -13,9 +15,23 @@ export const store = configureStore({
|
||||
queue: queueReducer,
|
||||
ui: uiReducer,
|
||||
},
|
||||
// Tier 1 offline: rehydrate queue/player from the active backend's namespace
|
||||
// so a reload (even with no backend) restores exactly where the user left off.
|
||||
preloadedState: {
|
||||
queue: loadQueueState(),
|
||||
player: loadPlayerState(),
|
||||
},
|
||||
middleware: (getDefaultMiddleware) =>
|
||||
getDefaultMiddleware().concat(api.middleware),
|
||||
});
|
||||
|
||||
// Flush queue/player changes back to localStorage (throttled).
|
||||
startPersistence(store);
|
||||
|
||||
// Tier 2 offline: replay the last-seen RTKQ cache, then keep snapshotting it.
|
||||
// Rehydrate first so cached server data is present before any component mounts.
|
||||
rehydrateApiCache(store.dispatch);
|
||||
startApiPersistence(store);
|
||||
|
||||
export type RootState = ReturnType<typeof store.getState>;
|
||||
export type AppDispatch = typeof store.dispatch;
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Tier 1 offline support: persist client state (queue + player) to the active
|
||||
* backend's localStorage namespace, mirroring the auth slice. This is what lets
|
||||
* the UI come back exactly as the user left it after a reload with no backend
|
||||
* reachable — no server data is duplicated (the queue stores track IDs + minimal
|
||||
* display fields only; full track records still live in the RTKQ cache).
|
||||
*
|
||||
* Server data (library/albums/…) is Tier 2 (see `rtkqPersist.ts`).
|
||||
*/
|
||||
import { instanceStorage } from '../config/instances';
|
||||
import {
|
||||
queueInitialState,
|
||||
type QueueState,
|
||||
} from './slices/queue';
|
||||
import {
|
||||
playerInitialState,
|
||||
type PlayerState,
|
||||
} from './slices/player';
|
||||
import type { RootState } from './index';
|
||||
|
||||
const QUEUE_KEY = 'queue';
|
||||
const PLAYER_KEY = 'player';
|
||||
|
||||
// Only persist fields that make sense to restore. `duration`/`isPlaying` are
|
||||
// derived from the <audio> element on next load, and the panel toggles are
|
||||
// transient UI, so they are intentionally left out.
|
||||
type PersistedQueue = Pick<
|
||||
QueueState,
|
||||
'entries' | 'currentIndex' | 'source' | 'sourceId' | 'sourceName'
|
||||
>;
|
||||
type PersistedPlayer = Pick<
|
||||
PlayerState,
|
||||
'currentTrackId' | 'position' | 'volume' | 'muted' | 'repeat' | 'shuffle'
|
||||
>;
|
||||
|
||||
function pickQueue(state: QueueState): PersistedQueue {
|
||||
return {
|
||||
entries: state.entries,
|
||||
currentIndex: state.currentIndex,
|
||||
source: state.source,
|
||||
sourceId: state.sourceId,
|
||||
sourceName: state.sourceName,
|
||||
};
|
||||
}
|
||||
|
||||
function pickPlayer(state: PlayerState): PersistedPlayer {
|
||||
return {
|
||||
currentTrackId: state.currentTrackId,
|
||||
position: state.position,
|
||||
volume: state.volume,
|
||||
muted: state.muted,
|
||||
repeat: state.repeat,
|
||||
shuffle: state.shuffle,
|
||||
};
|
||||
}
|
||||
|
||||
function read<T>(key: string): Partial<T> | null {
|
||||
try {
|
||||
const raw = instanceStorage.get(key);
|
||||
return raw ? (JSON.parse(raw) as Partial<T>) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Build the queue slice's initial state, restoring any persisted queue. */
|
||||
export function loadQueueState(): QueueState {
|
||||
const persisted = read<PersistedQueue>(QUEUE_KEY);
|
||||
if (!persisted) return queueInitialState;
|
||||
const merged: QueueState = { ...queueInitialState, ...persisted };
|
||||
// Guard the index against a corrupted/short entries array.
|
||||
if (
|
||||
merged.currentIndex >= merged.entries.length ||
|
||||
merged.currentIndex < -1
|
||||
) {
|
||||
merged.currentIndex = merged.entries.length ? 0 : -1;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/** Build the player slice's initial state, restoring any persisted player. */
|
||||
export function loadPlayerState(): PlayerState {
|
||||
const persisted = read<PersistedPlayer>(PLAYER_KEY);
|
||||
if (!persisted) return playerInitialState;
|
||||
// Never auto-resume playback on load: browsers block autoplay and the
|
||||
// <audio> element starts paused regardless. isPlaying stays false.
|
||||
return { ...playerInitialState, ...persisted, isPlaying: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe a store so queue/player changes are flushed to localStorage. The
|
||||
* write is throttled because `setPosition` fires several times a second during
|
||||
* playback — without throttling we'd hammer localStorage on every tick.
|
||||
*/
|
||||
export function startPersistence(store: {
|
||||
getState: () => RootState;
|
||||
subscribe: (listener: () => void) => () => void;
|
||||
}): () => void {
|
||||
const initial = store.getState();
|
||||
let lastQueue = JSON.stringify(pickQueue(initial.queue));
|
||||
let lastPlayer = JSON.stringify(pickPlayer(initial.player));
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const flush = () => {
|
||||
timer = null;
|
||||
const state = store.getState();
|
||||
const queueSnapshot = JSON.stringify(pickQueue(state.queue));
|
||||
if (queueSnapshot !== lastQueue) {
|
||||
instanceStorage.set(QUEUE_KEY, queueSnapshot);
|
||||
lastQueue = queueSnapshot;
|
||||
}
|
||||
const playerSnapshot = JSON.stringify(pickPlayer(state.player));
|
||||
if (playerSnapshot !== lastPlayer) {
|
||||
instanceStorage.set(PLAYER_KEY, playerSnapshot);
|
||||
lastPlayer = playerSnapshot;
|
||||
}
|
||||
};
|
||||
|
||||
return store.subscribe(() => {
|
||||
if (timer) return;
|
||||
timer = setTimeout(flush, 1000);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Tier 2 offline support: persist the RTK Query cache (last-seen server data —
|
||||
* library/albums/artists/…) to the active backend's localStorage namespace and
|
||||
* replay it into the cache on startup. With the backend down, components keep
|
||||
* rendering the last-known data read-only instead of an error state.
|
||||
*
|
||||
* Per the architecture invariant, server data is NOT copied into a slice: this
|
||||
* snapshots the RTKQ cache itself and feeds it back through RTKQ's own
|
||||
* `extractRehydrationInfo` mechanism (see `api/index.ts`).
|
||||
*/
|
||||
import { instanceStorage } from '../config/instances';
|
||||
import { rehydrateApi, type RehydrateApiPayload } from '../api/rehydrate';
|
||||
import type { RootState } from './index';
|
||||
|
||||
const CACHE_KEY = 'rtkq';
|
||||
|
||||
type ApiState = RootState['api'];
|
||||
type QueryEntry = ApiState['queries'][string];
|
||||
|
||||
/**
|
||||
* Keep only successfully-fulfilled query results — pending/rejected entries
|
||||
* carry no usable data and subscriptions are rebuilt by components on mount.
|
||||
* Mutation results are never restored.
|
||||
*/
|
||||
function snapshot(apiState: ApiState): RehydrateApiPayload {
|
||||
const queries: Record<string, unknown> = {};
|
||||
for (const [key, entry] of Object.entries(apiState.queries)) {
|
||||
const q = entry as QueryEntry | undefined;
|
||||
if (q && q.status === 'fulfilled') queries[key] = q;
|
||||
}
|
||||
return { queries, mutations: {} };
|
||||
}
|
||||
|
||||
function load(): RehydrateApiPayload | null {
|
||||
try {
|
||||
const raw = instanceStorage.get(CACHE_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as Partial<RehydrateApiPayload>;
|
||||
if (!parsed.queries) return null;
|
||||
return { queries: parsed.queries, mutations: {} };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Replay the persisted cache into RTKQ. Call once after the store is created. */
|
||||
export function rehydrateApiCache(dispatch: (action: unknown) => void): void {
|
||||
const cached = load();
|
||||
if (cached) dispatch(rehydrateApi(cached));
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe a store so the RTKQ cache is flushed to localStorage. Throttled,
|
||||
* since cache state churns on every in-flight query transition.
|
||||
*/
|
||||
export function startApiPersistence(store: {
|
||||
getState: () => RootState;
|
||||
subscribe: (listener: () => void) => () => void;
|
||||
}): () => void {
|
||||
let last = '';
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const flush = () => {
|
||||
timer = null;
|
||||
const snap = JSON.stringify(snapshot(store.getState().api));
|
||||
if (snap !== last) {
|
||||
instanceStorage.set(CACHE_KEY, snap);
|
||||
last = snap;
|
||||
}
|
||||
};
|
||||
|
||||
return store.subscribe(() => {
|
||||
if (timer) return;
|
||||
timer = setTimeout(flush, 2000);
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { createSlice, type PayloadAction } from '@reduxjs/toolkit';
|
||||
|
||||
type RepeatMode = 'none' | 'one' | 'all';
|
||||
export type RepeatMode = 'none' | 'one' | 'all';
|
||||
|
||||
interface PlayerState {
|
||||
export interface PlayerState {
|
||||
currentTrackId: string | null;
|
||||
isPlaying: boolean;
|
||||
position: number;
|
||||
@@ -15,7 +15,7 @@ interface PlayerState {
|
||||
isQueueOpen: boolean;
|
||||
}
|
||||
|
||||
const initialState: PlayerState = {
|
||||
export const playerInitialState: PlayerState = {
|
||||
currentTrackId: null,
|
||||
isPlaying: false,
|
||||
position: 0,
|
||||
@@ -25,14 +25,12 @@ const initialState: PlayerState = {
|
||||
repeat: 'none',
|
||||
shuffle: false,
|
||||
isNowPlayingOpen: false,
|
||||
// STUB: open by default so the queue drawer look is visible before a backend
|
||||
// exists (pairs with DEMO_QUEUE). Default to false once real playback lands.
|
||||
isQueueOpen: true,
|
||||
isQueueOpen: false,
|
||||
};
|
||||
|
||||
export const playerSlice = createSlice({
|
||||
name: 'player',
|
||||
initialState,
|
||||
initialState: playerInitialState,
|
||||
reducers: {
|
||||
play(state, action: PayloadAction<string>) {
|
||||
state.currentTrackId = action.payload;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createSlice, type PayloadAction } from '@reduxjs/toolkit';
|
||||
|
||||
type QueueSource =
|
||||
export type QueueSource =
|
||||
| 'manual'
|
||||
| 'album'
|
||||
| 'playlist'
|
||||
@@ -8,7 +8,7 @@ type QueueSource =
|
||||
| 'search'
|
||||
| 'radio';
|
||||
|
||||
interface QueueEntry {
|
||||
export interface QueueEntry {
|
||||
trackId: string;
|
||||
title: string;
|
||||
artistName: string;
|
||||
@@ -17,7 +17,7 @@ interface QueueEntry {
|
||||
albumArtUrl?: string;
|
||||
}
|
||||
|
||||
interface QueueState {
|
||||
export interface QueueState {
|
||||
entries: QueueEntry[];
|
||||
currentIndex: number;
|
||||
source: QueueSource;
|
||||
@@ -25,52 +25,17 @@ interface QueueState {
|
||||
sourceName: string | null;
|
||||
}
|
||||
|
||||
// STUB demo queue — purely client-side display data so the player bar and
|
||||
// queue drawer render with content before the backend exists. Delete this
|
||||
// block (reset entries/currentIndex/source to the empty values) once real
|
||||
// playback wires tracks into the queue.
|
||||
const DEMO_QUEUE: QueueEntry[] = [
|
||||
{
|
||||
trackId: 'd1',
|
||||
title: 'Quiet Storage',
|
||||
artistName: 'Cyan Atlas',
|
||||
albumTitle: 'Night Index',
|
||||
durationMs: 312_000,
|
||||
},
|
||||
{
|
||||
trackId: 'd2',
|
||||
title: 'Magnetic North',
|
||||
artistName: 'Tidal Bloom',
|
||||
albumTitle: 'Ferric Coast',
|
||||
durationMs: 243_000,
|
||||
},
|
||||
{
|
||||
trackId: 'd3',
|
||||
title: 'Ambergris',
|
||||
artistName: 'Møller',
|
||||
albumTitle: 'Warm Static',
|
||||
durationMs: 201_000,
|
||||
},
|
||||
{
|
||||
trackId: 'd4',
|
||||
title: 'Slow Carrier',
|
||||
artistName: 'Tidal Bloom',
|
||||
albumTitle: 'Ferric Coast',
|
||||
durationMs: 301_000,
|
||||
},
|
||||
];
|
||||
|
||||
const initialState: QueueState = {
|
||||
entries: DEMO_QUEUE,
|
||||
currentIndex: 0,
|
||||
source: 'radio',
|
||||
export const queueInitialState: QueueState = {
|
||||
entries: [],
|
||||
currentIndex: -1,
|
||||
source: 'manual',
|
||||
sourceId: null,
|
||||
sourceName: 'My radio',
|
||||
sourceName: null,
|
||||
};
|
||||
|
||||
export const queueSlice = createSlice({
|
||||
name: 'queue',
|
||||
initialState,
|
||||
initialState: queueInitialState,
|
||||
reducers: {
|
||||
setQueue(
|
||||
state,
|
||||
|
||||
Reference in New Issue
Block a user