From 3eea235ab149bc703421f1ad670add0e37bf7fb0 Mon Sep 17 00:00:00 2001 From: talksik Date: Sat, 21 Mar 2026 15:31:05 -0700 Subject: [PATCH] feat: use declarative callbacks for data changes --- js/src/hooks/use-particle.ts | 4 ++ js/src/hooks/use-stream-playback.ts | 97 +++++++++++------------------ js/src/lib/firestore-particles.ts | 16 +++-- 3 files changed, 53 insertions(+), 64 deletions(-) diff --git a/js/src/hooks/use-particle.ts b/js/src/hooks/use-particle.ts index 620b56c..f0ef983 100644 --- a/js/src/hooks/use-particle.ts +++ b/js/src/hooks/use-particle.ts @@ -60,6 +60,8 @@ export function useLiveParticleChildren( orderByField: string = "created_at", orderDirection: "asc" | "desc" = "desc", visibilityScopes?: string[], + onAdded?: (child: Particle) => void, + onRemoved?: (child: Particle, updatedChildren: Particle[]) => void, ): UseLiveParticleChildrenResult { const [children, setChildren] = useState([]); const [isLoading, setIsLoading] = useState(true); @@ -85,6 +87,8 @@ export function useLiveParticleChildren( visibilityScopes, orderByField, orderDirection, + onAdded, + onRemoved, ); return unsubscribe; diff --git a/js/src/hooks/use-stream-playback.ts b/js/src/hooks/use-stream-playback.ts index bddf19c..2e44c53 100644 --- a/js/src/hooks/use-stream-playback.ts +++ b/js/src/hooks/use-stream-playback.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useReducer, useRef } from "react"; +import { useCallback, useEffect, useEffectEvent, useMemo, useReducer, useRef } from "react"; import { useAuthStore } from "@/stores/auth-store"; import type { Particle } from "@/api/types"; import { useLiveParticleChildren } from "@/hooks/use-particle"; @@ -20,7 +20,8 @@ type PlaybackAction = | { type: "INIT"; particleId: string } | { type: "SET_PARTICLE"; particleId: string } | { type: "END" } - | { type: "PARTICLE_REMOVED"; fallbackParticleId: string | null } + | { type: "PARTICLE_ADDED"; particleId: string } + | { type: "PARTICLE_REMOVED"; removedParticleId: string; fallbackParticleId: string | null } | { type: "PAUSE" } | { type: "RESUME" }; @@ -49,7 +50,13 @@ function playbackReducer(state: PlaybackState, action: PlaybackAction): Playback }; case "END": return { ...state, status: "ended", paused: false }; + case "PARTICLE_ADDED": + if (state.status === "ended") { + return { ...state, currentParticleId: action.particleId, status: "playing", paused: false }; + } + return state; case "PARTICLE_REMOVED": + if (action.removedParticleId !== state.currentParticleId) return state; if (action.fallbackParticleId) { return { ...state, currentParticleId: action.fallbackParticleId, status: "playing" }; } @@ -86,13 +93,29 @@ export function useStreamPlayback( 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 | null>(null); // Track the stream ID we've initialized for, to reset when navigating between streams const initializedForRef = useRef(null); + // --- Firestore change callbacks --- + const onParticleAdded = useCallback((particle: Particle) => { + dispatch({ type: "PARTICLE_ADDED", particleId: particle.id }); + }, []); + + const onParticleRemoved = useEffectEvent((removed: Particle, updatedChildren: Particle[]) => { + const fallbackIndex = Math.min(currentIndex, updatedChildren.length - 1); + const fallback = updatedChildren[Math.max(0, fallbackIndex)]; + dispatch({ + type: "PARTICLE_REMOVED", + removedParticleId: removed.id, + fallbackParticleId: fallback?.id ?? null, + }); + }); + + const { children } = useLiveParticleChildren( + path, "created_at", "asc", undefined, onParticleAdded, onParticleRemoved, + ); + // Derive current index and particle from ID const currentIndex = useMemo(() => { if (!state.currentParticleId) return -1; @@ -101,15 +124,18 @@ export function useStreamPlayback( const currentParticle = currentIndex !== -1 ? children[currentIndex] : null; + // Fallback init — always sees latest children/state via useEffectEvent + const initFallback = useEffectEvent(() => { + if (state.initialized || children.length === 0) return; + initializedForRef.current = streamParticle.id; + dispatch({ type: "INIT", particleId: children[0].id }); + }); + // --- 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 @@ -132,63 +158,16 @@ export function useStreamPlayback( ); 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; - } - }; + // Marker target not found yet — fall back after timeout + const timeout = setTimeout(initFallback, INIT_FALLBACK_TIMEOUT_MS); + return () => clearTimeout(timeout); }, [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; diff --git a/js/src/lib/firestore-particles.ts b/js/src/lib/firestore-particles.ts index 4ba0408..dc49eb0 100644 --- a/js/src/lib/firestore-particles.ts +++ b/js/src/lib/firestore-particles.ts @@ -132,6 +132,8 @@ export function subscribeToParticleChildren( visibilityScopes: string[] = [], orderByField: string = "created_at", orderDirection: "asc" | "desc" = "desc", + onAdded?: (child: Particle) => void, + onRemoved?: (child: Particle, updatedChildren: Particle[]) => void, ): Unsubscribe { let q = query(typedCollection(collectionPath), orderBy(orderByField, orderDirection)); if (visibilityScopes.length > 0) { @@ -143,11 +145,15 @@ export function subscribeToParticleChildren( return onSnapshot( q, (snap) => { - // onNext(snap.docChanges().map((change) => { - // const data = change.doc.data(); - // return { type: change.type, data }; - // })); - onData(snap.docs.map((d) => d.data())); + const updatedChildren = snap.docs.map((d) => d.data()); + onData(updatedChildren); + + if (onAdded || onRemoved) { + for (const change of snap.docChanges()) { + if (change.type === "added" && onAdded) onAdded(change.doc.data()); + if (change.type === "removed" && onRemoved) onRemoved(change.doc.data(), updatedChildren); + } + } }, onError, );