-
-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathtrackpad.tsx
More file actions
341 lines (301 loc) · 8.57 KB
/
trackpad.tsx
File metadata and controls
341 lines (301 loc) · 8.57 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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import { BufferBar } from "@/components/Trackpad/Buffer"
import type { ModifierState } from "@/types"
import { createFileRoute } from "@tanstack/react-router"
import { useRef, useState, useEffect } from "react"
import { ControlBar } from "../components/Trackpad/ControlBar"
import { ExtraKeys } from "../components/Trackpad/ExtraKeys"
import { TouchArea } from "../components/Trackpad/TouchArea"
import { useRemoteConnection } from "../hooks/useRemoteConnection"
import { useTrackpadGesture } from "../hooks/useTrackpadGesture"
import { ScreenMirror } from "../components/Trackpad/ScreenMirror"
export const Route = createFileRoute("/trackpad")({
component: TrackpadPage,
})
type ClipboardMessage = {
type: "clipboard-text"
text: string
}
function TrackpadPage() {
const [scrollMode, setScrollMode] = useState(false)
const [modifier, setModifier] = useState<ModifierState>("Release")
const [buffer, setBuffer] = useState<string[]>([])
const bufferText = buffer.join(" + ")
const hiddenInputRef = useRef<HTMLInputElement>(null)
const isComposingRef = useRef(false)
const [keyboardOpen, setKeyboardOpen] = useState(false)
const [extraKeysVisible, setExtraKeysVisible] = useState(true)
// Load Client Settings
const [sensitivity] = useState(() => {
if (typeof window === "undefined") return 1.0
const s = localStorage.getItem("rein_sensitivity")
return s ? Number.parseFloat(s) : 1.0
})
const [invertScroll] = useState(() => {
if (typeof window === "undefined") return false
const s = localStorage.getItem("rein_invert")
return s ? JSON.parse(s) : false
})
const { send, sendCombo, subscribe } = useRemoteConnection()
// Pass sensitivity and invertScroll to the gesture hook
const { isTracking, handlers } = useTrackpadGesture(
send,
scrollMode,
sensitivity,
invertScroll,
)
// When keyboardOpen changes, focus or blur the hidden input
useEffect(() => {
if (keyboardOpen) {
hiddenInputRef.current?.focus()
} else {
hiddenInputRef.current?.blur()
}
}, [keyboardOpen])
useEffect(() => {
const unsubscribe = subscribe("clipboard-text", async (msg) => {
const data = msg as ClipboardMessage
try {
const text = data.text || ""
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text)
} else {
const textarea = document.createElement("textarea")
textarea.value = text
document.body.appendChild(textarea)
textarea.select()
document.execCommand("copy")
document.body.removeChild(textarea)
}
} catch (err) {
console.error("Clipboard write failed", err)
}
})
return () => unsubscribe()
}, [subscribe])
const toggleKeyboard = () => {
setKeyboardOpen((prev) => !prev)
}
const focusInput = () => {
hiddenInputRef.current?.focus()
}
const handleClick = (button: "left" | "right") => {
send({ type: "click", button, press: true })
// Release after short delay to simulate click
setTimeout(() => send({ type: "click", button, press: false }), 50)
}
const handleCopy = () => {
// copy from SERVER → CLIENT
send({ type: "clipboard-pull" })
}
const handlePaste = async () => {
// paste from CLIENT → SERVER
try {
let text = ""
if (navigator.clipboard && window.isSecureContext) {
text = await navigator.clipboard.readText()
} else {
text = window.getSelection()?.toString() || ""
}
send({
type: "clipboard-push",
text,
})
} catch (err) {
console.error("Paste failed", err)
}
}
const handleInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const nativeEvent = e.nativeEvent as InputEvent
const inputType = nativeEvent.inputType
const data = nativeEvent.data
const val = e.target.value
const resetInput = () => {
if (hiddenInputRef.current) {
hiddenInputRef.current.value = " "
hiddenInputRef.current.setSelectionRange(1, 1)
}
}
// 1. Backspace
if (inputType === "deleteContentBackward" || val.length === 0) {
send({ type: "key", key: "backspace" })
resetInput()
return
}
// 2. Enter
if (inputType === "insertLineBreak" || inputType === "insertParagraph") {
send({ type: "key", key: "enter" })
resetInput()
return
}
// 3. Text
// Early return only for EXPLICIT composition text that isn't finished
if (isComposingRef.current && inputType === "insertCompositionText") {
return
}
const textToSend = data || (val.length > 1 ? val.slice(1) : null)
if (textToSend) {
if (modifier !== "Release") {
handleModifier(textToSend)
} else {
if (textToSend === " ") {
send({ type: "key", key: "space" })
} else {
send({ type: "text", text: textToSend })
}
}
resetInput()
}
}
const handleCompositionStart = () => {
isComposingRef.current = true
}
const handleCompositionEnd = (
e: React.CompositionEvent<HTMLInputElement>,
) => {
isComposingRef.current = false
const val = (e.target as HTMLInputElement).value
const textToSend = val.startsWith(" ") ? val.slice(1) : val
if (textToSend) {
if (modifier !== "Release") {
handleModifier(textToSend)
} else {
send({ type: "text", text: textToSend })
}
}
if (hiddenInputRef.current) {
hiddenInputRef.current.value = " "
hiddenInputRef.current.setSelectionRange(1, 1)
}
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
const key = e.key.toLowerCase()
// 1. Enter key fallback
if (key === "enter") {
send({ type: "key", key: "enter" })
if (hiddenInputRef.current) {
hiddenInputRef.current.value = " "
}
return
}
// 2. Modifier Logic
if (modifier !== "Release") {
if (key === "escape") {
e.preventDefault()
setModifier("Release")
setBuffer([])
return
}
if (key.length > 1 && key !== "unidentified" && key !== "backspace") {
e.preventDefault()
handleModifier(key)
return
}
}
// 3. Special keys (Arrows, Tab, etc.)
if (
key.length > 1 &&
key !== "unidentified" &&
key !== "backspace" &&
key !== "process"
) {
send({ type: "key", key })
}
}
const handleModifierState = () => {
switch (modifier) {
case "Active":
if (buffer.length > 0) setModifier("Hold")
else setModifier("Release")
break
case "Hold":
setModifier("Release")
setBuffer([])
break
case "Release":
setModifier("Active")
setBuffer([])
break
}
}
const handleModifier = (key: string) => {
if (modifier === "Hold") {
const comboKeys = [...buffer, key]
sendCombo(comboKeys)
} else if (modifier === "Active") {
setBuffer((prev) => [...prev, key])
}
}
return (
<div className="flex flex-col h-full min-h-0 bg-base-300 overflow-hidden">
{/* TOUCH AREA */}
<div className="flex-1 min-h-0 relative flex flex-col border-b border-base-200">
<TouchArea
isTracking={isTracking}
scrollMode={scrollMode}
handlers={handlers}
/>
<ScreenMirror
isTracking={isTracking}
scrollMode={scrollMode}
handlers={handlers}
/>
{bufferText !== "" && <BufferBar bufferText={bufferText} />}
</div>
{/* CONTROL BAR */}
<div className="shrink-0 border-b border-base-200">
<ControlBar
onCopy={handleCopy}
onPaste={handlePaste}
scrollMode={scrollMode}
modifier={modifier}
buffer={buffer.join(" + ")}
keyboardOpen={keyboardOpen}
extraKeysVisible={extraKeysVisible}
onToggleScroll={() => setScrollMode(!scrollMode)}
onLeftClick={() => handleClick("left")}
onRightClick={() => handleClick("right")}
onKeyboardToggle={toggleKeyboard}
onModifierToggle={handleModifierState}
onExtraKeysToggle={() => setExtraKeysVisible((prev) => !prev)}
/>
</div>
<div
className={`shrink-0 overflow-hidden transition-all duration-300
${
!extraKeysVisible || keyboardOpen
? "max-h-0 opacity-0 pointer-events-none"
: "max-h-[50vh] opacity-100"
}`}
>
<ExtraKeys
sendKey={(k) => {
if (modifier !== "Release") handleModifier(k)
else send({ type: "key", key: k })
}}
onInputFocus={focusInput}
/>
</div>
{/* Hidden Input for Mobile Keyboard */}
<input
ref={hiddenInputRef}
className="opacity-0 absolute bottom-0 pointer-events-none h-0 w-0"
defaultValue=" "
onKeyDown={handleKeyDown}
onChange={handleInput}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
onBlur={() => {
if (keyboardOpen) {
setTimeout(() => hiddenInputRef.current?.focus(), 10)
}
}}
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
spellCheck={false}
inputMode="text"
enterKeyHint="enter"
/>
</div>
)
}