forked from libp2p/universal-connectivity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.tsx
319 lines (294 loc) · 11.1 KB
/
chat.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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import { useLibp2pContext } from '@/context/ctx'
import React, { useCallback, useEffect, useState } from 'react'
import { Message } from '@libp2p/interface-pubsub'
import { CHAT_TOPIC } from '@/lib/constants'
import { createIcon } from '@download/blockies'
import { ChatMessage, useChatContext } from '../context/chat-ctx'
interface MessageProps extends ChatMessage { }
function Message({ msg, from, peerId }: MessageProps) {
const msgref = React.useRef<HTMLLIElement>(null)
const { libp2p } = useLibp2pContext()
useEffect(() => {
const icon = createIcon({
seed: peerId,
size: 15,
scale: 3,
})
icon.className = 'rounded mr-2 max-h-10 max-w-10'
const childrenCount = msgref.current?.childElementCount
// Prevent inserting an icon more than once.
if (childrenCount && childrenCount < 2) {
msgref.current?.insertBefore(icon, msgref.current?.firstChild)
}
}, [peerId])
return (
<li ref={msgref} className={`flex ${from === 'me' ? 'justify-end' : 'justify-start'}`}>
<div
className="flex relative max-w-xl px-4 py-2 text-gray-700 rounded shadow bg-white"
>
<div className="block">
{msg}
<p className="italic text-gray-400">{peerId !== libp2p.peerId.toString() ? `from: ${peerId.slice(-4)}` : null} </p>
</div>
</div>
</li>
)
}
export default function ChatContainer() {
const { libp2p } = useLibp2pContext()
const { messageHistory, setMessageHistory } = useChatContext();
const [input, setInput] = useState<string>('')
// Effect hook to subscribe to pubsub events and update the message state hook
useEffect(() => {
const messageCB = (evt: CustomEvent<Message>) => {
console.log('gossipsub console log', evt.detail)
// FIXME: Why does 'from' not exist on type 'Message'?
const { topic, data } = evt.detail
const msg = new TextDecoder().decode(data)
console.log(`${topic}: ${msg}`)
// Append signed messages, otherwise discard
if (evt.detail.type === 'signed') {
setMessageHistory([...messageHistory, { msg, from: 'other', peerId: evt.detail.from.toString() }])
}
}
libp2p.services.pubsub.addEventListener('message', messageCB)
return () => {
// Cleanup handlers 👇
// libp2p.pubsub.unsubscribe(CHAT_TOPIC)
libp2p.services.pubsub.removeEventListener('message', messageCB)
}
}, [libp2p, messageHistory, setMessageHistory])
const sendMessage = useCallback(async () => {
if (input === '') return
console.log(
'peers in gossip:',
libp2p.services.pubsub.getSubscribers(CHAT_TOPIC).toString(),
)
const res = await libp2p.services.pubsub.publish(
CHAT_TOPIC,
new TextEncoder().encode(input),
)
console.log(
'sent message to: ',
res.recipients.map((peerId) => peerId.toString()),
)
const myPeerId = libp2p.peerId.toString()
setMessageHistory([...messageHistory, { msg: input, from: 'me', peerId: myPeerId }])
setInput('')
}, [input, messageHistory, setInput, libp2p, setMessageHistory])
const handleKeyUp = useCallback(
async (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key !== 'Enter') {
return
}
sendMessage()
},
[sendMessage],
)
const handleSend = useCallback(
async (e: React.MouseEvent<HTMLButtonElement>) => {
sendMessage()
},
[sendMessage],
)
const handleInput = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
setInput(e.target.value)
},
[setInput],
)
return (
<div className="container mx-auto">
<div className="min-w-full border rounded lg:grid lg:grid-cols-3">
{/* <RoomList /> */}
<div className="lg:col-span-3 lg:block">
<div className="w-full">
<div className="relative flex items-center p-3 border-b border-gray-300">
{/* disable
<img
className="object-cover w-10 h-10 rounded-full"
src="https://github.com/achingbrain.png"
alt="username"
/>
<span className="absolute w-3 h-3 bg-green-600 rounded-full left-10 top-3"></span> */}
<span className="text-3xl">💁🏽♀️💁🏿♂️</span>
<span className="block ml-2 font-bold text-gray-600">
Public Chat
</span>
</div>
<div className="relative w-full p-6 overflow-y-auto h-[40rem] bg-gray-100">
<ul className="space-y-2">
{/* messages start */}
{messageHistory.map(({ msg, from, peerId }, idx) => (
<Message key={idx} msg={msg} from={from} peerId={peerId} />
))}
{/* messages end */}
</ul>
</div>
<div className="flex items-center justify-between w-full p-3 border-t border-gray-300">
<button>
<svg
xmlns="http://www.w3.org/2000/svg"
className="w-6 h-6 text-gray-500"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
</button>
<button>
<svg
xmlns="http://www.w3.org/2000/svg"
className="w-5 h-5 text-gray-500"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"
/>
</svg>
</button>
<input
value={input}
onKeyUp={handleKeyUp}
onChange={handleInput}
type="text"
placeholder="Message"
className="block w-full py-2 pl-4 mx-3 bg-gray-100 rounded-full outline-none focus:text-gray-700"
name="message"
required
/>
<button>
<svg
xmlns="http://www.w3.org/2000/svg"
className="w-5 h-5 text-gray-500"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"
/>
</svg>
</button>
<button onClick={handleSend} type="submit">
<svg
className="w-5 h-5 text-gray-500 origin-center transform rotate-90"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
>
<path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z" />
</svg>
</button>
</div>
</div>
</div>
</div>
</div>
)
}
export function RoomList() {
return (
<div className="border-r border-gray-300 lg:col-span-1">
<div className="mx-3 my-3">
<div className="relative text-gray-600">
<span className="absolute inset-y-0 left-0 flex items-center pl-2">
<svg
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
viewBox="0 0 24 24"
className="w-6 h-6 text-gray-300"
>
<path d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
</svg>
</span>
<input
type="search"
className="block w-full py-2 pl-10 bg-gray-100 rounded outline-none"
name="search"
placeholder="Search"
required
/>
</div>
</div>
<ul className="overflow-auto h-[32rem]">
<h2 className="my-2 mb-2 ml-2 text-lg text-gray-600">Chats</h2>
<li>
<a className="flex items-center px-3 py-2 text-sm transition duration-150 ease-in-out border-b border-gray-300 cursor-pointer hover:bg-gray-100 focus:outline-none">
<img
className="object-cover w-10 h-10 rounded-full"
src="https://github.com/2color.png"
alt="username"
/>
<div className="w-full pb-2">
<div className="flex justify-between">
<span className="block ml-2 font-semibold text-gray-600">
Daniel
</span>
<span className="block ml-2 text-sm text-gray-600">
25 minutes
</span>
</div>
<span className="block ml-2 text-sm text-gray-600">bye</span>
</div>
</a>
<a className="flex items-center px-3 py-2 text-sm transition duration-150 ease-in-out bg-gray-100 border-b border-gray-300 cursor-pointer focus:outline-none">
<img
className="object-cover w-10 h-10 rounded-full"
src="https://github.com/achingbrain.png"
alt="username"
/>
<div className="w-full pb-2">
<div className="flex justify-between">
<span className="block ml-2 font-semibold text-gray-600">
Alex
</span>
<span className="block ml-2 text-sm text-gray-600">
50 minutes
</span>
</div>
<span className="block ml-2 text-sm text-gray-600">
Good night
</span>
</div>
</a>
<a className="flex items-center px-3 py-2 text-sm transition duration-150 ease-in-out border-b border-gray-300 cursor-pointer hover:bg-gray-100 focus:outline-none">
<img
className="object-cover w-10 h-10 rounded-full"
src="https://github.com/hannahhoward.png"
alt="username"
/>
<div className="w-full pb-2">
<div className="flex justify-between">
<span className="block ml-2 font-semibold text-gray-600">
Hannah
</span>
<span className="block ml-2 text-sm text-gray-600">6 hour</span>
</div>
<span className="block ml-2 text-sm text-gray-600">
Good Morning
</span>
</div>
</a>
</li>
</ul>
</div>
)
}