Files
llink/js/src/hooks/use-stream-autoplay.ts
T

42 lines
1.3 KiB
TypeScript

import { useEffect, useRef } from "react";
import beepSound from "../../assets/sound.wav";
import type { Particle, StreamProperties } from "@/api/types";
import { useAuthStore } from "@/stores/auth-store";
import { useAutoplayStore } from "@/stores/autoplay-store";
/**
* Triggers autoplay when a stream's latest child changes to a new media particle.
* Plays a beep sound for new text particles from other users.
*/
export function useStreamAutoplay(
latestChild: Particle | null,
streamParticle: Particle & { type: "stream"; properties: StreamProperties },
) {
const userId = useAuthStore((s) => s.user?.id) ?? "";
const settledIdRef = useRef<string | undefined>(undefined);
useEffect(() => {
if (!latestChild) return;
// First real value: record as baseline, don't autoplay
if (settledIdRef.current === undefined) {
settledIdRef.current = latestChild.id;
return;
}
if (latestChild.id === settledIdRef.current) return;
settledIdRef.current = latestChild.id;
if (latestChild.created_by_human_id === userId) return;
if (latestChild.type === "text") {
new Audio(beepSound).play().catch(() => {});
return;
}
if (latestChild.type !== "media") return;
useAutoplayStore.getState().play(latestChild, streamParticle.id);
}, [latestChild?.id]); // eslint-disable-line react-hooks/exhaustive-deps
}