v1.0.2: Mood mix optimizations and media player improvements

- Fixed player seek flicker on podcasts (30s skip buttons)
- Added dual-layer seek lock mechanism to prevent stale time updates
- Optimized cached podcast seeking (direct seek before reload fallback)
- Large skips now execute immediately for responsive feel
- Mood mix performance optimizations
This commit is contained in:
Kevin O'Neill
2025-12-26 13:06:17 -06:00
parent d8c608cf70
commit f8b464feec
28 changed files with 5328 additions and 1615 deletions

View File

@@ -32,7 +32,10 @@ const MixCard = memo(
{mix.coverUrls.length > 0 ? (
<div className="grid grid-cols-2 gap-0 w-full h-full">
{mix.coverUrls.slice(0, 4).map((url, idx) => {
const proxiedUrl = api.getCoverArtUrl(url, 300);
const proxiedUrl = api.getCoverArtUrl(
url,
300
);
return (
<div
key={idx}
@@ -51,7 +54,10 @@ const MixCard = memo(
})}
{/* Fill remaining cells if less than 4 covers */}
{Array.from({
length: Math.max(0, 4 - mix.coverUrls.length),
length: Math.max(
0,
4 - mix.coverUrls.length
),
}).map((_, idx) => (
<div
key={`empty-${idx}`}
@@ -79,7 +85,18 @@ const MixCard = memo(
);
},
(prevProps, nextProps) => {
return prevProps.mix.id === nextProps.mix.id;
// Compare id, name, description, trackCount, and coverUrls to detect content changes
// This ensures the card re-renders when mood mix content changes even if ID is the same
return (
prevProps.mix.id === nextProps.mix.id &&
prevProps.mix.name === nextProps.mix.name &&
prevProps.mix.description === nextProps.mix.description &&
prevProps.mix.trackCount === nextProps.mix.trackCount &&
prevProps.mix.coverUrls.length === nextProps.mix.coverUrls.length &&
prevProps.mix.coverUrls.every(
(url, i) => url === nextProps.mix.coverUrls[i]
)
);
}
);

View File

@@ -1,10 +1,25 @@
"use client";
import { useState, useEffect } from "react";
import { api, MoodPreset, MoodMixParams } from "@/lib/api";
import { api, MoodType, MoodBucketPreset } from "@/lib/api";
import { useAudioControls } from "@/lib/audio-controls-context";
import { Track } from "@/lib/audio-state-context";
import { Play, Loader2, AudioWaveform, Sliders, X, ChevronDown, ChevronUp } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import {
Play,
Loader2,
AudioWaveform,
X,
Smile,
Frown,
Coffee,
Zap,
PartyPopper,
Brain,
CloudRain,
Flame,
Guitar,
} from "lucide-react";
import { toast } from "sonner";
interface MoodMixerProps {
@@ -12,46 +27,92 @@ interface MoodMixerProps {
onClose: () => void;
}
// Mood configuration with icons and colors
const MOOD_CONFIG: Record<
MoodType,
{
icon: React.ComponentType<{ className?: string }>;
color: string;
label: string;
description: string;
}
> = {
happy: {
icon: Smile,
color: "from-yellow-500 to-orange-500",
label: "Happy",
description: "Uplifting & joyful",
},
sad: {
icon: Frown,
color: "from-blue-600 to-indigo-700",
label: "Sad",
description: "Melancholic & emotional",
},
chill: {
icon: Coffee,
color: "from-teal-500 to-cyan-600",
label: "Chill",
description: "Relaxed & mellow",
},
energetic: {
icon: Zap,
color: "from-orange-500 to-red-500",
label: "Energetic",
description: "High energy & pumped",
},
party: {
icon: PartyPopper,
color: "from-pink-500 to-purple-600",
label: "Party",
description: "Dance & celebrate",
},
focus: {
icon: Brain,
color: "from-emerald-500 to-green-600",
label: "Focus",
description: "Concentration & flow",
},
melancholy: {
icon: CloudRain,
color: "from-slate-500 to-gray-600",
label: "Melancholy",
description: "Bittersweet & reflective",
},
aggressive: {
icon: Flame,
color: "from-red-600 to-rose-700",
label: "Aggressive",
description: "Intense & powerful",
},
acoustic: {
icon: Guitar,
color: "from-amber-600 to-yellow-700",
label: "Acoustic",
description: "Organic & unplugged",
},
};
// Order for display in 3x3 grid
const MOOD_ORDER: MoodType[] = [
"happy",
"energetic",
"party",
"chill",
"focus",
"acoustic",
"melancholy",
"sad",
"aggressive",
];
export function MoodMixer({ isOpen, onClose }: MoodMixerProps) {
const { playTracks } = useAudioControls();
const [presets, setPresets] = useState<MoodPreset[]>([]);
const queryClient = useQueryClient();
const [presets, setPresets] = useState<MoodBucketPreset[]>([]);
const [loading, setLoading] = useState(true);
const [generating, setGenerating] = useState<string | null>(null);
const [showCustom, setShowCustom] = useState(false);
const [generating, setGenerating] = useState<MoodType | null>(null);
const [isVisible, setIsVisible] = useState(false);
const [showAdvanced, setShowAdvanced] = useState(false);
// Custom sliders state - basic audio features
const [customParams, setCustomParams] = useState<{
valence: [number, number];
energy: [number, number];
danceability: [number, number];
bpm: [number, number];
}>({
valence: [0, 100],
energy: [0, 100],
danceability: [0, 100],
bpm: [60, 180],
});
// ML mood sliders state (Advanced mode)
const [mlMoods, setMlMoods] = useState<{
moodHappy: [number, number];
moodSad: [number, number];
moodRelaxed: [number, number];
moodAggressive: [number, number];
moodParty: [number, number];
moodAcoustic: [number, number];
moodElectronic: [number, number];
}>({
moodHappy: [0, 100],
moodSad: [0, 100],
moodRelaxed: [0, 100],
moodAggressive: [0, 100],
moodParty: [0, 100],
moodAcoustic: [0, 100],
moodElectronic: [0, 100],
});
// Handle visibility animation
useEffect(() => {
@@ -67,7 +128,7 @@ export function MoodMixer({ isOpen, onClose }: MoodMixerProps) {
const loadPresets = async () => {
try {
const data = await api.getMoodPresets();
const data = await api.getMoodBucketPresets();
setPresets(data);
} catch (error) {
console.error("Failed to load mood presets:", error);
@@ -77,16 +138,16 @@ export function MoodMixer({ isOpen, onClose }: MoodMixerProps) {
}
};
const generateMix = async (preset: MoodPreset) => {
setGenerating(preset.id);
const generateMix = async (mood: MoodType) => {
const config = MOOD_CONFIG[mood];
setGenerating(mood);
try {
const mix = await api.generateMoodMix({
...preset.params,
limit: 15,
});
// Get the mix from pre-computed bucket (instant!)
const mix = await api.getMoodBucketMix(mood);
if (mix.tracks && mix.tracks.length > 0) {
const tracks: Track[] = mix.tracks.map((t: any) => ({
const tracks: Track[] = mix.tracks.map((t) => ({
id: t.id,
title: t.title,
artist: {
@@ -101,153 +162,61 @@ export function MoodMixer({ isOpen, onClose }: MoodMixerProps) {
duration: t.duration,
}));
// Start playback
playTracks(tracks, 0);
toast.success(`Your ${preset.name} Mix`, {
// Save as user's active mood mix
await api.saveMoodBucketMix(mood);
toast.success(`${config.label} Mix`, {
description: `Playing ${tracks.length} tracks`,
});
// Save these params as user's mood mix preferences (include preset name for mix title)
try {
await api.post('/mixes/mood/save-preferences', {
...preset.params,
limit: 15,
presetName: preset.name
});
} catch (err) {
console.error("Failed to save mood preferences:", err);
}
// Force immediate refetch of mixes on home page
// Using refetchQueries instead of invalidateQueries for immediate update
await queryClient.refetchQueries({ queryKey: ["mixes"] });
// Notify other components to refresh mixes
// Also dispatch events for any other listeners
window.dispatchEvent(new CustomEvent("mix-generated"));
window.dispatchEvent(new CustomEvent("mixes-updated"));
onClose();
} else {
toast.error("Not enough matching tracks", {
toast.error("Not enough tracks for this mood", {
description:
"Try a different mood or wait for more analysis",
"Try analyzing more music or choose a different mood",
});
}
} catch (error: any) {
} catch (error: unknown) {
console.error("Failed to generate mood mix:", error);
toast.error(error?.error || "Failed to generate mix");
const errorMessage =
error instanceof Error
? error.message
: "Failed to generate mix";
toast.error(errorMessage);
} finally {
setGenerating(null);
}
};
const generateCustomMix = async () => {
setGenerating("custom");
try {
const params: MoodMixParams = {
valence: {
min: customParams.valence[0] / 100,
max: customParams.valence[1] / 100,
},
energy: {
min: customParams.energy[0] / 100,
max: customParams.energy[1] / 100,
},
danceability: {
min: customParams.danceability[0] / 100,
max: customParams.danceability[1] / 100,
},
bpm: { min: customParams.bpm[0], max: customParams.bpm[1] },
limit: 15,
};
// Add ML mood params if advanced mode is enabled
if (showAdvanced) {
params.moodHappy = {
min: mlMoods.moodHappy[0] / 100,
max: mlMoods.moodHappy[1] / 100,
};
params.moodSad = {
min: mlMoods.moodSad[0] / 100,
max: mlMoods.moodSad[1] / 100,
};
params.moodRelaxed = {
min: mlMoods.moodRelaxed[0] / 100,
max: mlMoods.moodRelaxed[1] / 100,
};
params.moodAggressive = {
min: mlMoods.moodAggressive[0] / 100,
max: mlMoods.moodAggressive[1] / 100,
};
params.moodParty = {
min: mlMoods.moodParty[0] / 100,
max: mlMoods.moodParty[1] / 100,
};
params.moodAcoustic = {
min: mlMoods.moodAcoustic[0] / 100,
max: mlMoods.moodAcoustic[1] / 100,
};
params.moodElectronic = {
min: mlMoods.moodElectronic[0] / 100,
max: mlMoods.moodElectronic[1] / 100,
};
}
const mix = await api.generateMoodMix(params);
if (mix.tracks && mix.tracks.length > 0) {
const tracks: Track[] = mix.tracks.map((t: any) => ({
id: t.id,
title: t.title,
artist: {
name: t.album?.artist?.name || "Unknown Artist",
id: t.album?.artist?.id,
},
album: {
title: t.album?.title || "Unknown Album",
coverArt: t.album?.coverUrl,
id: t.albumId,
},
duration: t.duration,
}));
playTracks(tracks, 0);
toast.success("Your Custom Mix", {
description: `Playing ${tracks.length} tracks`,
});
// Save these params as user's mood mix preferences
try {
await api.post('/mixes/mood/save-preferences', {
...params,
presetName: "Custom"
});
} catch (err) {
console.error("Failed to save mood preferences:", err);
}
// Notify other components to refresh mixes
window.dispatchEvent(new CustomEvent("mix-generated"));
window.dispatchEvent(new CustomEvent("mixes-updated"));
onClose();
} else {
toast.error("Not enough matching tracks", {
description: "Try widening your parameters",
});
}
} catch (error: any) {
console.error("Failed to generate custom mix:", error);
toast.error(error?.error || "Failed to generate mix");
} finally {
setGenerating(null);
}
// Get track count for a mood
const getTrackCount = (mood: MoodType): number => {
// MoodBucketPreset uses 'id' as the mood identifier
const preset = presets.find((p) => p.id === mood);
return preset?.trackCount || 0;
};
if (!isVisible && !isOpen) return null;
return (
<div
className={`fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4 transition-opacity duration-200 ${
className={`fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4 transition-opacity duration-200 ${
isOpen ? "opacity-100" : "opacity-0"
}`}
onClick={onClose}
>
<div
className={`bg-gradient-to-b from-[#1a1a1a] to-[#0a0a0a] rounded-2xl max-w-2xl w-full max-h-[85vh] overflow-hidden border border-white/10 shadow-2xl transition-all duration-200 ${
className={`bg-gradient-to-b from-[#1a1a1a] to-[#0a0a0a] rounded-2xl max-w-lg w-full max-h-[85vh] overflow-hidden border border-white/10 shadow-2xl transition-all duration-200 ${
isOpen ? "scale-100 opacity-100" : "scale-95 opacity-0"
}`}
onClick={(e) => e.stopPropagation()}
@@ -263,7 +232,7 @@ export function MoodMixer({ isOpen, onClose }: MoodMixerProps) {
Mood Mixer
</h2>
<p className="text-sm text-gray-400">
Generate a mix based on your vibe
Pick your vibe
</p>
</div>
</div>
@@ -282,354 +251,78 @@ export function MoodMixer({ isOpen, onClose }: MoodMixerProps) {
<Loader2 className="w-8 h-8 animate-spin text-[#ecb200]" />
</div>
) : (
<>
{/* Toggle between presets and custom */}
<div className="flex gap-2 mb-6">
<button
onClick={() => setShowCustom(false)}
className={`flex-1 py-2.5 px-4 rounded-lg font-medium text-sm transition-all ${
!showCustom
? "bg-[#ecb200] text-black"
: "bg-white/5 text-white/70 hover:bg-white/10"
}`}
>
<AudioWaveform className="w-4 h-4 inline-block mr-2" />
Quick Moods
</button>
<button
onClick={() => setShowCustom(true)}
className={`flex-1 py-2.5 px-4 rounded-lg font-medium text-sm transition-all ${
showCustom
? "bg-[#ecb200] text-black"
: "bg-white/5 text-white/70 hover:bg-white/10"
}`}
>
<Sliders className="w-4 h-4 inline-block mr-2" />
Custom Mix
</button>
</div>
/* 3x3 Mood Grid */
<div className="grid grid-cols-3 gap-3">
{MOOD_ORDER.map((mood) => {
const config = MOOD_CONFIG[mood];
const Icon = config.icon;
const trackCount = getTrackCount(mood);
const isDisabled = trackCount < 5;
const isGenerating = generating === mood;
{!showCustom ? (
/* Preset Grid */
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{presets.map((preset) => (
<button
key={preset.id}
onClick={() => generateMix(preset)}
disabled={generating !== null}
className={`
relative group p-4 rounded-xl overflow-hidden
bg-gradient-to-br ${preset.color}
border border-white/10 hover:border-white/20
transition-all duration-200 hover:scale-[1.02] active:scale-[0.98]
disabled:opacity-50 disabled:cursor-not-allowed
text-left
`}
>
<div className="relative z-10 flex flex-col justify-end h-full">
<h3 className="font-semibold text-white text-sm">
{preset.name}
</h3>
</div>
{/* Play overlay */}
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
{generating === preset.id ? (
<Loader2 className="w-8 h-8 text-white animate-spin" />
) : (
<div className="w-12 h-12 rounded-full bg-[#ecb200] flex items-center justify-center shadow-lg">
<Play
className="w-6 h-6 text-black ml-0.5"
fill="currentColor"
/>
</div>
)}
</div>
</button>
))}
</div>
) : (
/* Custom Sliders */
<div className="space-y-6">
<SliderControl
label="Happiness"
value={customParams.valence}
onChange={(v) =>
setCustomParams((p) => ({
...p,
valence: v,
}))
}
min={0}
max={100}
lowLabel="Sad"
highLabel="Happy"
/>
<SliderControl
label="Energy"
value={customParams.energy}
onChange={(v) =>
setCustomParams((p) => ({
...p,
energy: v,
}))
}
min={0}
max={100}
lowLabel="Calm"
highLabel="Energetic"
/>
<SliderControl
label="Danceability"
value={customParams.danceability}
onChange={(v) =>
setCustomParams((p) => ({
...p,
danceability: v,
}))
}
min={0}
max={100}
lowLabel="Static"
highLabel="Groovy"
/>
<SliderControl
label="Tempo (BPM)"
value={customParams.bpm}
onChange={(v) =>
setCustomParams((p) => ({
...p,
bpm: v,
}))
}
min={60}
max={180}
lowLabel="Slow"
highLabel="Fast"
showValues
/>
{/* Advanced Mode Toggle */}
return (
<button
onClick={() => setShowAdvanced(!showAdvanced)}
className="w-full py-2 px-3 rounded-lg bg-white/5 hover:bg-white/10 transition-colors flex items-center justify-between text-sm text-white/70"
key={mood}
onClick={() => generateMix(mood)}
disabled={
generating !== null || isDisabled
}
className={`
relative group aspect-square rounded-xl overflow-hidden
bg-gradient-to-br ${config.color}
border border-white/10 hover:border-white/30
transition-all duration-200 hover:scale-[1.03] active:scale-[0.97]
disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:scale-100
flex flex-col items-center justify-center gap-2 p-3
`}
title={
isDisabled
? `Need at least 5 tracks (have ${trackCount})`
: config.description
}
>
<span className="flex items-center gap-2">
<Sliders className="w-4 h-4" />
ML Mood Controls
</span>
{showAdvanced ? (
<ChevronUp className="w-4 h-4" />
) : (
<ChevronDown className="w-4 h-4" />
)}
</button>
{/* ML Mood Sliders (Advanced Mode) */}
{showAdvanced && (
<div className="space-y-4 p-4 bg-white/5 rounded-lg border border-white/10">
<p className="text-xs text-gray-400 mb-2">
Fine-tune using ML-detected mood predictions
</p>
<SliderControl
label="Happy"
value={mlMoods.moodHappy}
onChange={(v) =>
setMlMoods((p) => ({ ...p, moodHappy: v }))
}
min={0}
max={100}
lowLabel="Low"
highLabel="High"
/>
<SliderControl
label="Sad"
value={mlMoods.moodSad}
onChange={(v) =>
setMlMoods((p) => ({ ...p, moodSad: v }))
}
min={0}
max={100}
lowLabel="Low"
highLabel="High"
/>
<SliderControl
label="Relaxed"
value={mlMoods.moodRelaxed}
onChange={(v) =>
setMlMoods((p) => ({ ...p, moodRelaxed: v }))
}
min={0}
max={100}
lowLabel="Low"
highLabel="High"
/>
<SliderControl
label="Aggressive"
value={mlMoods.moodAggressive}
onChange={(v) =>
setMlMoods((p) => ({ ...p, moodAggressive: v }))
}
min={0}
max={100}
lowLabel="Low"
highLabel="High"
/>
<SliderControl
label="Party"
value={mlMoods.moodParty}
onChange={(v) =>
setMlMoods((p) => ({ ...p, moodParty: v }))
}
min={0}
max={100}
lowLabel="Low"
highLabel="High"
/>
<SliderControl
label="Acoustic"
value={mlMoods.moodAcoustic}
onChange={(v) =>
setMlMoods((p) => ({ ...p, moodAcoustic: v }))
}
min={0}
max={100}
lowLabel="Low"
highLabel="High"
/>
<SliderControl
label="Electronic"
value={mlMoods.moodElectronic}
onChange={(v) =>
setMlMoods((p) => ({ ...p, moodElectronic: v }))
}
min={0}
max={100}
lowLabel="Low"
highLabel="High"
/>
{/* Icon */}
<div className="relative z-10">
{isGenerating ? (
<Loader2 className="w-8 h-8 text-white animate-spin" />
) : (
<Icon className="w-8 h-8 text-white drop-shadow-lg" />
)}
</div>
)}
<button
onClick={generateCustomMix}
disabled={generating !== null}
className="w-full py-3 px-4 rounded-lg bg-[#ecb200] text-black font-semibold hover:bg-[#d4a000] transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
>
{generating === "custom" ? (
<Loader2 className="w-5 h-5 animate-spin" />
) : (
<>
<Play
className="w-5 h-5"
fill="currentColor"
/>
Generate Mix
</>
)}
{/* Label */}
<span className="relative z-10 text-sm font-semibold text-white drop-shadow-lg">
{config.label}
</span>
{/* Track count badge */}
<span className="absolute top-2 right-2 text-[10px] font-medium text-white/70 bg-black/30 px-1.5 py-0.5 rounded-full">
{trackCount}
</span>
{/* Hover overlay with play icon */}
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
{!isGenerating && !isDisabled && (
<div className="w-12 h-12 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center">
<Play
className="w-6 h-6 text-white ml-0.5"
fill="currentColor"
/>
</div>
)}
</div>
</button>
</div>
)}
</>
);
})}
</div>
)}
{/* Help text */}
<p className="text-center text-xs text-gray-500 mt-4">
Moods are based on audio analysis of your library
</p>
</div>
</div>
</div>
);
}
interface SliderControlProps {
label: string;
value: [number, number];
onChange: (value: [number, number]) => void;
min: number;
max: number;
lowLabel: string;
highLabel: string;
showValues?: boolean;
}
function SliderControl({
label,
value,
onChange,
min,
max,
lowLabel,
highLabel,
showValues,
}: SliderControlProps) {
const handleMinChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newMin = Math.min(Number(e.target.value), value[1] - 1);
onChange([newMin, value[1]]);
};
const handleMaxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newMax = Math.max(Number(e.target.value), value[0] + 1);
onChange([value[0], newMax]);
};
const percentage = ((value[0] - min) / (max - min)) * 100;
const width = ((value[1] - value[0]) / (max - min)) * 100;
return (
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-white">{label}</span>
{showValues && (
<span className="text-xs text-gray-400">
{value[0]} - {value[1]}
</span>
)}
</div>
<div className="relative h-2">
{/* Track background - pointer-events-none so inputs receive clicks */}
<div className="absolute inset-0 bg-white/10 rounded-full pointer-events-none" />
{/* Active range - pointer-events-none so inputs receive clicks */}
<div
className="absolute h-full bg-gradient-to-r from-[#ecb200] to-amber-500 rounded-full pointer-events-none"
style={{ left: `${percentage}%`, width: `${width}%` }}
/>
{/* Min slider */}
<input
type="range"
min={min}
max={max}
value={value[0]}
onChange={handleMinChange}
className="absolute inset-0 w-full opacity-0 cursor-pointer z-10"
style={{ pointerEvents: "auto" }}
/>
{/* Max slider */}
<input
type="range"
min={min}
max={max}
value={value[1]}
onChange={handleMaxChange}
className="absolute inset-0 w-full opacity-0 cursor-pointer z-20"
style={{ pointerEvents: "auto" }}
/>
{/* Thumb indicators */}
<div
className="absolute w-4 h-4 bg-white rounded-full shadow-lg transform -translate-y-1/4 pointer-events-none border-2 border-[#ecb200]"
style={{ left: `calc(${percentage}% - 8px)` }}
/>
<div
className="absolute w-4 h-4 bg-white rounded-full shadow-lg transform -translate-y-1/4 pointer-events-none border-2 border-[#ecb200]"
style={{ left: `calc(${percentage + width}% - 8px)` }}
/>
</div>
<div className="flex justify-between text-xs text-gray-500">
<span>{lowLabel}</span>
<span>{highLabel}</span>
</div>
</div>
);
}

View File

@@ -113,7 +113,7 @@ export function AuthenticatedLayout({ children }: { children: ReactNode }) {
<main
className="flex-1 bg-gradient-to-b from-[#1a1a1a] via-black to-black mx-2 mb-2 rounded-lg overflow-y-auto relative"
style={{
marginTop: "52px",
marginTop: "58px",
marginBottom:
"calc(56px + env(safe-area-inset-bottom, 0px) + 8px)",
}}

View File

@@ -139,7 +139,7 @@ export function TopBar() {
return (
<header
className="fixed top-0 left-0 right-0 bg-black flex items-center px-3 z-50"
style={{ height: isMobileOrTablet ? "52px" : "64px" }}
style={{ height: isMobileOrTablet ? "58px" : "64px" }}
>
{/* Mobile/Tablet Layout: Hamburger + Home + Search + Bell */}
{isMobileOrTablet ? (

View File

@@ -6,7 +6,14 @@ import { useAudioControls } from "@/lib/audio-controls-context";
import { api } from "@/lib/api";
import { howlerEngine } from "@/lib/howler-engine";
import { audioSeekEmitter } from "@/lib/audio-seek-emitter";
import { useEffect, useLayoutEffect, useRef, memo, useCallback, useMemo } from "react";
import {
useEffect,
useLayoutEffect,
useRef,
memo,
useCallback,
useMemo,
} from "react";
function podcastDebugEnabled(): boolean {
try {
@@ -51,6 +58,7 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
const {
isPlaying,
setCurrentTime,
setCurrentTimeFromEngine,
setDuration,
setIsPlaying,
isBuffering,
@@ -59,6 +67,7 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
canSeek,
setCanSeek,
setDownloadProgress,
lockSeek,
} = useAudioPlayback();
// Controls context
@@ -83,6 +92,11 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
const loadListenerRef = useRef<(() => void) | null>(null);
const loadErrorListenerRef = useRef<(() => void) | null>(null);
const cachePollingLoadListenerRef = useRef<(() => void) | null>(null);
// Counter to track seek operations and abort stale ones
const seekOperationIdRef = useRef<number>(0);
// Debounce timer for rapid podcast seeks
const seekDebounceRef = useRef<NodeJS.Timeout | null>(null);
const pendingSeekTimeRef = useRef<number | null>(null);
// Reset duration when nothing is playing
useEffect(() => {
@@ -94,7 +108,9 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
// Subscribe to Howler events
useEffect(() => {
const handleTimeUpdate = (data: { time: number }) => {
setCurrentTime(data.time);
// Use setCurrentTimeFromEngine to respect seek lock
// This prevents stale timeupdate events from overwriting optimistic seek updates
setCurrentTimeFromEngine(data.time);
};
const handleLoad = (data: { duration: number }) => {
@@ -131,15 +147,19 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
console.error("[HowlerAudioElement] Playback error:", data.error);
setIsPlaying(false);
isUserInitiatedRef.current = false;
if (playbackType === "track") {
if (queue.length > 1) {
console.log("[HowlerAudioElement] Track failed, trying next in queue");
console.log(
"[HowlerAudioElement] Track failed, trying next in queue"
);
lastTrackIdRef.current = null;
isLoadingRef.current = false;
next();
} else {
console.log("[HowlerAudioElement] Track failed, no more in queue - clearing");
console.log(
"[HowlerAudioElement] Track failed, no more in queue - clearing"
);
lastTrackIdRef.current = null;
isLoadingRef.current = false;
setCurrentTrack(null);
@@ -164,7 +184,7 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
const handlePause = () => {
if (isLoadingRef.current) return;
if (seekReloadInProgressRef.current) return;
if (!isUserInitiatedRef.current) {
setIsPlaying(false);
}
@@ -188,7 +208,7 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
howlerEngine.off("play", handlePlay);
howlerEngine.off("pause", handlePause);
};
}, [playbackType, currentTrack, currentAudiobook, currentPodcast, repeatMode, next, pause, setCurrentTime, setDuration, setIsPlaying, queue, setCurrentTrack, setCurrentAudiobook, setCurrentPodcast, setPlaybackType]);
}, [playbackType, currentTrack, currentAudiobook, currentPodcast, repeatMode, next, pause, setCurrentTimeFromEngine, setDuration, setIsPlaying, queue, setCurrentTrack, setCurrentAudiobook, setCurrentPodcast, setPlaybackType]);
// Save audiobook progress
const saveAudiobookProgress = useCallback(
@@ -287,10 +307,10 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
if (isSeekingRef.current) {
return;
}
const shouldPlay = lastPlayingStateRef.current || isPlaying;
const isCurrentlyPlaying = howlerEngine.isPlaying();
if (shouldPlay && !isCurrentlyPlaying) {
howlerEngine.seek(0);
howlerEngine.play();
@@ -330,7 +350,7 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
if (streamUrl) {
const wasHowlerPlayingBeforeLoad = howlerEngine.isPlaying();
const fallbackDuration =
currentTrack?.duration ||
currentAudiobook?.duration ||
@@ -386,7 +406,8 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
});
}
const shouldAutoPlay = lastPlayingStateRef.current || wasHowlerPlayingBeforeLoad;
const shouldAutoPlay =
lastPlayingStateRef.current || wasHowlerPlayingBeforeLoad;
if (shouldAutoPlay) {
howlerEngine.play();
@@ -522,6 +543,9 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
// Poll for podcast cache and reload when ready
const startCachePolling = useCallback(
(podcastId: string, episodeId: string, targetTime: number) => {
// Capture the current seek operation ID
const pollingSeekId = seekOperationIdRef.current;
if (cachePollingRef.current) {
clearInterval(cachePollingRef.current);
}
@@ -530,6 +554,19 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
const maxPolls = 60;
cachePollingRef.current = setInterval(async () => {
// Check if a newer seek operation has started
if (seekOperationIdRef.current !== pollingSeekId) {
if (cachePollingRef.current) {
clearInterval(cachePollingRef.current);
cachePollingRef.current = null;
}
podcastDebugLog("cache polling aborted (stale)", {
pollingSeekId,
currentId: seekOperationIdRef.current,
});
return;
}
pollCount++;
try {
@@ -537,6 +574,16 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
podcastId,
episodeId
);
// Re-check after async operation
if (seekOperationIdRef.current !== pollingSeekId) {
if (cachePollingRef.current) {
clearInterval(cachePollingRef.current);
cachePollingRef.current = null;
}
return;
}
podcastDebugLog("cache poll", {
podcastId,
episodeId,
@@ -553,14 +600,20 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
cachePollingRef.current = null;
}
podcastDebugLog("cache ready -> howlerEngine.reload()", {
podcastId,
episodeId,
targetTime,
});
podcastDebugLog(
"cache ready -> howlerEngine.reload()",
{
podcastId,
episodeId,
targetTime,
}
);
// Clean up any previous cache polling load listener
if (cachePollingLoadListenerRef.current) {
howlerEngine.off("load", cachePollingLoadListenerRef.current);
howlerEngine.off(
"load",
cachePollingLoadListenerRef.current
);
cachePollingLoadListenerRef.current = null;
}
@@ -570,6 +623,15 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
howlerEngine.off("load", onLoad);
cachePollingLoadListenerRef.current = null;
// Check if still current before acting
if (seekOperationIdRef.current !== pollingSeekId) {
podcastDebugLog(
"cache polling load callback aborted (stale)",
{ pollingSeekId }
);
return;
}
howlerEngine.seek(targetTime);
setCurrentTime(targetTime);
howlerEngine.play();
@@ -594,12 +656,17 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
cachePollingRef.current = null;
}
console.warn("[HowlerAudioElement] Cache polling timeout");
console.warn(
"[HowlerAudioElement] Cache polling timeout"
);
setIsBuffering(false);
setTargetSeekPosition(null);
}
} catch (error) {
console.error("[HowlerAudioElement] Cache polling error:", error);
console.error(
"[HowlerAudioElement] Cache polling error:",
error
);
}
}, 2000);
},
@@ -608,93 +675,219 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
// Handle seeking via event emitter
useEffect(() => {
// Store previous time to detect large skips vs fine scrubbing
let previousTime = howlerEngine.getCurrentTime();
const handleSeek = async (time: number) => {
// Increment seek operation ID to track this specific seek
seekOperationIdRef.current += 1;
const thisSeekId = seekOperationIdRef.current;
const wasPlayingAtSeekStart = howlerEngine.isPlaying();
setCurrentTime(time);
// Detect if this is a large skip (like 30s buttons) vs fine scrubbing
const timeDelta = Math.abs(time - previousTime);
const isLargeSkip = timeDelta >= 10; // 10+ seconds = large skip (30s, 15s buttons)
previousTime = time;
// DON'T set currentTime here for podcasts - the seek() in audio-controls-context
// already did it optimistically. Setting it again causes a race condition.
// We only update it after the seek actually completes.
if (playbackType === "podcast" && currentPodcast) {
// Cancel any previous seek-related operations
if (seekCheckTimeoutRef.current) {
clearTimeout(seekCheckTimeoutRef.current);
seekCheckTimeoutRef.current = null;
}
// Cancel any pending cache polling from previous seek
if (cachePollingRef.current) {
clearInterval(cachePollingRef.current);
cachePollingRef.current = null;
}
// Cancel previous reload listener
if (seekReloadListenerRef.current) {
howlerEngine.off("load", seekReloadListenerRef.current);
seekReloadListenerRef.current = null;
}
// Cancel previous cache polling load listener
if (cachePollingLoadListenerRef.current) {
howlerEngine.off(
"load",
cachePollingLoadListenerRef.current
);
cachePollingLoadListenerRef.current = null;
}
// Cancel any pending debounced seek
if (seekDebounceRef.current) {
clearTimeout(seekDebounceRef.current);
seekDebounceRef.current = null;
}
// Store the pending seek time - debounce will use the latest value
pendingSeekTimeRef.current = time;
const [podcastId, episodeId] = currentPodcast.id.split(":");
try {
const status = await api.getPodcastEpisodeCacheStatus(
podcastId,
episodeId
);
if (status.cached) {
podcastDebugLog("seek: cached=true, using reload+seek pattern", {
time,
podcastId,
episodeId,
});
if (seekReloadListenerRef.current) {
howlerEngine.off("load", seekReloadListenerRef.current);
seekReloadListenerRef.current = null;
}
seekReloadInProgressRef.current = true;
howlerEngine.reload();
const onLoad = () => {
howlerEngine.off("load", onLoad);
seekReloadListenerRef.current = null;
seekReloadInProgressRef.current = false;
howlerEngine.seek(time);
setCurrentTime(time);
if (wasPlayingAtSeekStart) {
howlerEngine.play();
setIsPlaying(true);
}
};
seekReloadListenerRef.current = onLoad;
howlerEngine.on("load", onLoad);
// Execute the seek logic - immediately for large skips, debounced for fine scrubbing
const executeSeek = async () => {
const seekTime = pendingSeekTimeRef.current ?? time;
pendingSeekTimeRef.current = null;
// Check if this seek is still current
if (seekOperationIdRef.current !== thisSeekId) {
return;
}
} catch (e) {
console.warn("[HowlerAudioElement] Could not check cache status:", e);
}
howlerEngine.seek(time);
seekCheckTimeoutRef.current = setTimeout(() => {
try {
const actualPos = howlerEngine.getActualCurrentTime();
const seekFailed = time > 30 && actualPos < 30;
podcastDebugLog("seek check", {
time,
actualPos,
seekFailed,
const status = await api.getPodcastEpisodeCacheStatus(
podcastId,
episodeId,
});
episodeId
);
if (seekFailed) {
howlerEngine.pause();
setIsBuffering(true);
setTargetSeekPosition(time);
setIsPlaying(false);
startCachePolling(podcastId, episodeId, time);
// Check if this seek operation is still current
if (seekOperationIdRef.current !== thisSeekId) {
podcastDebugLog("seek: aborted (stale operation)", {
thisSeekId,
currentId: seekOperationIdRef.current,
});
return;
}
if (status.cached) {
// For cached podcasts, try direct seek first (faster than reload)
podcastDebugLog(
"seek: cached=true, trying direct seek first",
{
time: seekTime,
podcastId,
episodeId,
}
);
// Direct seek - howlerEngine now handles seek locking internally
howlerEngine.seek(seekTime);
// Verify seek succeeded after a short delay
setTimeout(() => {
if (seekOperationIdRef.current !== thisSeekId) {
return;
}
const actualPos = howlerEngine.getActualCurrentTime();
const seekSucceeded = Math.abs(actualPos - seekTime) < 5; // Within 5 seconds
podcastDebugLog("seek: direct seek result", {
seekTime,
actualPos,
seekSucceeded,
});
if (!seekSucceeded) {
// Direct seek failed, fall back to reload pattern
podcastDebugLog("seek: direct seek failed, falling back to reload");
seekReloadInProgressRef.current = true;
howlerEngine.reload();
const onLoad = () => {
howlerEngine.off("load", onLoad);
seekReloadListenerRef.current = null;
seekReloadInProgressRef.current = false;
if (seekOperationIdRef.current !== thisSeekId) {
return;
}
howlerEngine.seek(seekTime);
if (wasPlayingAtSeekStart) {
howlerEngine.play();
setIsPlaying(true);
}
};
seekReloadListenerRef.current = onLoad;
howlerEngine.on("load", onLoad);
} else {
// Seek succeeded - resume playback if needed
if (wasPlayingAtSeekStart && !howlerEngine.isPlaying()) {
howlerEngine.play();
}
}
}, 150);
return;
}
} catch (e) {
console.error("[HowlerAudioElement] Seek check error:", e);
console.warn(
"[HowlerAudioElement] Could not check cache status:",
e
);
}
}, 1000);
// Check if still current after async operation
if (seekOperationIdRef.current !== thisSeekId) {
return;
}
// Not cached - try direct seek
howlerEngine.seek(seekTime);
seekCheckTimeoutRef.current = setTimeout(() => {
// Check if this seek is still current
if (seekOperationIdRef.current !== thisSeekId) {
return;
}
try {
const actualPos = howlerEngine.getActualCurrentTime();
const seekFailed = seekTime > 30 && actualPos < 30;
podcastDebugLog("seek check", {
time: seekTime,
actualPos,
seekFailed,
podcastId,
episodeId,
});
if (seekFailed) {
howlerEngine.pause();
setIsBuffering(true);
setTargetSeekPosition(seekTime);
setIsPlaying(false);
startCachePolling(podcastId, episodeId, seekTime);
}
} catch (e) {
console.error(
"[HowlerAudioElement] Seek check error:",
e
);
}
}, 1000);
};
// For large skips (30s buttons), execute immediately for responsive feel
// For fine scrubbing (progress bar), debounce to prevent spamming
if (isLargeSkip) {
podcastDebugLog("seek: large skip, executing immediately", { timeDelta, time });
executeSeek();
} else {
podcastDebugLog("seek: fine scrub, debouncing", { timeDelta, time });
seekDebounceRef.current = setTimeout(executeSeek, 150);
}
return;
}
// For audiobooks and tracks, set seeking flag to prevent load effect interference
isSeekingRef.current = true;
howlerEngine.seek(time);
// Reset seeking flag after a short delay to allow seek to complete
setTimeout(() => {
isSeekingRef.current = false;
@@ -703,7 +896,7 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
const unsubscribe = audioSeekEmitter.subscribe(handleSeek);
return unsubscribe;
}, [setCurrentTime, playbackType, currentPodcast, setIsBuffering, setTargetSeekPosition, setIsPlaying, startCachePolling]);
}, [playbackType, currentPodcast, setIsBuffering, setTargetSeekPosition, setIsPlaying, startCachePolling]);
// Cleanup cache polling, seek timeout, and seek-reload listener on unmount
useEffect(() => {
@@ -718,6 +911,10 @@ export const HowlerAudioElement = memo(function HowlerAudioElement() {
howlerEngine.off("load", seekReloadListenerRef.current);
seekReloadListenerRef.current = null;
}
if (seekDebounceRef.current) {
clearTimeout(seekDebounceRef.current);
seekDebounceRef.current = null;
}
};
}, []);

View File

@@ -314,11 +314,12 @@ export function MiniPlayer() {
return (
<div
className="fixed left-2 right-2 z-50 rounded-xl overflow-hidden shadow-xl transition-transform"
className="fixed left-2 right-2 z-50 rounded-xl overflow-hidden shadow-xl"
style={{
bottom: "calc(56px + env(safe-area-inset-bottom, 0px) + 8px)",
transform: `translateX(${swipeOffset}px)`,
opacity: swipeOpacity,
transition: swipeOffset === 0 ? 'transform 0.25s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.25s cubic-bezier(0.4, 0, 0.2, 1)' : 'none',
}}
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
@@ -339,42 +340,42 @@ export function MiniPlayer() {
/>
</div>
{/* Player content */}
{/* Player content - more spacious padding */}
<div
className="relative flex items-center gap-2.5 px-3 py-2 cursor-pointer"
className="relative flex items-center gap-3 px-3 py-3 cursor-pointer"
onClick={() => setPlayerMode("overlay")}
>
{/* Album Art */}
<div className="relative w-10 h-10 flex-shrink-0 rounded-md overflow-hidden bg-black/30 shadow-md">
{/* Album Art - slightly larger */}
<div className="relative w-12 h-12 flex-shrink-0 rounded-lg overflow-hidden bg-black/30 shadow-md">
{coverUrl ? (
<Image
src={coverUrl}
alt={title}
fill
sizes="40px"
sizes="48px"
className="object-cover"
unoptimized
/>
) : (
<div className="w-full h-full flex items-center justify-center">
<MusicIcon className="w-4 h-4 text-gray-400" />
<MusicIcon className="w-5 h-5 text-gray-400" />
</div>
)}
</div>
{/* Track Info */}
<div className="flex-1 min-w-0">
<p className="text-white text-[13px] font-medium truncate leading-tight">
<p className="text-white text-sm font-medium truncate leading-tight">
{title}
</p>
<p className="text-gray-300/70 text-[11px] truncate leading-tight">
<p className="text-gray-300/70 text-xs truncate leading-tight mt-0.5">
{subtitle}
</p>
</div>
{/* Controls - Vibe & Play/Pause */}
<div
className="flex items-center gap-1 flex-shrink-0"
className="flex items-center gap-1.5 flex-shrink-0"
onClick={(e) => e.stopPropagation()}
>
{/* Vibe Button */}
@@ -382,7 +383,7 @@ export function MiniPlayer() {
onClick={handleVibeToggle}
disabled={!canSkip || isVibeLoading}
className={cn(
"w-9 h-9 flex items-center justify-center rounded-full transition-colors",
"w-10 h-10 flex items-center justify-center rounded-full transition-colors",
!canSkip
? "text-gray-600"
: vibeMode
@@ -396,9 +397,9 @@ export function MiniPlayer() {
}
>
{isVibeLoading ? (
<Loader2 className="w-[18px] h-[18px] animate-spin" />
<Loader2 className="w-5 h-5 animate-spin" />
) : (
<AudioWaveform className="w-[18px] h-[18px]" />
<AudioWaveform className="w-5 h-5" />
)}
</button>
@@ -414,7 +415,7 @@ export function MiniPlayer() {
}
}}
className={cn(
"w-9 h-9 rounded-full flex items-center justify-center transition shadow-md",
"w-10 h-10 rounded-full flex items-center justify-center transition shadow-md",
isBuffering
? "bg-white/80 text-black"
: "bg-white text-black hover:scale-105"
@@ -428,11 +429,11 @@ export function MiniPlayer() {
}
>
{isBuffering ? (
<Loader2 className="w-[18px] h-[18px] animate-spin" />
<Loader2 className="w-5 h-5 animate-spin" />
) : isPlaying ? (
<Pause className="w-[18px] h-[18px]" />
<Pause className="w-5 h-5" />
) : (
<Play className="w-[18px] h-[18px] ml-0.5" />
<Play className="w-5 h-5 ml-0.5" />
)}
</button>
</div>