| 1 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | import { createPortal, flushSync } from "react-dom"; |
| 3 | import { ArrowDownLeft, ArrowLeft, ArrowRight, BookOpen, Check, CornerDownLeft, Delete, Globe2, Keyboard, LoaderCircle, Maximize, Monitor, RotateCw, ZoomIn, X } from "lucide-react"; |
| 4 | import { PhoneFavorites } from "./phone-favorites"; |
| 5 | import { connectDisplay, framePoint } from "./browser-session.mjs"; |
| 6 | import "./remote-browser.css"; |
| 7 | |
| 8 | function Tool({icon: Icon, label, ...props}) { |
| 9 | return <button type="button" className="icon-button" aria-label={label} title={label} {...props}> |
| 10 | <Icon size={19} aria-hidden="true" /> |
| 11 | </button>; |
| 12 | } |
| 13 | |
| 14 | function AddressBar({frame, goToAddress, onNotice}) { |
| 15 | const [address, setAddress] = useState(null); |
| 16 | const [invalid, setInvalid] = useState(false); |
| 17 | const [submitting, setSubmitting] = useState(false); |
| 18 | const submission = useRef(false); |
| 19 | const current = frame?.url === "about:blank" ? "" : frame?.url || ""; |
| 20 | const navigate = async event => { |
| 21 | event.preventDefault(); |
| 22 | if (submission.current) return; |
| 23 | const field = event.currentTarget.elements[0]; |
| 24 | const raw = field.value.trim(); |
| 25 | let url; |
| 26 | try { |
| 27 | if (!raw) throw new Error(); |
| 28 | url = new URL(raw.includes("://") ? raw : "https://" + raw); |
| 29 | if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.href.length > 16384) throw new Error(); |
| 30 | } catch { |
| 31 | setInvalid(true); onNotice("请输入有效的 HTTP 或 HTTPS 网址。"); |
| 32 | return; |
| 33 | } |
| 34 | submission.current = true; setSubmitting(true); onNotice(""); |
| 35 | try { |
| 36 | if (await goToAddress(url.href) && field.value.trim() === raw) { |
| 37 | field.blur(); |
| 38 | setAddress(null); |
| 39 | } |
| 40 | } catch (error) { |
| 41 | onNotice(error.message); |
| 42 | } finally { |
| 43 | submission.current = false; setSubmitting(false); |
| 44 | } |
| 45 | }; |
| 46 | return <form className="remote-address" onSubmit={navigate}> |
| 47 | <Globe2 size={16} aria-hidden="true" /> |
| 48 | <input aria-label="远程网页地址" aria-invalid={invalid} inputMode="url" enterKeyHint="go" autoCapitalize="none" |
| 49 | autoCorrect="off" autoComplete="off" spellCheck={false} placeholder="输入网址" disabled={!frame} |
| 50 | value={address ?? current} onFocus={event => event.target.select()} |
| 51 | onChange={event => {setAddress(event.target.value); setInvalid(false); onNotice("");}} |
| 52 | onKeyDown={event => {if (event.key === "Escape") {setAddress(null); setInvalid(false); onNotice(""); event.target.blur();}}} /> |
| 53 | <button type="submit" aria-label="前往网址" aria-busy={submitting} disabled={!frame || submitting}>{submitting ? <LoaderCircle className="spin" size={17} /> : <ArrowDownLeft size={17} />}</button> |
| 54 | </form>; |
| 55 | } |
| 56 | |
| 57 | function RemoteKeyboard({frame, busy, send, onClose}) { |
| 58 | const [draft, setDraft] = useState(""); |
| 59 | const insert = async event => { |
| 60 | event.preventDefault(); |
| 61 | if (!draft || !frame.focus || busy || new TextEncoder().encode(draft).length > 8192) return; |
| 62 | if (await send({type: "text", focus: frame.focus, text: draft}, frame)) setDraft(""); |
| 63 | }; |
| 64 | const tooLong = new TextEncoder().encode(draft).length > 8192; |
| 65 | return <form className="remote-keyboard" onSubmit={insert}> |
| 66 | <input autoFocus type={frame.password ? "password" : "text"} aria-label="待插入文字" placeholder={frame.password ? "输入密码" : "输入文字"} |
| 67 | autoComplete="off" autoCapitalize="none" spellCheck={false} autoCorrect="off" enterKeyHint="done" |
| 68 | maxLength={8192} value={draft} onChange={e => setDraft(e.target.value)} |
| 69 | onKeyDown={e => {if (e.key === "Enter" && (e.nativeEvent.isComposing || e.nativeEvent.keyCode === 229)) e.preventDefault();}} /> |
| 70 | <button type="submit" className="icon-button" aria-label="插入文字" title="插入文字" disabled={busy || !draft || tooLong}><Check size={19} /></button> |
| 71 | <Tool label="删除前一字符" icon={Delete} disabled={busy || !!draft} onClick={() => send({type: "key", key: "Backspace", focus: frame.focus}, frame)} /> |
| 72 | <Tool label="发送回车" icon={CornerDownLeft} disabled={busy || !!draft} onClick={() => send({type: "key", key: "Enter", focus: frame.focus}, frame)} /> |
| 73 | <Tool label="收起输入框" icon={X} onClick={onClose} /> |
| 74 | {tooLong && <p role="alert" className="remote-note">单次输入最多 8192 字节,请分段输入。</p>} |
| 75 | </form>; |
| 76 | } |
| 77 | |
| 78 | |
| 79 | |
| 80 | function LoginKeyboard({frame, busy, session, onClose}) { |
| 81 | const keys = useRef([]); |
| 82 | const sending = useRef(false); |
| 83 | const [sequence, wake] = useState(0); |
| 84 | const [notice, setNotice] = useState(""); |
| 85 | useEffect(() => () => { keys.current.length = 0; }, []); |
| 86 | useEffect(() => { |
| 87 | if (busy || sending.current || !keys.current.length || !session?.canSend(frame, frame.focus)) return; |
| 88 | const key = keys.current.shift(); |
| 89 | sending.current = true; |
| 90 | void session.send({type:"key", key, focus:frame.focus}, frame).then(ok => { |
| 91 | if (!ok) { |
| 92 | keys.current.length = 0; |
| 93 | setNotice("输入焦点或连接已变化,请检查远程输入框。"); |
| 94 | } |
| 95 | sending.current = false; |
| 96 | if (keys.current.length) wake(value => value + 1); |
| 97 | }); |
| 98 | }, [frame, busy, session, sequence]); |
| 99 | const press = key => { |
| 100 | if (keys.current.length >= 32) {setNotice("请稍候,前面的按键正在发送。"); return;} |
| 101 | keys.current.push(key); setNotice(""); wake(value => value + 1); |
| 102 | }; |
| 103 | return <div className="remote-keyboard"> |
| 104 | <input type="password" autoFocus aria-label="逐键登录输入" placeholder="逐键输入英文或符号" |
| 105 | autoComplete="off" autoCapitalize="none" spellCheck={false} autoCorrect="off" enterKeyHint="done" |
| 106 | onPaste={e => e.preventDefault()} onDrop={e => e.preventDefault()} |
| 107 | onInput={e => { |
| 108 | const value = e.currentTarget.value; |
| 109 | e.currentTarget.value = ""; |
| 110 | if (e.nativeEvent.inputType === "deleteContentBackward") {press("Backspace"); return;} |
| 111 | if (!e.nativeEvent.isComposing && /^[ -~]$/.test(value)) press(value); |
| 112 | else if (value) setNotice("登录键盘支持逐个输入英文、数字和符号。"); |
| 113 | }} |
| 114 | onKeyDown={e => { |
| 115 | if (["Backspace","Tab","Enter"].includes(e.key) && !e.nativeEvent.isComposing) { |
| 116 | e.preventDefault(); press(e.key); |
| 117 | } |
| 118 | }} /> |
| 119 | <Tool label="删除前一字符" icon={Delete} onClick={() => press("Backspace")} /> |
| 120 | <Tool label="发送回车" icon={CornerDownLeft} onClick={() => press("Enter")} /> |
| 121 | <Tool label="收起输入框" icon={X} onClick={onClose} /> |
| 122 | {notice && <p className="remote-note" role="alert">{notice}</p>} |
| 123 | </div>; |
| 124 | } |
| 125 | |
| 126 | function remoteHost(url) { |
| 127 | try { return new URL(url).hostname; } catch { return ""; } |
| 128 | } |
| 129 | |
| 130 | export function RemoteDisplay({visible, onBack, onReopen, id, tool, start, initialURL, controls, addressSlot}) { |
| 131 | const desktop = tool === "desktop"; |
| 132 | const name = desktop ? "Claude Desktop" : tool === "claude" ? "Claude.ai" : "远程浏览器"; |
| 133 | const [reading, setReading] = useState(false); |
| 134 | const [showAddress, setShowAddress] = useState(tool === "browser"); |
| 135 | const [addressNotice, setAddressNotice] = useState(""); |
| 136 | const [favorites, setFavorites] = useState(false); |
| 137 | const surface = useRef(null); |
| 138 | const stage = useRef(null); |
| 139 | const gesture = useRef(null); |
| 140 | const [state, setState] = useState({}); |
| 141 | const [keyboard, setKeyboard] = useState(""); |
| 142 | const preview = location.protocol === "cage-preview:"; |
| 143 | const frame = visible ? state.frame : null; |
| 144 | |
| 145 | |
| 146 | const login = desktop && frame?.window === "login"; |
| 147 | const focus = desktop && frame?.password && !login ? "" : frame?.focus || ""; |
| 148 | const typing = !!focus && keyboard === focus; |
| 149 | const hostname = tool === "claude" && frame ? remoteHost(frame.url) : ""; |
| 150 | useEffect(() => { |
| 151 | if (reading && stage.current) stage.current.scrollLeft = (stage.current.scrollWidth - stage.current.clientWidth) / 2; |
| 152 | }, [reading]); |
| 153 | useEffect(() => { |
| 154 | if (preview) return; |
| 155 | const session = connectDisplay(stage.current, next => { |
| 156 | if (!next.frame) {gesture.current = null; setKeyboard(""); setFavorites(false);} |
| 157 | setState(next); |
| 158 | }, id, start, tool, initialURL); |
| 159 | controls.current = session; |
| 160 | const visibility = () => { |
| 161 | gesture.current = null; setKeyboard(""); |
| 162 | session.visibility(!document.hidden); |
| 163 | }; |
| 164 | const pageHide = () => {gesture.current = null; setKeyboard(""); session.visibility(false);}; |
| 165 | document.addEventListener("visibilitychange", visibility); |
| 166 | const offline = () => {gesture.current = null; session.offline();}; |
| 167 | window.addEventListener("offline", offline); |
| 168 | window.addEventListener("pagehide", pageHide); |
| 169 | window.addEventListener("pageshow", visibility); |
| 170 | visibility(); |
| 171 | return () => { |
| 172 | document.removeEventListener("visibilitychange", visibility); |
| 173 | window.removeEventListener("offline", offline); |
| 174 | window.removeEventListener("pagehide", pageHide); |
| 175 | window.removeEventListener("pageshow", visibility); |
| 176 | session.close(); |
| 177 | controls.current = null; |
| 178 | }; |
| 179 | }, [id, start, tool, initialURL, preview, controls]); |
| 180 | |
| 181 | const send = (payload, expected) => controls.current?.send(payload, expected); |
| 182 | const point = event => framePoint(surface.current.getBoundingClientRect(), frame, event.clientX, event.clientY); |
| 183 | const down = event => { |
| 184 | if (favorites || !frame || (desktop && state.busy) || !event.isPrimary || event.button !== 0) return; |
| 185 | const location = point(event); |
| 186 | if (!location) return; |
| 187 | if (!desktop) controls.current.cancelScroll(); |
| 188 | event.currentTarget.setPointerCapture(event.pointerId); |
| 189 | gesture.current = {pointer: event.pointerId, location, frame, x:event.clientX, y:event.clientY, |
| 190 | lastX:0, lastY:0, dragged:false, left:stage.current.scrollLeft, top:stage.current.scrollTop}; |
| 191 | }; |
| 192 | const drag = (start, event) => { |
| 193 | const dx = start.x - event.clientX, dy = start.y - event.clientY; |
| 194 | if (!start.dragged && Math.hypot(dx, dy) < 6) return; |
| 195 | start.dragged = true; |
| 196 | if (reading) { |
| 197 | stage.current.scrollLeft = start.left + dx; |
| 198 | stage.current.scrollTop = start.top + dy; |
| 199 | } else if (!desktop) { |
| 200 | const {x, y, scale} = start.location; |
| 201 | const totalX = Math.round(dx / scale), totalY = Math.round(dy / scale); |
| 202 | controls.current.scroll(start.frame, {x, y, dx:totalX - start.lastX, dy:totalY - start.lastY}); |
| 203 | start.lastX = totalX; start.lastY = totalY; |
| 204 | } |
| 205 | }; |
| 206 | const move = event => { |
| 207 | const start = gesture.current; |
| 208 | if (start?.pointer === event.pointerId) drag(start, event); |
| 209 | }; |
| 210 | const up = event => { |
| 211 | const start = gesture.current; |
| 212 | if (start?.pointer !== event.pointerId) return; |
| 213 | gesture.current = null; |
| 214 | drag(start, event); |
| 215 | const {x, y, scale} = start.location; |
| 216 | if (!start.dragged) void send({type:"tap", x, y}, start.frame); |
| 217 | else if (desktop && !reading) { |
| 218 | const delta = value => Math.max(-3200, Math.min(3200, Math.round(value / scale))); |
| 219 | void send({type:"scroll", x, y, dx:delta(start.x - event.clientX), dy:delta(start.y - event.clientY)}, start.frame); |
| 220 | } |
| 221 | }; |
| 222 | const wheel = event => { |
| 223 | if (favorites || !frame || (desktop && state.busy)) return; |
| 224 | if (reading) { |
| 225 | stage.current.scrollBy(event.deltaX, event.deltaY); return; |
| 226 | } |
| 227 | const location = point(event); |
| 228 | if (!location) return; |
| 229 | const units = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? frame.height : 1; |
| 230 | const delta = value => Math.max(-3200, Math.min(3200, Math.round(value * units / location.scale))); |
| 231 | const input = {x:location.x, y:location.y, dx:delta(event.deltaX), dy:delta(event.deltaY)}; |
| 232 | if (desktop) void send({type:"scroll", ...input}, frame); |
| 233 | else controls.current.scroll(frame, input); |
| 234 | }; |
| 235 | return <section className="remote-browser" aria-label={name}> |
| 236 | {!desktop && addressSlot && frame && (showAddress |
| 237 | ? createPortal(<AddressBar frame={frame} goToAddress={async url => {const opened = await controls.current.navigate(url); if (opened) setFavorites(false); return opened;}} onNotice={setAddressNotice} />, addressSlot) |
| 238 | : hostname && hostname !== "claude.ai" && createPortal(<span className="remote-domain" title={hostname}><Globe2 size={14} />{hostname}</span>, addressSlot))} |
| 239 | {frame && state.homeNotice && <p className="remote-home-note" role="status">{state.homeNotice}</p>} |
| 240 | {frame && showAddress && addressNotice && <p className="remote-note" role="alert">{addressNotice}</p>} |
| 241 | <div ref={stage} className="remote-stage" onPointerDown={down} onPointerMove={move} onPointerUp={up} |
| 242 | onPointerCancel={() => {gesture.current = null; controls.current?.cancelScroll();}} onWheel={wheel} onContextMenu={e => {if (!favorites) e.preventDefault();}}> |
| 243 | {frame && favorites ? <PhoneFavorites frame={frame} navigate={url => controls.current.navigate(url)} onClose={() => setFavorites(false)}/> : |
| 244 | frame ? <div className={reading ? "display-surface reading" : "display-surface"} ref={surface}> |
| 245 | <img className="remote-screen" alt={desktop ? "远程 Desktop 画面" : "远程浏览器画面"} src={frame.image} draggable={false} /> |
| 246 | </div> : |
| 247 | <div className="remote-empty" role={state.error ? "alert" : "status"}> |
| 248 | {preview ? <><Globe2 aria-hidden="true" /><p>连接真实电脑后,即可使用{name}。</p></> : |
| 249 | state.error ? <><p>{state.error}</p> |
| 250 | {state.uncertain && <p className="note">输入结果待确认,请先查看最新画面。</p>} |
| 251 | <button className="action secondary" onClick={() => { |
| 252 | setKeyboard(""); setState({}); |
| 253 | if (state.reopen) onReopen(); |
| 254 | else controls.current.refresh(); |
| 255 | }}>{state.reopen ? "重新打开" : "重新读取画面"}</button></> : |
| 256 | <><LoaderCircle className="spin" aria-hidden="true" /><p>{state.waiting ? `正在启动远程${desktop ? " Claude Desktop" : "浏览器"}…` : "正在读取远程画面…"}</p></>} |
| 257 | </div>} |
| 258 | </div> |
| 259 | {typing ? (login |
| 260 | ? <LoginKeyboard key={focus} frame={frame} busy={state.busy} session={controls.current} onClose={() => setKeyboard("")} /> |
| 261 | : <RemoteKeyboard key={focus} frame={frame} busy={state.busy} send={send} onClose={() => setKeyboard("")} />) : |
| 262 | <nav className="remote-tools" aria-label={desktop ? "远程桌面操作" : "远程网页操作"}> |
| 263 | {desktop ? <> |
| 264 | <Tool label="断开远程桌面" icon={X} onClick={onBack} /> |
| 265 | <button type="button" className="action" disabled={!frame} aria-pressed={reading} onClick={() => setReading(!reading)}> |
| 266 | {reading ? <Maximize size={17} /> : <ZoomIn size={17} />}{reading ? "全幅" : "放大阅读"} |
| 267 | </button> |
| 268 | {!frame?.shared && frame?.login_supported !== false && <button type="button" className="action" disabled={!frame || state.busy} |
| 269 | onClick={() => send({type:login ? "desktop" : "login"}, frame)}> |
| 270 | {login ? <Monitor size={17} /> : <Globe2 size={17} />}{login ? "返回 Desktop" : "登录窗口"} |
| 271 | </button>} |
| 272 | </> : <> |
| 273 | <Tool label="关闭远程浏览器" icon={X} onClick={onBack} /> |
| 274 | <Tool label="上一页" icon={ArrowLeft} disabled={!frame || state.busy || favorites} onClick={() => send({type:"back"}, frame)} /> |
| 275 | <Tool label="下一页" icon={ArrowRight} disabled={!frame || state.busy || favorites} onClick={() => send({type:"forward"}, frame)} /> |
| 276 | {tool === "claude" && <Tool label="网页地址" aria-pressed={showAddress} icon={Globe2} disabled={!frame} onClick={() => {setAddressNotice(""); setShowAddress(!showAddress);}} />} |
| 277 | {tool === "browser" && <Tool label="收藏夹" icon={BookOpen} disabled={!frame} aria-expanded={favorites} |
| 278 | onClick={() => {gesture.current = null; controls.current.cancelScroll(); setFavorites(!favorites);}} />} |
| 279 | <Tool label="重新加载网页" icon={RotateCw} disabled={!frame || state.busy || favorites} onClick={() => send({type:"reload"}, frame)} /> |
| 280 | </>} |
| 281 | <Tool label="输入文字" icon={Keyboard} disabled={!focus || state.busy || favorites} |
| 282 | onClick={() => flushSync(() => setKeyboard(focus))} /> |
| 283 | </nav>} |
| 284 | {desktop && frame?.login_supported === false && <p className="remote-home-note" role="status">需要登录时,请在电脑的 Cage 中完成 Claude Desktop 登录,手机会继续使用同一登录状态。</p>} |
| 285 | </section>; |
| 286 | } |