/
index.tsx
248 lines (199 loc) · 7.21 KB
/
index.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
import React, { useCallback, useEffect, useRef, useState } from "react";
import { DbConnection, PresenceListener, Reducer, StateListener, uniqueClientId, WrappedPresenceMessage } from "driftdb"
import { Api, RoomResult } from "driftdb/dist/api"
import { ConnectionStatus } from "driftdb/dist/types";
const ROOM_ID_KEY = "_driftdb_room"
export const DatabaseContext = React.createContext<DbConnection | null>(null);
export function useDatabase(): DbConnection {
const db = React.useContext(DatabaseContext);
if (db === null) {
throw new Error("useDatabase must be used within a DriftDBProvider");
}
return db;
}
export function RoomQRCode() {
const db = useDatabase();
const [pageUrl, setPageUrl] = React.useState<string | null>(null)
useEffect(() => {
const callback = () => {
if (typeof window === "undefined") {
return
}
const url = new URL(window.location.href)
const checkRoom = url.searchParams.get(ROOM_ID_KEY)
if (!checkRoom) {
return
}
setPageUrl(window.location.href)
return () => {
db.statusListener.removeListener(callback)
}
}
db.statusListener.addListener(callback)
}, [db])
if (pageUrl) {
return <img src={`https://api.jamsocket.live/qrcode?url=${pageUrl}`} />
} else {
return null
}
}
type SetterFunction<T> = (value: T | ((v: T) => T)) => void;
export function useSharedState<T>(key: string, initialValue: T): [T, SetterFunction<T>] {
const db = useDatabase();
const [state, setInnerState] = React.useState<T>(initialValue);
const stateListener = useRef<StateListener<T>>(null)
if (stateListener.current === null) {
(stateListener as any).current = new StateListener(setInnerState, db, key)
}
const setState = useCallback((value: T | ((v: T) => T)) => {
if (typeof value === "function") {
const currentValue = stateListener.current!.state ?? initialValue;
const newValue = (value as any)(currentValue);
stateListener.current!.setStateOptimistic(newValue);
} else {
stateListener.current!.setStateOptimistic(value);
}
}, [initialValue])
return [state, setState];
}
export function useUniqueClientId(): string {
const currentId = useRef<string>()
if (typeof window === "undefined") {
return null!
}
if (!currentId.current) {
currentId.current = uniqueClientId()
}
return currentId.current
}
export function useSharedReducer<T, A>(key: string, reducer: (state: T, action: A) => T, initialValue: any, init: ((v: any) => T) = (a: any) => a): [T, (action: A) => void] {
const db = useDatabase();
const initialStateRef = useRef<T>(null!)
if (initialStateRef.current === null) {
initialStateRef.current = structuredClone(init(initialValue))
}
const [state, setState] = React.useState<T>(initialStateRef.current);
const reducerRef = React.useRef<Reducer<T, A> | null>(null)
if (reducerRef.current === null) {
reducerRef.current = new Reducer({
key,
reducer,
initialValue: initialStateRef.current,
sizeThreshold: 30,
db,
callback: setState
})
}
const dispatch = reducerRef.current.dispatch;
return [state, dispatch];
}
export function useConnectionStatus(): ConnectionStatus {
const db = useDatabase();
const [status, setStatus] = React.useState<ConnectionStatus>({ connected: false });
React.useEffect(() => {
const callback = (event: ConnectionStatus) => {
setStatus(event);
};
db?.statusListener.addListener(callback);
return () => {
db?.statusListener.removeListener(callback);
};
}, [db]);
return status;
}
export function useLatency(): number | null {
const db = useDatabase();
const [latency, setLatency] = useState<number | null>(null!);
React.useEffect(() => {
const updateLatency = async () => {
const result = await db?.testLatency();
setLatency(result);
}
const interval = setInterval(updateLatency, 5000);
updateLatency();
return () => {
clearInterval(interval);
}
}, [db]);
return latency;
}
export function usePresence<T>(key: string, value: T): Record<string, WrappedPresenceMessage<T>> {
const db = useDatabase()
const clientId = useUniqueClientId()
const [presence, setPresence] = useState<Record<string, WrappedPresenceMessage<T>>>({})
const presenceListener = useRef<PresenceListener<T>>()
if (presenceListener.current === undefined) {
presenceListener.current = new PresenceListener({
key,
db,
clientId,
initialState: value,
callback: setPresence,
})
}
presenceListener.current.updateState(value)
return presence
}
export function StatusIndicator() {
const status = useConnectionStatus();
const latency = useLatency();
const latencyStr = latency === null ? "..." : Math.round(latency).toString();
let color
if (status.connected) {
color = "green"
} else {
color = "red"
}
return (
<div style={{ display: 'inline-block', border: '1px solid #ccc', background: '#eee', borderRadius: 10, padding: 10 }}>
DriftDB status: <span style={{ color, fontWeight: 'bold' }}>{status.connected ? "Connected" : "Disconnected"}</span>
{
status.connected ? <>
{" "}<span style={{fontSize: '70%', color: '#aaa'}}>
<a target="_blank" rel="noreferrer" style={{ textDecoration: 'none', color: '#aaa' }} href={status.debugUrl}>(ui)</a>
({latencyStr}ms)
</span>
</> : null
}
</div>
);
}
interface DriftDBProviderProps {
children: React.ReactNode
api: string
room?: string
}
export function DriftDBProvider(props: DriftDBProviderProps) {
const dbRef = useRef<DbConnection | null>(null);
if (dbRef.current === null) {
dbRef.current = new DbConnection();
}
React.useEffect(() => {
let api = new Api(props.api);
let roomId
if (props.room) {
roomId = props.room
} else {
const searchParams = new URLSearchParams(window.location.search)
roomId = searchParams.get(ROOM_ID_KEY)
}
let promise
if (roomId) {
promise = api.getRoom(roomId)
} else {
promise = api.newRoom()
}
promise.then((result: RoomResult) => {
if (!props.room) {
let url = new URL(window.location.href);
url.searchParams.set(ROOM_ID_KEY, result.room);
window.history.replaceState({}, "", url.toString());
}
dbRef.current?.connect(result.socket_url);
});
return () => {
dbRef.current?.disconnect();
}
}, []);
return <DatabaseContext.Provider value={dbRef.current}>{props.children}</DatabaseContext.Provider>;
}