Skip to content

Commit 5ab71e2

Browse files
committed
side-effect for updating iframe
1 parent 73f8cc7 commit 5ab71e2

File tree

1 file changed

+42
-16
lines changed

1 file changed

+42
-16
lines changed

packages/react/src/components/chat/YTChat.tsx

+42-16
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,33 @@
11
import { darkAtom } from "@/hooks/useTheme";
22
import { replayReloadContinuation } from "@/lib/ytChatTokenGen";
33
import { videoStatusAtomFamily } from "@/store/player";
4-
import { useAtomValue } from "jotai";
4+
import { getDefaultStore, useAtomValue } from "jotai";
55
import { useEffect, useRef } from "react";
6-
76
interface YTChatProps {
87
id: string;
98
status: VideoStatus;
109
channelId?: string;
1110
}
1211

12+
// Keep track of chat iframes to publish to
13+
const chatIframeRefs = new Map<string, HTMLIFrameElement>();
14+
15+
// Subscribe to video status updates outside of React
16+
export function subscribeToVideoProgress(videoId: string) {
17+
const videoStatusAtom = videoStatusAtomFamily(videoId);
18+
const store = getDefaultStore();
19+
return store.sub(videoStatusAtom, () => {
20+
const videoStatus = store.get(videoStatusAtom);
21+
const iframe = chatIframeRefs.get(videoId);
22+
if (iframe?.contentWindow && videoStatus?.progress !== undefined) {
23+
iframe.contentWindow.postMessage(
24+
{ "yt-player-video-progress": videoStatus.progress },
25+
"*",
26+
);
27+
}
28+
});
29+
}
30+
1331
export function YTChat({ id, status, channelId }: YTChatProps) {
1432
const dark = useAtomValue(darkAtom);
1533
const ref = useRef<HTMLIFrameElement>(null);
@@ -30,26 +48,34 @@ export function YTChat({ id, status, channelId }: YTChatProps) {
3048
? `https://www.youtube.com/live_chat_replay?${q}`
3149
: `https://www.youtube.com/live_chat?${q}`;
3250

33-
const videoStatus = useAtomValue(videoStatusAtomFamily(id));
51+
// const videoStatus = useAtomValue(videoStatusAtomFamily(id));
3452

3553
useEffect(() => {
36-
if (
37-
isArchive &&
38-
channelId &&
39-
ref.current?.contentWindow &&
40-
videoStatus?.progress !== undefined
41-
) {
42-
ref.current.contentWindow.postMessage(
43-
{ "yt-player-video-progress": videoStatus.progress },
44-
"*",
45-
);
46-
}
47-
}, [isArchive, channelId, videoStatus?.progress]);
54+
if (!ref.current || !isArchive || !channelId) return;
55+
56+
// Store ref in map
57+
chatIframeRefs.set(id, ref.current);
58+
59+
// Initialize progress
60+
ref.current.contentWindow?.postMessage(
61+
{ "yt-player-video-progress": 0 },
62+
"*",
63+
);
64+
65+
// Set up subscription
66+
const unsubscribe = subscribeToVideoProgress(id);
67+
68+
// Cleanup
69+
return () => {
70+
unsubscribe();
71+
chatIframeRefs.delete(id);
72+
};
73+
}, [id, isArchive, channelId]);
4874

4975
return (
5076
<iframe
5177
className="flex grow"
52-
key={src} // prevent push history
78+
key={src}
5379
ref={ref}
5480
src={src}
5581
onLoad={() => {

0 commit comments

Comments
 (0)