-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpaceProvider.tsx
112 lines (96 loc) · 2.85 KB
/
SpaceProvider.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import React, { ReactNode, useEffect, useRef, useState } from "react";
import {
LocalParticipant,
RemoteParticipant,
Space,
SpaceEvent,
} from "@mux/spaces-web";
import { MuxContext } from "./MuxContext";
import { UserMediaProvider } from "./UserMediaProvider";
import { DisplayMediaProvider } from "./DisplayMediaProvider";
type Props = {
jwt?: string;
children: ReactNode;
defaultAudioDeviceId?: string;
defaultVideoDeviceId?: string;
};
export const SpaceProvider: React.FC<Props> = ({
children,
jwt,
defaultAudioDeviceId = "",
defaultVideoDeviceId = "",
}) => {
const spaceRef = useRef<Space | null>(null);
const [participants, setParticipants] = useState<RemoteParticipant[]>([]);
const [localParticipant, setLocalParticipant] =
useState<LocalParticipant | null>(null);
const [joinError, setJoinError] = useState<string | null>(null);
useEffect(() => {
if (!jwt) {
return;
}
(window as any).MUX_SPACES_ENABLE_SIMULCAST = true;
let space: Space;
try {
space = new Space(jwt);
console.log("this is the space jwt string : ", space);
} catch (e: any) {
setJoinError(e.message);
return;
}
const handleParticipantJoined = (newParticipant: RemoteParticipant) => {
setParticipants((oldParticipantArray) => {
const found = oldParticipantArray.find(
(p) => p.connectionId === newParticipant.connectionId
);
if (!found) {
return [...oldParticipantArray, newParticipant];
}
return oldParticipantArray;
});
};
const handleParticipantLeft = (participantLeaving: RemoteParticipant) => {
setParticipants((oldParticipantArray) =>
oldParticipantArray.filter(
(p) => p.connectionId !== participantLeaving.connectionId
)
);
};
space.on(SpaceEvent.ParticipantJoined, handleParticipantJoined);
space.on(SpaceEvent.ParticipantLeft, handleParticipantLeft);
space
.join()
.then((_localParticipant: LocalParticipant) => {
setLocalParticipant(_localParticipant);
})
.catch((error) => {
setJoinError(error.message);
});
spaceRef.current = space;
return () => {
space.off(SpaceEvent.ParticipantJoined, handleParticipantJoined);
space.off(SpaceEvent.ParticipantLeft, handleParticipantLeft);
setParticipants([]);
space.leave();
};
}, [jwt, setJoinError]);
return (
<MuxContext.Provider
value={{
space: spaceRef.current,
participants,
localParticipant,
joinError,
}}
>
<DisplayMediaProvider>
<UserMediaProvider
defaultAudioDeviceId={defaultAudioDeviceId}
defaultVideoDeviceId={defaultVideoDeviceId}
>
{children}
</UserMediaProvider>
</DisplayMediaProvider>
</MuxContext.Provider>
);
};