feat: use declarative callbacks for data changes
This commit is contained in:
@@ -60,6 +60,8 @@ export function useLiveParticleChildren(
|
|||||||
orderByField: string = "created_at",
|
orderByField: string = "created_at",
|
||||||
orderDirection: "asc" | "desc" = "desc",
|
orderDirection: "asc" | "desc" = "desc",
|
||||||
visibilityScopes?: string[],
|
visibilityScopes?: string[],
|
||||||
|
onAdded?: (child: Particle) => void,
|
||||||
|
onRemoved?: (child: Particle, updatedChildren: Particle[]) => void,
|
||||||
): UseLiveParticleChildrenResult {
|
): UseLiveParticleChildrenResult {
|
||||||
const [children, setChildren] = useState<Particle[]>([]);
|
const [children, setChildren] = useState<Particle[]>([]);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
@@ -85,6 +87,8 @@ export function useLiveParticleChildren(
|
|||||||
visibilityScopes,
|
visibilityScopes,
|
||||||
orderByField,
|
orderByField,
|
||||||
orderDirection,
|
orderDirection,
|
||||||
|
onAdded,
|
||||||
|
onRemoved,
|
||||||
);
|
);
|
||||||
|
|
||||||
return unsubscribe;
|
return unsubscribe;
|
||||||
|
|||||||
@@ -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 { useAuthStore } from "@/stores/auth-store";
|
||||||
import type { Particle } from "@/api/types";
|
import type { Particle } from "@/api/types";
|
||||||
import { useLiveParticleChildren } from "@/hooks/use-particle";
|
import { useLiveParticleChildren } from "@/hooks/use-particle";
|
||||||
@@ -20,7 +20,8 @@ type PlaybackAction =
|
|||||||
| { type: "INIT"; particleId: string }
|
| { type: "INIT"; particleId: string }
|
||||||
| { type: "SET_PARTICLE"; particleId: string }
|
| { type: "SET_PARTICLE"; particleId: string }
|
||||||
| { type: "END" }
|
| { type: "END" }
|
||||||
| { type: "PARTICLE_REMOVED"; fallbackParticleId: string | null }
|
| { type: "PARTICLE_ADDED"; particleId: string }
|
||||||
|
| { type: "PARTICLE_REMOVED"; removedParticleId: string; fallbackParticleId: string | null }
|
||||||
| { type: "PAUSE" }
|
| { type: "PAUSE" }
|
||||||
| { type: "RESUME" };
|
| { type: "RESUME" };
|
||||||
|
|
||||||
@@ -49,7 +50,13 @@ function playbackReducer(state: PlaybackState, action: PlaybackAction): Playback
|
|||||||
};
|
};
|
||||||
case "END":
|
case "END":
|
||||||
return { ...state, status: "ended", paused: false };
|
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":
|
case "PARTICLE_REMOVED":
|
||||||
|
if (action.removedParticleId !== state.currentParticleId) return state;
|
||||||
if (action.fallbackParticleId) {
|
if (action.fallbackParticleId) {
|
||||||
return { ...state, currentParticleId: action.fallbackParticleId, status: "playing" };
|
return { ...state, currentParticleId: action.fallbackParticleId, status: "playing" };
|
||||||
}
|
}
|
||||||
@@ -86,13 +93,29 @@ export function useStreamPlayback(
|
|||||||
path: ParticlePath,
|
path: ParticlePath,
|
||||||
): UseStreamPlaybackResult {
|
): UseStreamPlaybackResult {
|
||||||
const userId = useAuthStore((s) => s.user?.id);
|
const userId = useAuthStore((s) => s.user?.id);
|
||||||
const { children } = useLiveParticleChildren(path, "created_at", "asc");
|
|
||||||
|
|
||||||
const [state, dispatch] = useReducer(playbackReducer, initialState);
|
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
|
// Track the stream ID we've initialized for, to reset when navigating between streams
|
||||||
const initializedForRef = useRef<string | null>(null);
|
const initializedForRef = useRef<string | null>(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
|
// Derive current index and particle from ID
|
||||||
const currentIndex = useMemo(() => {
|
const currentIndex = useMemo(() => {
|
||||||
if (!state.currentParticleId) return -1;
|
if (!state.currentParticleId) return -1;
|
||||||
@@ -101,15 +124,18 @@ export function useStreamPlayback(
|
|||||||
|
|
||||||
const currentParticle = currentIndex !== -1 ? children[currentIndex] : null;
|
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 ---
|
// --- Init logic: runs on every children change until initialized ---
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Reset if we navigated to a different stream
|
// Reset if we navigated to a different stream
|
||||||
if (initializedForRef.current !== null && initializedForRef.current !== streamParticle.id) {
|
if (initializedForRef.current !== null && initializedForRef.current !== streamParticle.id) {
|
||||||
initializedForRef.current = null;
|
initializedForRef.current = null;
|
||||||
if (initTimeoutRef.current) {
|
|
||||||
clearTimeout(initTimeoutRef.current);
|
|
||||||
initTimeoutRef.current = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Already initialized for this stream
|
// Already initialized for this stream
|
||||||
@@ -132,63 +158,16 @@ export function useStreamPlayback(
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (found) {
|
if (found) {
|
||||||
// Found it — init immediately
|
|
||||||
initializedForRef.current = streamParticle.id;
|
initializedForRef.current = streamParticle.id;
|
||||||
if (initTimeoutRef.current) {
|
|
||||||
clearTimeout(initTimeoutRef.current);
|
|
||||||
initTimeoutRef.current = null;
|
|
||||||
}
|
|
||||||
dispatch({ type: "INIT", particleId: found.id });
|
dispatch({ type: "INIT", particleId: found.id });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Marker target not found yet — start timeout if not already running
|
// Marker target not found yet — fall back after timeout
|
||||||
if (!initTimeoutRef.current) {
|
const timeout = setTimeout(initFallback, INIT_FALLBACK_TIMEOUT_MS);
|
||||||
initTimeoutRef.current = setTimeout(() => {
|
return () => clearTimeout(timeout);
|
||||||
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]);
|
}, [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 ---
|
// --- Persist playback marker ---
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!userId || !state.initialized || !currentParticle) return;
|
if (!userId || !state.initialized || !currentParticle) return;
|
||||||
|
|||||||
@@ -132,6 +132,8 @@ export function subscribeToParticleChildren(
|
|||||||
visibilityScopes: string[] = [],
|
visibilityScopes: string[] = [],
|
||||||
orderByField: string = "created_at",
|
orderByField: string = "created_at",
|
||||||
orderDirection: "asc" | "desc" = "desc",
|
orderDirection: "asc" | "desc" = "desc",
|
||||||
|
onAdded?: (child: Particle) => void,
|
||||||
|
onRemoved?: (child: Particle, updatedChildren: Particle[]) => void,
|
||||||
): Unsubscribe {
|
): Unsubscribe {
|
||||||
let q = query(typedCollection(collectionPath), orderBy(orderByField, orderDirection));
|
let q = query(typedCollection(collectionPath), orderBy(orderByField, orderDirection));
|
||||||
if (visibilityScopes.length > 0) {
|
if (visibilityScopes.length > 0) {
|
||||||
@@ -143,11 +145,15 @@ export function subscribeToParticleChildren(
|
|||||||
return onSnapshot(
|
return onSnapshot(
|
||||||
q,
|
q,
|
||||||
(snap) => {
|
(snap) => {
|
||||||
// onNext(snap.docChanges().map((change) => {
|
const updatedChildren = snap.docs.map((d) => d.data());
|
||||||
// const data = change.doc.data();
|
onData(updatedChildren);
|
||||||
// return { type: change.type, data };
|
|
||||||
// }));
|
if (onAdded || onRemoved) {
|
||||||
onData(snap.docs.map((d) => d.data()));
|
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,
|
onError,
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in New Issue
Block a user