-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.jsx
230 lines (192 loc) · 6.48 KB
/
main.jsx
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
import * as React from 'react'
import {render} from 'react-dom'
import Peer from 'peerjs'
// awful snowpack hack
const {useEffect, useRef, useState} = React
const entry = document.getElementById('main')
const randID = () => Math.random().toString(36).substr(2, 10)
function copyID(ev) {
const rng = document.createRange()
rng.selectNode(ev.target)
window.getSelection().removeAllRanges()
window.getSelection().addRange(rng)
document.execCommand('copy')
window.getSelection().removeAllRanges()
}
// largely broken
function useSpeech() {
const [result, setResult] = useState('')
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
const rec = new SpeechRecognition()
rec.continuous = true
rec.lang = 'en-US'
rec.interimResults = true
// bind the result handler for parsing the results
// add a handler for results
// hack to make sure it's continuous in firefox??
rec.addEventListener('end', () => rec.start())
rec.start()
rec.addEventListener("result", ev => {
setResult(res => [...res, ev])
})
return result
}
function useChat(peer) {
const [messages, setMessages] = useState([])
peer.on('connection', (conn) => {
conn.on('open', () => conn.on('data', (data) => {
const msg = JSON.parse(data)
if (msg.type !== 'chat') return
setMessages(msgs => {
const tail = msgs[msgs.length - 1]
if (tail && tail.id === `t-${msg.id}`) return msgs
return [...msgs, {id: `t-${msg.id}`, from: 'them', text: msg.text}]
})
}))
})
return {messages, setMessages}
}
const App = () => {
const idInit = randID()
const id = useRef(idInit)
const peer = useRef(new Peer(idInit))
const [stream, setStream] = useState(null)
const [muted, setMuted] = useState(false)
const [partner, setPartner] = useState(null)
const [showChat, setChat] = useState(false)
const [sharing, setSharing] = useState(false)
const them = useRef(null)
const idIn = useRef(null)
const video = useRef(null)
const theirScreen = useRef(null)
const {messages, setMessages} = useChat(peer.current)
const toggleChat = () => setChat(cur => !cur)
function sendMessage(ev) {
if (ev.key !== 'Enter') return
const id = randID()
// @todo: cleanup
partner.send(JSON.stringify({id, type: 'chat', text: ev.target.value.trim()}))
setMessages(msgs => [...msgs, {id: `m-${id}`, from: 'me', text: ev.target.value.trim()}])
setTimeout(() => ev.target.value = '', 10)
}
async function share() {
const opts = {video: {cursor: 'always'}, audio: false}
const capture = await navigator.mediaDevices.getDisplayMedia(opts)
peer.current.call(idIn.current.value, capture)
}
function call() {
const dial = peer.current.call(idIn.current.value, stream)
dial.on('stream', (remote) => {
them.current.srcObject = remote
them.current.play()
const conn = peer.current.connect(idIn.current.value)
conn.on('open', () => setPartner(conn))
})
}
const tryCall = ({key}) => key === "Enter" && call()
async function mute() {
setMuted((state) => {
// set enabled to what we're inverting to
stream.getAudioTracks().forEach((track) => track.enabled = state)
return !state
})
}
useEffect(() => {
if (!stream) {
navigator.mediaDevices
.getUserMedia({audio: true, video: true})
.then((s) => setStream(s))
} else {
video.current.srcObject = stream
video.current.play()
peer.current.on('call', (dial) => {
idIn.current.value = dial.peer
dial.answer(stream)
dial.on('stream', (remote) => {
// make sure we're not already streaming
// prevents us playing the webcam doubly in the screen share box
if (!them.current.paused && them.current.dataset.id === remote.id) return
// if 'them' (cam) is paused, play their cam there
if (them.current.paused) {
them.current.dataset.id = remote.id
them.current.srcObject = remote
them.current.play()
// else, we've called, so we must want to share screens
} else {
theirScreen.current.srcObject = remote
theirScreen.current.play()
setSharing(true)
}
const conn = peer.current.connect(dial.peer)
conn.on('open', () => setPartner(conn))
})
})
}
}, [stream])
return (
<main className="p-8">
<div>
<p className="h-12">
<span className="px-4 py-2 text-sm whitespace-no-wrap bg-gray-300 border-2 border-r-0 rounded-l">Your ID:</span>
<span
className="w-full px-4 py-2 bg-white border-2 rounded-r cursor-pointer"
onClick={copyID}
>
{id.current}
</span>
</p>
<div className="flex">
<span className="px-4 py-2 text-sm whitespace-no-wrap bg-gray-300 border-2 border-r-0 rounded-l">Partner ID:</span>
<input
ref={idIn}
onKeyUp={tryCall}
name="field_name"
className="px-4 py-2 border-2 rounded-r"
type="text"
placeholder="Enter your partner's ID"
/>
</div>
</div>
<div className="my-4 grid grid-cols-10 grid-rows-2 gap-8">
<section className={`${showChat ? 'col-span-4' : 'col-span-5'} bg-white shadow`}>
<video muted ref={video} className="us" />
<div className="flex flex-wrap justify-center px-4 py-2 sm:flex-nowrap md:justify-between">
<button type="button" onClick={mute}>Mute (muted: {muted.toString()})</button>
<button type="button" onClick={share}>Share screen</button>
<button type="button" onClick={toggleChat}>{showChat ? 'hide' : 'show'} chat</button>
</div>
</section>
<section className={`${showChat ? 'col-span-4' : 'col-span-5'} bg-white shadow`}>
<h2 className="py-2 text-center">Your Partner</h2>
<video ref={them} />
</section>
<section className={`${showChat || 'hidden'} col-span-2 ${sharing && 'row-span-2'} flex flex-col justify-between shadow bg-white`}>
<h2 className="py-2 text-center">Chat</h2>
<div className="flex-1 px-2 break-words">
{messages.map(message => (
<div className={`message ${message.from}`}>
<div key={message.id}>
<p>{message.text}</p>
</div>
</div>
))}
</div>
<div className="flex border-t-2">
<span className="px-4 py-2 text-sm whitespace-no-wrap bg-gray-300">Chat:</span>
<input
onKeyUp={sendMessage}
name="field_name"
className="w-full px-4 py-2"
type="text"
placeholder="Send a message..."
/>
</div>
</section>
<section className={`${showChat ? 'col-span-8' : 'col-span-10'}`}>
<video ref={theirScreen} />
</section>
</div>
</main>
)
}
render(<App />, entry)