1
1
import { darkAtom } from "@/hooks/useTheme" ;
2
2
import { replayReloadContinuation } from "@/lib/ytChatTokenGen" ;
3
3
import { videoStatusAtomFamily } from "@/store/player" ;
4
- import { useAtomValue } from "jotai" ;
4
+ import { getDefaultStore , useAtomValue } from "jotai" ;
5
5
import { useEffect , useRef } from "react" ;
6
-
7
6
interface YTChatProps {
8
7
id : string ;
9
8
status : VideoStatus ;
10
9
channelId ?: string ;
11
10
}
12
11
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
+
13
31
export function YTChat ( { id, status, channelId } : YTChatProps ) {
14
32
const dark = useAtomValue ( darkAtom ) ;
15
33
const ref = useRef < HTMLIFrameElement > ( null ) ;
@@ -30,26 +48,34 @@ export function YTChat({ id, status, channelId }: YTChatProps) {
30
48
? `https://www.youtube.com/live_chat_replay?${ q } `
31
49
: `https://www.youtube.com/live_chat?${ q } ` ;
32
50
33
- const videoStatus = useAtomValue ( videoStatusAtomFamily ( id ) ) ;
51
+ // const videoStatus = useAtomValue(videoStatusAtomFamily(id));
34
52
35
53
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 ] ) ;
48
74
49
75
return (
50
76
< iframe
51
77
className = "flex grow"
52
- key = { src } // prevent push history
78
+ key = { src }
53
79
ref = { ref }
54
80
src = { src }
55
81
onLoad = { ( ) => {
0 commit comments