-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDailyContainer.js
More file actions
286 lines (258 loc) · 8.14 KB
/
DailyContainer.js
File metadata and controls
286 lines (258 loc) · 8.14 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import { useCallback, useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import DailyIframe from '@daily-co/daily-js';
import JoinForm from '../JoinForm/JoinForm';
import AdminPanel from '../AdminPanel/AdminPanel';
import api from '../../daily';
import './daily-container.css';
export default function DailyContainer() {
const searchParams = useSearchParams();
const containerRef = useRef(null);
const [callFrame, setCallFrame] = useState(null);
const [url, setUrl] = useState(null);
const [isAdmin, setIsAdmin] = useState(false);
const [isOwner, setIsOwner] = useState(false);
const [error, setError] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [participants, setParticipants] = useState({});
const prevParticipants = useRef();
useEffect(() => {
prevParticipants.current = participants;
}, [participants]);
useEffect(() => {
const urlParam = searchParams.get('url');
if (urlParam) {
setUrl(urlParam);
}
}, [searchParams]);
const handleJoinedMeeting = (e) => {
console.log(e.action);
setParticipants((p) => ({
...p,
[e.participants.local.session_id]: e.participants.local,
}));
};
const handleParticipantJoined = (e) => {
console.log(e.action);
setParticipants((p) => ({
...p,
[e.participant.session_id]: e.participant,
}));
};
const handleParticipantUpdate = (e) => {
console.log(e.action);
// Return early if the participant list isn't set yet.
// This event is sometimes emitted before the joined-meeting event.
const { participant } = e;
const id = participant.session_id;
if (!prevParticipants.current[id]) return;
// Only update the participants list if the permission has changed.
// Daily Prebuilt handles all other call changes for us.
if (
prevParticipants.current[id].permissions.canAdmin !==
participant.permissions.canAdmin
) {
setParticipants((p) => ({
...p,
[id]: participant,
}));
if (participant.local) {
setIsAdmin(participant.permissions.canAdmin);
}
}
};
const handleParticipantLeft = (e) => {
console.log(e.action);
setParticipants((p) => {
const currentParticipants = { ...p };
delete currentParticipants[e.participant.session_id];
return currentParticipants;
});
};
const handleError = (e) => {
console.log(e.action);
setError(e.errorMsg);
};
const handleLeftMeeting = useCallback(
(e) => {
console.log(e.action);
if (callFrame) {
// https://docs.daily.co/reference/daily-js/instance-methods/off
callFrame
.off('joined-meeting', handleJoinedMeeting)
.off('participant-joined', handleParticipantJoined)
.off('participant-updated', handleParticipantUpdate)
.off('participant-left', handleParticipantLeft)
.off('error', handleError);
}
// Reset state
setCallFrame(null);
setIsAdmin(false);
setSubmitting(false);
setParticipants({});
},
[callFrame]
);
const addDailyEvents = (dailyCallFrame) => {
// https://docs.daily.co/reference/daily-js/instance-methods/on
dailyCallFrame
.on('joined-meeting', handleJoinedMeeting)
.on('participant-joined', handleParticipantJoined)
.on('participant-updated', handleParticipantUpdate)
.on('participant-left', handleParticipantLeft)
.on('left-meeting', handleLeftMeeting)
.on('error', handleError);
};
const joinRoom = async ({ name, roomURL, token, localIsOwner }) => {
const callContainerDiv = containerRef.current;
// https://docs.daily.co/reference/daily-js/factory-methods/create-frame
const dailyCallFrame = DailyIframe.createFrame(callContainerDiv, {
iframeStyle: {
width: '100%',
height: '100%',
},
});
addDailyEvents(dailyCallFrame);
const options = { userName: name, url: roomURL };
if (token) {
setIsOwner(localIsOwner);
options.token = token;
}
setSubmitting(true);
try {
// https://docs.daily.co/reference/daily-js/instance-methods/join
await dailyCallFrame.join(options);
setCallFrame(dailyCallFrame);
setUrl(roomURL);
setSubmitting(false);
} catch (e) {
console.error(e);
setSubmitting(false);
}
};
const createToken = async (options) => {
const { token } = await api.createToken(options);
if (token) {
return token;
}
console.error('Token creation failed.');
return null;
};
const createNewRoom = async () => {
const newRoom = await api.createRoom();
if (!newRoom.url) {
console.error('Room could not be created. Please try again.');
return null;
}
return newRoom;
};
const handleSubmitJoinForm = async (e) => {
e.preventDefault();
// Clear previous error
setError(null);
const { target } = e;
const options = { name: target.name.value };
// Use the existing room supplied in the query param if it's provided (or create a new room)
const existingRoomUrl = target?.url?.value;
if (existingRoomUrl) {
options.roomURL = existingRoomUrl;
const [, roomName] = existingRoomUrl.split('.co/');
options.roomName = roomName;
options.localIsOwner = false;
} else {
// Create a new Daily room when the form is submitted
const newRoom = await createNewRoom();
if (!newRoom) return; // error is thrown in createNewRoom
options.roomURL = newRoom.url;
options.roomName = newRoom.name;
options.localIsOwner = true;
// Create an owner meeting token
const newToken = await createToken({
roomName: newRoom.name,
isOwner: true,
});
if (!newToken) return; // error is thrown in createToken
options.token = newToken;
}
joinRoom(options);
};
const removeFromCall = useCallback(
(participantId) => {
// https://docs.daily.co/reference/daily-js/instance-methods/update-participant#setaudio-setvideo-and-eject
callFrame.updateParticipant(participantId, {
eject: true,
});
},
[callFrame]
);
const makeAdmin = useCallback(
(participantId) => {
// https://docs.daily.co/reference/daily-js/instance-methods/update-participant#permissions
callFrame.updateParticipant(participantId, {
updatePermissions: {
canAdmin: true,
},
});
},
[callFrame]
);
const leaveCall = useCallback(() => {
// https://docs.daily.co/reference/daily-js/instance-methods/leave
callFrame.leave();
// https://docs.daily.co/reference/daily-js/instance-methods/destroy
callFrame.destroy();
}, [callFrame]);
const localLink = useCallback(
() => `http://localhost:3000/?url=${url}`,
[url]
);
return (
<div className='daily-container'>
{error && (
<p className='error-msg'>
Error message: {error}. Refresh to start over.
</p>
)}
{!callFrame && !submitting && !error && (
<>
<h3>Create a new Daily room and join as an owner.</h3>
<JoinForm handleSubmitForm={handleSubmitJoinForm} url={url} />
</>
)}
{submitting && <p>Loading...</p>}
{callFrame && (
<>
<p>
<span>Share this link to let others join:</span>{' '}
<a href={localLink()} target='_blank' rel='noopener noreferrer'>
{localLink()}
</a>
</p>
<p>
External Daily room URL:{' '}
<a href={url} target='_blank' rel='noopener noreferrer'>
{url}
</a>
</p>
</>
)}
{callFrame && (
<>
<AdminPanel
participants={participants}
localIsOwner={isOwner}
localIsAdmin={isAdmin}
makeAdmin={makeAdmin}
removeFromCall={removeFromCall}
/>
<div className='call-header'>
<button className='red-button' onClick={leaveCall}>
Leave this call
</button>
</div>
</>
)}
<div className='call' ref={containerRef}></div>
</div>
);
}