fix: playback restarting from start of stream
This does a major refactor to using particleId for state of playback instead of index, since index would change if the particle children data does partial hydrations and a particle's index changes. Also it abstracts much of the playback details from the view component.
This commit is contained in:
@@ -1,9 +1,8 @@
|
|||||||
import { useState, useEffect, useEffectEvent, useCallback, useReducer, useRef } from "react";
|
import { useState, useEffect, useEffectEvent, useCallback } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
import type { Particle } from "@/api/types";
|
import type { Particle } from "@/api/types";
|
||||||
import { useLiveParticleChildren } from "@/hooks/use-particle";
|
import { parseParticlePath, type ParticlePath } from "@/lib/particle-path";
|
||||||
import { parseParticlePath, toFirestoreDocPath, type ParticlePath } from "@/lib/particle-path";
|
|
||||||
import { ComposeOverlay } from "@/features/compose/compose-overlay";
|
import { ComposeOverlay } from "@/features/compose/compose-overlay";
|
||||||
import { PlaybackPageIndicator } from "@/features/particles/playback-page-indicator";
|
import { PlaybackPageIndicator } from "@/features/particles/playback-page-indicator";
|
||||||
import { MediaParticleView } from "@/features/particles/media-particle-view";
|
import { MediaParticleView } from "@/features/particles/media-particle-view";
|
||||||
@@ -11,7 +10,6 @@ import { TextParticleView } from "@/features/particles/text-particle-view";
|
|||||||
import { FallbackParticleView } from "@/features/particles/fallback-particle-view";
|
import { FallbackParticleView } from "@/features/particles/fallback-particle-view";
|
||||||
import { Avatar, AvatarFallback, AvatarGroup } from "@/components/ui/avatar";
|
import { Avatar, AvatarFallback, AvatarGroup } from "@/components/ui/avatar";
|
||||||
import ControlsIndicator from "@/features/compose/controls-indicator";
|
import ControlsIndicator from "@/features/compose/controls-indicator";
|
||||||
import { updateStreamPlaybackMarker } from "@/lib/firestore-particles";
|
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||||
import { useNetwork, useNetworks } from "@/hooks/use-networks";
|
import { useNetwork, useNetworks } from "@/hooks/use-networks";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -19,6 +17,7 @@ import { Home, Settings } from "lucide-react";
|
|||||||
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb";
|
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb";
|
||||||
import { WindowControls } from "@/components/window-controls";
|
import { WindowControls } from "@/components/window-controls";
|
||||||
import { formatDistanceToNow } from "@/lib/time-utils";
|
import { formatDistanceToNow } from "@/lib/time-utils";
|
||||||
|
import { useStreamPlayback } from "@/hooks/use-stream-playback";
|
||||||
|
|
||||||
function getParticleDisplayName(particle: Particle): string {
|
function getParticleDisplayName(particle: Particle): string {
|
||||||
switch (particle.type) {
|
switch (particle.type) {
|
||||||
@@ -38,92 +37,13 @@ function getParticleDisplayName(particle: Particle): string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Playback reducer ---
|
|
||||||
|
|
||||||
type PlaybackStatus = "idle" | "playing" | "ended";
|
|
||||||
|
|
||||||
interface PlaybackState {
|
|
||||||
currentIndex: number;
|
|
||||||
status: PlaybackStatus;
|
|
||||||
paused: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
type PlaybackAction =
|
|
||||||
| { type: "INIT"; particleCount: number, initialIndex?: number }
|
|
||||||
| { type: "NEXT"; particleCount: number }
|
|
||||||
| { type: "PREV" }
|
|
||||||
| { type: "GO_TO"; index: number; particleCount: number }
|
|
||||||
| { type: "PAUSE" }
|
|
||||||
| { type: "RESUME" }
|
|
||||||
| { type: "SYNC_PARTICLES"; particleCount: number };
|
|
||||||
|
|
||||||
function playbackReducer(
|
|
||||||
state: PlaybackState,
|
|
||||||
action: PlaybackAction,
|
|
||||||
): PlaybackState {
|
|
||||||
switch (action.type) {
|
|
||||||
case "INIT":
|
|
||||||
return {
|
|
||||||
currentIndex: action.initialIndex ?? 0,
|
|
||||||
status: action.particleCount > 0 ? "playing" : "idle",
|
|
||||||
paused: false,
|
|
||||||
};
|
|
||||||
case "NEXT":
|
|
||||||
if (state.currentIndex < action.particleCount - 1) {
|
|
||||||
return { ...state, currentIndex: state.currentIndex + 1, paused: false };
|
|
||||||
}
|
|
||||||
return { ...state, status: "ended", paused: false };
|
|
||||||
case "PREV":
|
|
||||||
if (state.currentIndex > 0) {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
currentIndex: state.currentIndex - 1,
|
|
||||||
status: "playing",
|
|
||||||
paused: false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return state;
|
|
||||||
case "GO_TO":
|
|
||||||
if (action.index >= 0 && action.index < action.particleCount) {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
currentIndex: action.index,
|
|
||||||
status: "playing",
|
|
||||||
paused: false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return state;
|
|
||||||
case "PAUSE":
|
|
||||||
return { ...state, paused: true };
|
|
||||||
case "RESUME":
|
|
||||||
return { ...state, paused: false };
|
|
||||||
case "SYNC_PARTICLES":
|
|
||||||
// Clamp index if particles were removed; don't reset position
|
|
||||||
if (action.particleCount === 0) {
|
|
||||||
return { currentIndex: 0, status: "idle", paused: state.paused };
|
|
||||||
}
|
|
||||||
if (state.status === "ended" && state.currentIndex < action.particleCount - 1) {
|
|
||||||
// New particle appended — resume and advance to it
|
|
||||||
return { ...state, currentIndex: state.currentIndex + 1, status: "playing", paused: false };
|
|
||||||
}
|
|
||||||
if (state.currentIndex >= action.particleCount) {
|
|
||||||
return { ...state, currentIndex: action.particleCount - 1 };
|
|
||||||
}
|
|
||||||
return state;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const initialState: PlaybackState = {
|
|
||||||
currentIndex: 0,
|
|
||||||
status: "idle",
|
|
||||||
paused: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- Exit countdown hook ---
|
// --- Exit countdown hook ---
|
||||||
|
|
||||||
const EXIT_DELAY_MS = 5000;
|
const EXIT_DELAY_MS = 5000;
|
||||||
const EXIT_TICK_MS = 100;
|
const EXIT_TICK_MS = 100;
|
||||||
|
|
||||||
|
type PlaybackStatus = "idle" | "playing" | "ended";
|
||||||
|
|
||||||
function useExitCountdown(
|
function useExitCountdown(
|
||||||
status: PlaybackStatus,
|
status: PlaybackStatus,
|
||||||
composeActive: boolean,
|
composeActive: boolean,
|
||||||
@@ -179,88 +99,43 @@ interface StreamViewProps {
|
|||||||
export function StreamView({ path, streamParticle }: StreamViewProps) {
|
export function StreamView({ path, streamParticle }: StreamViewProps) {
|
||||||
const { networkId } = parseParticlePath(path);
|
const { networkId } = parseParticlePath(path);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { children } = useLiveParticleChildren(path, "created_at", "asc");
|
|
||||||
|
|
||||||
const [state, dispatch] = useReducer(playbackReducer, initialState);
|
const {
|
||||||
|
children,
|
||||||
|
currentParticle,
|
||||||
|
currentIndex,
|
||||||
|
status,
|
||||||
|
paused,
|
||||||
|
next,
|
||||||
|
prev,
|
||||||
|
goTo,
|
||||||
|
pause,
|
||||||
|
resume,
|
||||||
|
} = useStreamPlayback(streamParticle, path);
|
||||||
|
|
||||||
const [composeActive, setComposeActive] = useState(false);
|
const [composeActive, setComposeActive] = useState(false);
|
||||||
const [progress, setProgress] = useState(0);
|
const [progress, setProgress] = useState(0);
|
||||||
const hasInitializedRef = useRef<string | null>(null);
|
|
||||||
|
|
||||||
const handleExitNavigate = useCallback(() => {
|
const handleExitNavigate = useCallback(() => {
|
||||||
navigate(`/${networkId}`);
|
navigate(`/${networkId}`);
|
||||||
}, [navigate, networkId]);
|
}, [navigate, networkId]);
|
||||||
|
|
||||||
const exitRemainingMs = useExitCountdown(
|
const exitRemainingMs = useExitCountdown(
|
||||||
state.status,
|
status,
|
||||||
composeActive,
|
composeActive,
|
||||||
handleExitNavigate,
|
handleExitNavigate,
|
||||||
);
|
);
|
||||||
|
|
||||||
const userId = useAuthStore((s) => s.user?.id);
|
|
||||||
|
|
||||||
// Reset progress when particle changes
|
// Reset progress when particle changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setProgress(0);
|
setProgress(0);
|
||||||
}, [state.currentIndex]);
|
}, [currentParticle?.id]);
|
||||||
|
|
||||||
// Init playback once per stream entry, only after children have loaded
|
|
||||||
useEffect(() => {
|
|
||||||
if (children.length === 0) return;
|
|
||||||
if (hasInitializedRef.current === streamParticle.id) return;
|
|
||||||
hasInitializedRef.current = streamParticle.id;
|
|
||||||
|
|
||||||
const playbackPosition = streamParticle.playback_markers?.[userId ?? ""];
|
|
||||||
let initialIndex = 0;
|
|
||||||
|
|
||||||
if (playbackPosition) {
|
|
||||||
const foundIndex = children.findIndex(
|
|
||||||
(c) => c.created_at.getTime() === playbackPosition.getTime(),
|
|
||||||
);
|
|
||||||
if (foundIndex !== -1) {
|
|
||||||
initialIndex = foundIndex;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dispatch({ type: "INIT", particleCount: children.length, initialIndex });
|
|
||||||
}, [streamParticle.id, userId, children]);
|
|
||||||
|
|
||||||
// Sync on subsequent changes (new particle appended, removed, etc.)
|
|
||||||
useEffect(() => {
|
|
||||||
if (hasInitializedRef.current !== streamParticle.id) return;
|
|
||||||
dispatch({ type: "SYNC_PARTICLES", particleCount: children.length });
|
|
||||||
}, [children.length, streamParticle.id]);
|
|
||||||
|
|
||||||
// Pause/resume playback when compose overlay opens/closes
|
// Pause/resume playback when compose overlay opens/closes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (composeActive) dispatch({ type: "PAUSE" });
|
if (composeActive) pause();
|
||||||
else dispatch({ type: "RESUME" });
|
else resume();
|
||||||
}, [composeActive]);
|
}, [composeActive, pause, resume]);
|
||||||
|
|
||||||
const next = useCallback(() => {
|
|
||||||
dispatch({ type: "NEXT", particleCount: children.length });
|
|
||||||
}, [children.length]);
|
|
||||||
|
|
||||||
const prev = useCallback(() => {
|
|
||||||
dispatch({ type: "PREV" });
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const goTo = useCallback(
|
|
||||||
(index: number) => {
|
|
||||||
dispatch({ type: "GO_TO", index, particleCount: children.length });
|
|
||||||
},
|
|
||||||
[children.length],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Click-to-navigate: left 30% = prev, right 70% = next
|
|
||||||
const handlePlaybackClick = useCallback(
|
|
||||||
(e: React.MouseEvent<HTMLDivElement>) => {
|
|
||||||
const rect = e.currentTarget.getBoundingClientRect();
|
|
||||||
const x = (e.clientX - rect.left) / rect.width;
|
|
||||||
if (x < 0.3) prev();
|
|
||||||
else if (x > 0.7) next();
|
|
||||||
},
|
|
||||||
[prev, next],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Playback keyboard: arrows, escape
|
// Playback keyboard: arrows, escape
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -299,18 +174,16 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
|
|||||||
[composeActive, next, prev, navigate, networkId],
|
[composeActive, next, prev, navigate, networkId],
|
||||||
);
|
);
|
||||||
|
|
||||||
const currentParticle = children[state.currentIndex] ?? null;
|
// Click-to-navigate: left 30% = prev, right 70% = next
|
||||||
|
const handlePlaybackClick = useCallback(
|
||||||
useEffect(() => {
|
(e: React.MouseEvent<HTMLDivElement>) => {
|
||||||
if (!userId || !currentParticle) return;
|
const rect = e.currentTarget.getBoundingClientRect();
|
||||||
|
const x = (e.clientX - rect.left) / rect.width;
|
||||||
const streamDocPath = toFirestoreDocPath(path);
|
if (x < 0.3) prev();
|
||||||
updateStreamPlaybackMarker(streamDocPath, userId, currentParticle.created_at);
|
else if (x > 0.7) next();
|
||||||
}, [currentParticle?.id, path])
|
},
|
||||||
|
[prev, next],
|
||||||
// Author info from current particle
|
);
|
||||||
const authorEmail = currentParticle?.created_by_email ?? "";
|
|
||||||
const authorInitials = authorEmail.split("@")[0]?.slice(0, 2).toUpperCase() ?? "";
|
|
||||||
|
|
||||||
if (children.length === 0) {
|
if (children.length === 0) {
|
||||||
return (
|
return (
|
||||||
@@ -328,7 +201,7 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render particle content inline (replaces ParticleRenderer)
|
// Render particle content inline
|
||||||
function renderParticle(particle: Particle) {
|
function renderParticle(particle: Particle) {
|
||||||
switch (particle.type) {
|
switch (particle.type) {
|
||||||
case "media":
|
case "media":
|
||||||
@@ -336,7 +209,7 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
|
|||||||
<MediaParticleView
|
<MediaParticleView
|
||||||
key={particle.id}
|
key={particle.id}
|
||||||
particle={particle}
|
particle={particle}
|
||||||
paused={state.paused}
|
paused={paused}
|
||||||
onEnded={next}
|
onEnded={next}
|
||||||
onProgress={setProgress}
|
onProgress={setProgress}
|
||||||
/>
|
/>
|
||||||
@@ -346,7 +219,7 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
|
|||||||
<TextParticleView
|
<TextParticleView
|
||||||
key={particle.id}
|
key={particle.id}
|
||||||
particle={particle}
|
particle={particle}
|
||||||
paused={state.paused}
|
paused={paused}
|
||||||
onEnded={next}
|
onEnded={next}
|
||||||
onProgress={setProgress}
|
onProgress={setProgress}
|
||||||
/>
|
/>
|
||||||
@@ -362,7 +235,7 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
|
|||||||
<div className="z-10 absolute left-0 right-0">
|
<div className="z-10 absolute left-0 right-0">
|
||||||
<PlaybackPageIndicator
|
<PlaybackPageIndicator
|
||||||
total={children.length}
|
total={children.length}
|
||||||
current={state.currentIndex}
|
current={currentIndex}
|
||||||
progress={progress}
|
progress={progress}
|
||||||
onGoTo={goTo}
|
onGoTo={goTo}
|
||||||
/>
|
/>
|
||||||
@@ -394,7 +267,9 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
|
|||||||
<div className="absolute right-0 bottom-0 z-10">
|
<div className="absolute right-0 bottom-0 z-10">
|
||||||
<ControlsIndicator type={"reply"}>
|
<ControlsIndicator type={"reply"}>
|
||||||
<div className="flex items-center gap-1 text-xs text-white/70">
|
<div className="flex items-center gap-1 text-xs text-white/70">
|
||||||
<SeenIndicator stream={streamParticle} currentParticle={currentParticle} networkId={networkId} />
|
{currentParticle && (
|
||||||
|
<SeenIndicator stream={streamParticle} currentParticle={currentParticle} networkId={networkId} />
|
||||||
|
)}
|
||||||
{/* Exit countdown */}
|
{/* Exit countdown */}
|
||||||
{exitRemainingMs !== null && (
|
{exitRemainingMs !== null && (
|
||||||
<span>
|
<span>
|
||||||
@@ -408,7 +283,7 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TopBar({ networkId, particle, streamParticle }: { networkId: string; particle: Particle; streamParticle: Particle & { type: "stream" } }) {
|
function TopBar({ networkId, particle, streamParticle }: { networkId: string; particle: Particle | null; streamParticle: Particle & { type: "stream" } }) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -0,0 +1,240 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useReducer, useRef } from "react";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import type { Particle } from "@/api/types";
|
||||||
|
import { useLiveParticleChildren } from "@/hooks/use-particle";
|
||||||
|
import { toFirestoreDocPath, type ParticlePath } from "@/lib/particle-path";
|
||||||
|
import { updateStreamPlaybackMarker } from "@/lib/firestore-particles";
|
||||||
|
|
||||||
|
// --- Playback reducer (ID-based) ---
|
||||||
|
|
||||||
|
type PlaybackStatus = "idle" | "playing" | "ended";
|
||||||
|
|
||||||
|
interface PlaybackState {
|
||||||
|
currentParticleId: string | null;
|
||||||
|
status: PlaybackStatus;
|
||||||
|
paused: boolean;
|
||||||
|
initialized: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
type PlaybackAction =
|
||||||
|
| { type: "INIT"; particleId: string }
|
||||||
|
| { type: "SET_PARTICLE"; particleId: string }
|
||||||
|
| { type: "END" }
|
||||||
|
| { type: "PARTICLE_REMOVED"; fallbackParticleId: string | null }
|
||||||
|
| { type: "PAUSE" }
|
||||||
|
| { type: "RESUME" };
|
||||||
|
|
||||||
|
const initialState: PlaybackState = {
|
||||||
|
currentParticleId: null,
|
||||||
|
status: "idle",
|
||||||
|
paused: false,
|
||||||
|
initialized: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
function playbackReducer(state: PlaybackState, action: PlaybackAction): PlaybackState {
|
||||||
|
switch (action.type) {
|
||||||
|
case "INIT":
|
||||||
|
return {
|
||||||
|
currentParticleId: action.particleId,
|
||||||
|
status: "playing",
|
||||||
|
paused: false,
|
||||||
|
initialized: true,
|
||||||
|
};
|
||||||
|
case "SET_PARTICLE":
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
currentParticleId: action.particleId,
|
||||||
|
status: "playing",
|
||||||
|
paused: false,
|
||||||
|
};
|
||||||
|
case "END":
|
||||||
|
return { ...state, status: "ended", paused: false };
|
||||||
|
case "PARTICLE_REMOVED":
|
||||||
|
if (action.fallbackParticleId) {
|
||||||
|
return { ...state, currentParticleId: action.fallbackParticleId, status: "playing" };
|
||||||
|
}
|
||||||
|
return { ...state, currentParticleId: null, status: "idle" };
|
||||||
|
case "PAUSE":
|
||||||
|
return { ...state, paused: true };
|
||||||
|
case "RESUME":
|
||||||
|
return { ...state, paused: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Init timeout ---
|
||||||
|
|
||||||
|
const INIT_FALLBACK_TIMEOUT_MS = 5000;
|
||||||
|
|
||||||
|
// --- Hook ---
|
||||||
|
|
||||||
|
interface UseStreamPlaybackResult {
|
||||||
|
children: Particle[];
|
||||||
|
currentParticle: Particle | null;
|
||||||
|
currentIndex: number;
|
||||||
|
status: PlaybackStatus;
|
||||||
|
paused: boolean;
|
||||||
|
initialized: boolean;
|
||||||
|
next: () => void;
|
||||||
|
prev: () => void;
|
||||||
|
goTo: (index: number) => void;
|
||||||
|
pause: () => void;
|
||||||
|
resume: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useStreamPlayback(
|
||||||
|
streamParticle: Particle & { type: "stream" },
|
||||||
|
path: ParticlePath,
|
||||||
|
): UseStreamPlaybackResult {
|
||||||
|
const userId = useAuthStore((s) => s.user?.id);
|
||||||
|
const { children } = useLiveParticleChildren(path, "created_at", "asc");
|
||||||
|
|
||||||
|
const [state, dispatch] = useReducer(playbackReducer, initialState);
|
||||||
|
const initTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
// Track the stream ID we've initialized for, to reset when navigating between streams
|
||||||
|
const initializedForRef = useRef<string | null>(null);
|
||||||
|
|
||||||
|
// Derive current index and particle from ID
|
||||||
|
const currentIndex = useMemo(() => {
|
||||||
|
if (!state.currentParticleId) return -1;
|
||||||
|
return children.findIndex((c) => c.id === state.currentParticleId);
|
||||||
|
}, [children, state.currentParticleId]);
|
||||||
|
|
||||||
|
const currentParticle = currentIndex !== -1 ? children[currentIndex] : null;
|
||||||
|
|
||||||
|
// --- Init logic: runs on every children change until initialized ---
|
||||||
|
useEffect(() => {
|
||||||
|
// Reset if we navigated to a different stream
|
||||||
|
if (initializedForRef.current !== null && initializedForRef.current !== streamParticle.id) {
|
||||||
|
initializedForRef.current = null;
|
||||||
|
if (initTimeoutRef.current) {
|
||||||
|
clearTimeout(initTimeoutRef.current);
|
||||||
|
initTimeoutRef.current = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Already initialized for this stream
|
||||||
|
if (state.initialized && initializedForRef.current === streamParticle.id) return;
|
||||||
|
|
||||||
|
if (children.length === 0) return;
|
||||||
|
|
||||||
|
const playbackPosition = streamParticle.playback_markers?.[userId ?? ""];
|
||||||
|
|
||||||
|
if (!playbackPosition) {
|
||||||
|
// No marker — start from the beginning
|
||||||
|
initializedForRef.current = streamParticle.id;
|
||||||
|
dispatch({ type: "INIT", particleId: children[0].id });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to find the marker's target particle
|
||||||
|
const found = children.find(
|
||||||
|
(c) => c.created_at.getTime() === playbackPosition.getTime(),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (found) {
|
||||||
|
// Found it — init immediately
|
||||||
|
initializedForRef.current = streamParticle.id;
|
||||||
|
if (initTimeoutRef.current) {
|
||||||
|
clearTimeout(initTimeoutRef.current);
|
||||||
|
initTimeoutRef.current = null;
|
||||||
|
}
|
||||||
|
dispatch({ type: "INIT", particleId: found.id });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Marker target not found yet — start timeout if not already running
|
||||||
|
if (!initTimeoutRef.current) {
|
||||||
|
initTimeoutRef.current = setTimeout(() => {
|
||||||
|
initTimeoutRef.current = null;
|
||||||
|
// Fallback: find nearest particle by timestamp, or first child
|
||||||
|
initializedForRef.current = streamParticle.id;
|
||||||
|
dispatch({ type: "INIT", particleId: children[0].id });
|
||||||
|
}, INIT_FALLBACK_TIMEOUT_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (initTimeoutRef.current) {
|
||||||
|
clearTimeout(initTimeoutRef.current);
|
||||||
|
initTimeoutRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [children, streamParticle.id, streamParticle.playback_markers, userId, state.initialized]);
|
||||||
|
|
||||||
|
// --- Handle current particle disappearing (deletion) ---
|
||||||
|
useEffect(() => {
|
||||||
|
if (!state.initialized || !state.currentParticleId) return;
|
||||||
|
if (children.length === 0) {
|
||||||
|
dispatch({ type: "PARTICLE_REMOVED", fallbackParticleId: null });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const stillExists = children.some((c) => c.id === state.currentParticleId);
|
||||||
|
if (stillExists) return;
|
||||||
|
|
||||||
|
// Current particle was removed — find nearest neighbor
|
||||||
|
// Use the previous index position, clamped to the new array bounds
|
||||||
|
const fallbackIndex = Math.min(currentIndex, children.length - 1);
|
||||||
|
const fallback = children[Math.max(0, fallbackIndex)];
|
||||||
|
dispatch({ type: "PARTICLE_REMOVED", fallbackParticleId: fallback?.id ?? null });
|
||||||
|
}, [children, state.initialized, state.currentParticleId, currentIndex]);
|
||||||
|
|
||||||
|
// --- Handle new particles appended while at "ended" ---
|
||||||
|
useEffect(() => {
|
||||||
|
if (state.status !== "ended" || !state.currentParticleId) return;
|
||||||
|
|
||||||
|
const idx = children.findIndex((c) => c.id === state.currentParticleId);
|
||||||
|
if (idx !== -1 && idx < children.length - 1) {
|
||||||
|
// New particle after current — advance to it
|
||||||
|
dispatch({ type: "SET_PARTICLE", particleId: children[idx + 1].id });
|
||||||
|
}
|
||||||
|
}, [children, state.status, state.currentParticleId]);
|
||||||
|
|
||||||
|
// --- Persist playback marker ---
|
||||||
|
useEffect(() => {
|
||||||
|
if (!userId || !state.initialized || !currentParticle) return;
|
||||||
|
|
||||||
|
const streamDocPath = toFirestoreDocPath(path);
|
||||||
|
updateStreamPlaybackMarker(streamDocPath, userId, currentParticle.created_at);
|
||||||
|
}, [currentParticle?.id, state.initialized, userId, path]);
|
||||||
|
|
||||||
|
// --- Navigation callbacks ---
|
||||||
|
const next = useCallback(() => {
|
||||||
|
if (currentIndex === -1) return;
|
||||||
|
if (currentIndex < children.length - 1) {
|
||||||
|
dispatch({ type: "SET_PARTICLE", particleId: children[currentIndex + 1].id });
|
||||||
|
} else {
|
||||||
|
dispatch({ type: "END" });
|
||||||
|
}
|
||||||
|
}, [children, currentIndex]);
|
||||||
|
|
||||||
|
const prev = useCallback(() => {
|
||||||
|
if (currentIndex <= 0) return;
|
||||||
|
dispatch({ type: "SET_PARTICLE", particleId: children[currentIndex - 1].id });
|
||||||
|
}, [children, currentIndex]);
|
||||||
|
|
||||||
|
const goTo = useCallback(
|
||||||
|
(index: number) => {
|
||||||
|
if (index >= 0 && index < children.length) {
|
||||||
|
dispatch({ type: "SET_PARTICLE", particleId: children[index].id });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[children],
|
||||||
|
);
|
||||||
|
|
||||||
|
const pause = useCallback(() => dispatch({ type: "PAUSE" }), []);
|
||||||
|
const resume = useCallback(() => dispatch({ type: "RESUME" }), []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
children,
|
||||||
|
currentParticle,
|
||||||
|
currentIndex,
|
||||||
|
status: state.status,
|
||||||
|
paused: state.paused,
|
||||||
|
initialized: state.initialized,
|
||||||
|
next,
|
||||||
|
prev,
|
||||||
|
goTo,
|
||||||
|
pause,
|
||||||
|
resume,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -143,6 +143,10 @@ export function subscribeToParticleChildren(
|
|||||||
return onSnapshot(
|
return onSnapshot(
|
||||||
q,
|
q,
|
||||||
(snap) => {
|
(snap) => {
|
||||||
|
// onNext(snap.docChanges().map((change) => {
|
||||||
|
// const data = change.doc.data();
|
||||||
|
// return { type: change.type, data };
|
||||||
|
// }));
|
||||||
onData(snap.docs.map((d) => d.data()));
|
onData(snap.docs.map((d) => d.data()));
|
||||||
},
|
},
|
||||||
onError,
|
onError,
|
||||||
|
|||||||
Reference in New Issue
Block a user