feat(ui): persist user settings and audio position across sessions
- Replace double inline player controls with compact 'now playing' indicator when mini-bar is active - Add user_settings PocketBase collection (auto_next, voice, speed) and audio_time field on progress - Add getSettings/saveSettings/setAudioTime/getAudioTime server functions - Add GET/PUT /api/settings and GET/PATCH /api/progress/audio-time API routes - Load settings server-side in layout and apply to audioStore on mount - Debounced 800ms effect persists settings changes to DB - Save audio currentTime on pause/end; restore position when replaying a chapter
This commit is contained in:
@@ -138,6 +138,8 @@
|
||||
if (url) {
|
||||
audioStore.audioUrl = url;
|
||||
audioStore.status = 'ready';
|
||||
// Restore last saved position after the audio element loads
|
||||
restoreSavedAudioTime();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -158,6 +160,7 @@
|
||||
if (!url2) throw new Error('Audio generated but presign returned 404');
|
||||
audioStore.audioUrl = url2;
|
||||
audioStore.status = 'ready';
|
||||
// Don't restore time for freshly generated audio — position is 0
|
||||
} catch (e) {
|
||||
stopProgress();
|
||||
audioStore.progress = 0;
|
||||
@@ -166,6 +169,27 @@
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the saved audio time for this chapter and seek to it after a short
|
||||
* delay (to allow the audio element to load the source).
|
||||
*/
|
||||
async function restoreSavedAudioTime() {
|
||||
try {
|
||||
const params = new URLSearchParams({ slug, chapter: String(chapter) });
|
||||
const res = await fetch(`/api/progress/audio-time?${params}`);
|
||||
if (!res.ok) return;
|
||||
const data = (await res.json()) as { audioTime: number | null };
|
||||
if (data.audioTime && data.audioTime > 5) {
|
||||
// Small delay to let the <audio> element fully load the src before seeking
|
||||
setTimeout(() => {
|
||||
audioStore.seekRequest = data.audioTime as number;
|
||||
}, 300);
|
||||
}
|
||||
} catch {
|
||||
// Non-critical — silently ignore
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePlay() {
|
||||
const isCurrent = audioStore.isCurrentChapter(slug, chapter);
|
||||
|
||||
@@ -237,62 +261,44 @@
|
||||
<p class="text-xs text-zinc-500 tabular-nums">{Math.round(audioStore.progress)}%</p>
|
||||
</div>
|
||||
|
||||
{:else if audioStore.status === 'ready'}
|
||||
<!-- Inline full-size controls (larger than the mini-bar) -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<!-- Seek bar -->
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max={audioStore.duration || 0}
|
||||
value={audioStore.currentTime}
|
||||
oninput={(e) => {
|
||||
audioStore.seekRequest = parseFloat((e.target as HTMLInputElement).value);
|
||||
}}
|
||||
class="w-full accent-amber-400 h-1.5 rounded cursor-pointer"
|
||||
/>
|
||||
|
||||
<div class="flex items-center gap-3">
|
||||
<!-- Play/Pause -->
|
||||
<button
|
||||
onclick={handlePlay}
|
||||
class="w-9 h-9 rounded-full bg-amber-400 text-zinc-900 flex items-center justify-center hover:bg-amber-300 transition-colors flex-shrink-0"
|
||||
aria-label={audioStore.isPlaying ? 'Pause' : 'Play'}
|
||||
>
|
||||
{#if audioStore.isPlaying}
|
||||
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/>
|
||||
</svg>
|
||||
{:else}
|
||||
<svg class="w-4 h-4 ml-0.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z"/>
|
||||
</svg>
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
<span class="text-xs text-zinc-400 tabular-nums flex-1">
|
||||
{formatTime(audioStore.currentTime)} / {formatTime(audioStore.duration)}
|
||||
</span>
|
||||
|
||||
<!-- Auto-next toggle (inline, only visible when there is a next chapter) -->
|
||||
{#if nextChapter !== null && nextChapter !== undefined}
|
||||
<button
|
||||
onclick={() => (audioStore.autoNext = !audioStore.autoNext)}
|
||||
class="flex items-center gap-1.5 px-2 py-1 rounded text-xs font-medium transition-colors flex-shrink-0 {audioStore.autoNext
|
||||
? 'text-amber-400 bg-amber-400/15 hover:bg-amber-400/25'
|
||||
: 'text-zinc-500 bg-zinc-700 hover:bg-zinc-600 hover:text-zinc-200'}"
|
||||
title={audioStore.autoNext ? 'Auto-next on — will play Ch.{nextChapter} automatically' : 'Auto-next off'}
|
||||
aria-pressed={audioStore.autoNext}
|
||||
>
|
||||
<svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 18l8.5-6L6 6v12zm8.5-6L23 6v12l-8.5-6z"/>
|
||||
</svg>
|
||||
Auto
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if audioStore.status === 'ready'}
|
||||
<!-- Mini-bar is the canonical control surface — show a compact indicator here -->
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2 text-xs text-zinc-400">
|
||||
{#if audioStore.isPlaying}
|
||||
<svg class="w-3.5 h-3.5 text-amber-400 flex-shrink-0" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/>
|
||||
</svg>
|
||||
<span>Playing — controls below</span>
|
||||
{:else}
|
||||
<svg class="w-3.5 h-3.5 flex-shrink-0 ml-0.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z"/>
|
||||
</svg>
|
||||
<span>Paused — controls below</span>
|
||||
{/if}
|
||||
<span class="tabular-nums text-zinc-500">
|
||||
{formatTime(audioStore.currentTime)} / {formatTime(audioStore.duration)}
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Auto-next toggle (keep here as useful context) -->
|
||||
{#if nextChapter !== null && nextChapter !== undefined}
|
||||
<button
|
||||
onclick={() => (audioStore.autoNext = !audioStore.autoNext)}
|
||||
class="flex items-center gap-1.5 px-2 py-1 rounded text-xs font-medium transition-colors flex-shrink-0 {audioStore.autoNext
|
||||
? 'text-amber-400 bg-amber-400/15 hover:bg-amber-400/25'
|
||||
: 'text-zinc-500 bg-zinc-700 hover:bg-zinc-600 hover:text-zinc-200'}"
|
||||
title={audioStore.autoNext ? `Auto-next on — will play Ch.${nextChapter} automatically` : 'Auto-next off'}
|
||||
aria-pressed={audioStore.autoNext}
|
||||
>
|
||||
<svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 18l8.5-6L6 6v12zm8.5-6L23 6v12l-8.5-6z"/>
|
||||
</svg>
|
||||
Auto
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{:else if audioStore.active}
|
||||
<!-- ── A different chapter is currently playing ── -->
|
||||
|
||||
@@ -42,9 +42,20 @@ export interface Progress {
|
||||
user_id?: string;
|
||||
slug: string;
|
||||
chapter: number;
|
||||
audio_time?: number;
|
||||
updated: string;
|
||||
}
|
||||
|
||||
export interface UserSettings {
|
||||
id?: string;
|
||||
session_id: string;
|
||||
user_id?: string;
|
||||
auto_next: boolean;
|
||||
voice: string;
|
||||
speed: number;
|
||||
updated?: string;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
@@ -395,3 +406,102 @@ export async function loginUser(username: string, password: string): Promise<Use
|
||||
log.info('pocketbase', 'loginUser: success', { username, role: user.role });
|
||||
return user;
|
||||
}
|
||||
|
||||
// ─── User settings ────────────────────────────────────────────────────────────
|
||||
|
||||
function settingsFilter(sessionId: string, userId?: string): string {
|
||||
if (userId) return `user_id="${userId}"`;
|
||||
return `session_id="${sessionId}"`;
|
||||
}
|
||||
|
||||
export async function getSettings(
|
||||
sessionId: string,
|
||||
userId?: string
|
||||
): Promise<UserSettings | null> {
|
||||
return listOne<UserSettings>('user_settings', settingsFilter(sessionId, userId));
|
||||
}
|
||||
|
||||
export async function saveSettings(
|
||||
sessionId: string,
|
||||
settings: { autoNext: boolean; voice: string; speed: number },
|
||||
userId?: string
|
||||
): Promise<void> {
|
||||
const existing = await listOne<UserSettings & { id: string }>(
|
||||
'user_settings',
|
||||
settingsFilter(sessionId, userId)
|
||||
);
|
||||
|
||||
const payload: Partial<UserSettings> = {
|
||||
session_id: sessionId,
|
||||
auto_next: settings.autoNext,
|
||||
voice: settings.voice,
|
||||
speed: settings.speed,
|
||||
updated: new Date().toISOString()
|
||||
};
|
||||
if (userId) payload.user_id = userId;
|
||||
|
||||
if (existing) {
|
||||
const res = await pbPatch(`/api/collections/user_settings/records/${existing.id}`, payload);
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '');
|
||||
log.error('pocketbase', 'saveSettings PATCH failed', { status: res.status, body });
|
||||
}
|
||||
} else {
|
||||
const res = await pbPost('/api/collections/user_settings/records', payload);
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '');
|
||||
log.error('pocketbase', 'saveSettings POST failed', { status: res.status, body });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Audio time ───────────────────────────────────────────────────────────────
|
||||
|
||||
export async function setAudioTime(
|
||||
sessionId: string,
|
||||
slug: string,
|
||||
chapter: number,
|
||||
audioTime: number,
|
||||
userId?: string
|
||||
): Promise<void> {
|
||||
const existing = await listOne<Progress & { id: string }>(
|
||||
'progress',
|
||||
progressFilter(sessionId, slug, userId)
|
||||
);
|
||||
if (!existing) {
|
||||
// No progress record yet — create one with audio_time
|
||||
const payload: Partial<Progress> = {
|
||||
session_id: sessionId,
|
||||
slug,
|
||||
chapter,
|
||||
audio_time: audioTime,
|
||||
updated: new Date().toISOString()
|
||||
};
|
||||
if (userId) payload.user_id = userId;
|
||||
const res = await pbPost('/api/collections/progress/records', payload);
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '');
|
||||
log.error('pocketbase', 'setAudioTime POST failed', { slug, chapter, status: res.status, body });
|
||||
}
|
||||
return;
|
||||
}
|
||||
const res = await pbPatch(`/api/collections/progress/records/${existing.id}`, {
|
||||
audio_time: audioTime,
|
||||
updated: new Date().toISOString()
|
||||
});
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '');
|
||||
log.error('pocketbase', 'setAudioTime PATCH failed', { slug, chapter, status: res.status, body });
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAudioTime(
|
||||
sessionId: string,
|
||||
slug: string,
|
||||
chapter: number,
|
||||
userId?: string
|
||||
): Promise<number | null> {
|
||||
const row = await listOne<Progress>('progress', progressFilter(sessionId, slug, userId));
|
||||
if (!row || !row.audio_time) return null;
|
||||
return row.audio_time;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user