Files
chandra/remote/web/index.html
T
nandiandClaude Opus 5.5 0356413bb2
CI / test (push) Failing after 1m7s
Remote: forward the physical keyboard and hide the phone OSK while typing
The web UI now sends key events without opening the KB bar, and releases
held keys on blur, hide or disconnect. The first remote keystroke (web or
VNC) turns the on-screen keyboard off; it comes back when the last typing
client disconnects, unless the user toggled it by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 14:27:17 -08:00

779 lines
28 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<meta name="theme-color" content="#0b1020">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="manifest" href="/manifest.json">
<link rel="icon" href="/icon.svg" type="image/svg+xml">
<title>Chandra Remote</title>
<style>
:root {
--bg: #0b1020;
--panel: rgba(15, 23, 42, 0.88);
--border: rgba(148, 163, 184, 0.24);
--accent: #38bdf8;
--text: #e2e8f0;
--muted: #94a3b8;
--ok: #22c55e;
--warn: #f59e0b;
--err: #ef4444;
}
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
html, body {
margin: 0; padding: 0; width: 100%; height: 100%;
overflow: hidden; background: var(--bg); color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
overscroll-behavior: none; user-select: none; -webkit-user-select: none;
}
#stage {
position: fixed; inset: 0;
display: flex; align-items: center; justify-content: center;
background: #050814; touch-action: none;
}
#screen {
display: block; max-width: 100%; max-height: 100%;
touch-action: none; image-rendering: auto;
box-shadow: 0 10px 40px rgba(0,0,0,0.65);
}
#cursor {
position: fixed; width: 16px; height: 16px; border-radius: 50%;
border: 2px solid #fff; background: rgba(56, 189, 248, 0.45);
box-shadow: 0 0 6px rgba(0,0,0,0.8);
pointer-events: none; transform: translate(-50%, -50%);
display: none; z-index: 20;
}
#pillWrap {
position: fixed; top: max(8px, env(safe-area-inset-top)); right: max(8px, env(safe-area-inset-right));
z-index: 30; display: flex; flex-direction: column; align-items: flex-end; gap: 6px;
}
#pillBar {
display: flex; align-items: center; gap: 6px; padding: 5px 8px;
background: var(--panel); border: 1px solid var(--border);
border-radius: 999px; backdrop-filter: blur(12px);
box-shadow: 0 6px 20px rgba(0,0,0,0.45);
}
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--warn); flex: none; }
.dot.ok { background: var(--ok); }
.dot.err { background: var(--err); }
button.btn {
appearance: none; border: 1px solid var(--border);
background: rgba(30, 41, 59, 0.85); color: var(--text);
border-radius: 999px; padding: 5px 10px; font-size: 12px; font-weight: 600;
cursor: pointer; line-height: 1.2;
}
button.btn.active { background: var(--accent); color: #06131f; border-color: var(--accent); }
button.btn:active { transform: scale(0.95); }
#drawer {
display: none; flex-direction: column; gap: 8px; width: min(296px, calc(100vw - 16px));
padding: 12px; border-radius: 16px;
background: var(--panel); border: 1px solid var(--border);
backdrop-filter: blur(14px); box-shadow: 0 12px 32px rgba(0,0,0,0.55);
}
#drawer.open { display: flex; }
.row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.row-label { font-size: 11px; color: var(--muted); min-width: 68px; }
input[type=range] { flex: 1; accent-color: var(--accent); }
#kbdBar {
position: fixed; left: 0; right: 0; bottom: 0; z-index: 35;
display: none; gap: 5px; padding: 6px 8px calc(6px + env(safe-area-inset-bottom));
background: rgba(15, 23, 42, 0.96); border-top: 1px solid var(--border);
overflow-x: auto; white-space: nowrap;
}
#kbdBar.open { display: flex; }
#kbdInput {
position: fixed; left: -9999px; top: 0; width: 1px; height: 1px;
opacity: 0; border: 0; padding: 0; font-size: 16px;
}
#loginMask {
position: fixed; inset: 0; z-index: 50; display: none;
align-items: center; justify-content: center; padding: 20px;
background: rgba(5, 8, 20, 0.92); backdrop-filter: blur(8px);
}
#loginMask.open { display: flex; }
.card {
width: min(340px, 100%); padding: 22px; border-radius: 18px;
background: #0f172a; border: 1px solid var(--border);
box-shadow: 0 20px 50px rgba(0,0,0,0.6);
}
.card h1 { margin: 0 0 6px; font-size: 19px; }
.card p { margin: 0 0 14px; color: var(--muted); font-size: 13px; }
.card input[type=password] {
width: 100%; padding: 11px 12px; border-radius: 10px;
border: 1px solid var(--border); background: #090e1c; color: var(--text);
font-size: 15px; margin-bottom: 12px; outline: none;
}
.card button {
width: 100%; padding: 11px; border: 0; border-radius: 10px;
background: var(--accent); color: #06131f; font-size: 14px; font-weight: 700; cursor: pointer;
}
#loginErr { color: #f87171; font-size: 12px; margin-top: 8px; min-height: 16px; }
</style>
</head>
<body>
<div id="stage">
<canvas id="screen" width="540" height="1170"></canvas>
</div>
<div id="cursor"></div>
<div id="pillWrap">
<div id="pillBar">
<span id="statusDot" class="dot" title="Connecting"></span>
<button id="kbBtn" class="btn">KB</button>
<button id="modeBtn" class="btn">Touch</button>
<button id="menuBtn" class="btn">⋮</button>
</div>
<div id="drawer">
<div class="row">
<button class="btn" data-ctl="rotate cw">Rotate 90°</button>
<button class="btn" data-ctl="rotate flip">Flip 180°</button>
<button id="screenBtn" class="btn" data-ctl="screen toggle">OLED</button>
</div>
<div class="row">
<span class="row-label">Bright <span id="briVal">--</span>%</span>
<input id="briSlider" type="range" min="5" max="100" value="60">
</div>
<div class="row">
<button id="oskBtn" class="btn" data-ctl="osk toggle">Phone OSK</button>
<button class="btn" data-ctl="shortcut launcher">Launcher</button>
<button class="btn" data-ctl="shortcut overview">Overview</button>
</div>
<div class="row">
<button id="clipBtn" class="btn">Send Clipboard</button>
<button id="fsBtn" class="btn">Fullscreen</button>
<button class="btn" data-ctl="refresh">Redraw</button>
</div>
<div class="row">
<span class="row-label">Quality</span>
<button class="btn qbtn" data-q="55" data-fps="24">Fast</button>
<button class="btn qbtn active" data-q="82" data-fps="30">Balanced</button>
<button class="btn qbtn" data-q="92" data-fps="30">Sharp</button>
</div>
<div id="infoLine" style="font-size:11px;color:var(--muted);">540x1170 · Connecting…</div>
</div>
</div>
<div id="kbdBar">
<button class="btn kspecial" data-code="1">Esc</button>
<button class="btn kspecial" data-code="15">Tab</button>
<button id="modCtrl" class="btn kmod" data-bit="4">Ctrl</button>
<button id="modAlt" class="btn kmod" data-bit="8">Alt</button>
<button class="btn kspecial" data-code="125">Super</button>
<button class="btn kspecial" data-code="105">←</button>
<button class="btn kspecial" data-code="103">↑</button>
<button class="btn kspecial" data-code="108">↓</button>
<button class="btn kspecial" data-code="106">→</button>
<button id="pasteBtn" class="btn">Paste</button>
<button id="kbHideBtn" class="btn">Done</button>
</div>
<input id="kbdInput" type="text" value=" " autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
<div id="loginMask">
<form id="loginForm" class="card">
<h1>Chandra Remote</h1>
<p>Enter your remote desktop password</p>
<input id="passInput" type="password" placeholder="Password" autocomplete="current-password">
<button type="submit">Connect</button>
<div id="loginErr"></div>
</form>
</div>
<script>
(() => {
const canvas = document.getElementById('screen');
const ctx = canvas.getContext('2d', { alpha: false });
const stage = document.getElementById('stage');
const dot = document.getElementById('statusDot');
const infoLine = document.getElementById('infoLine');
const drawer = document.getElementById('drawer');
const menuBtn = document.getElementById('menuBtn');
const modeBtn = document.getElementById('modeBtn');
const cursorEl = document.getElementById('cursor');
const kbBtn = document.getElementById('kbBtn');
const kbdBar = document.getElementById('kbdBar');
const kbdInput = document.getElementById('kbdInput');
const screenBtn = document.getElementById('screenBtn');
const oskBtn = document.getElementById('oskBtn');
const briSlider = document.getElementById('briSlider');
const briVal = document.getElementById('briVal');
const loginMask = document.getElementById('loginMask');
const loginForm = document.getElementById('loginForm');
const passInput = document.getElementById('passInput');
const loginErr = document.getElementById('loginErr');
let ws = null;
let token = localStorage.getItem('chandra_remote_token') || '';
let authRequired = false;
let reconnectTimer = null;
let trackpadMode = false;
let cursorX = 270, cursorY = 585;
let stickyMods = 0;
let kbOpen = false;
let keyHandled = false;
let lastPtrSent = 0;
function sendJson(obj) {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(obj));
}
}
function setStatusDot(cls, label) {
dot.className = 'dot ' + cls;
dot.title = label;
}
function layoutCursor() {
if (!trackpadMode) { cursorEl.style.display = 'none'; return; }
const r = canvas.getBoundingClientRect();
if (r.width <= 0 || r.height <= 0) return;
cursorEl.style.display = 'block';
cursorEl.style.left = (r.left + (cursorX / canvas.width) * r.width) + 'px';
cursorEl.style.top = (r.top + (cursorY / canvas.height) * r.height) + 'px';
}
function clientToFb(cx, cy) {
const r = canvas.getBoundingClientRect();
if (r.width <= 0 || r.height <= 0) return [0, 0];
const x = Math.round(((cx - r.left) / r.width) * canvas.width);
const y = Math.round(((cy - r.top) / r.height) * canvas.height);
return [
Math.max(0, Math.min(canvas.width - 1, x)),
Math.max(0, Math.min(canvas.height - 1, y))
];
}
let frameQueue = Promise.resolve();
function handleBinary(buf) {
if (buf.byteLength < 18) return;
const dv = new DataView(buf);
const type = dv.getUint8(0);
if (type !== 1) return;
const x = dv.getUint16(2);
const y = dv.getUint16(4);
const w = dv.getUint16(6);
const h = dv.getUint16(8);
const fbW = dv.getUint16(10);
const fbH = dv.getUint16(12);
const fid = dv.getUint32(14);
const blob = new Blob([buf.slice(18)], { type: 'image/jpeg' });
frameQueue = frameQueue.then(async () => {
try {
const bmp = await createImageBitmap(blob);
if (fbW > 0 && fbH > 0 && (canvas.width !== fbW || canvas.height !== fbH)) {
canvas.width = fbW;
canvas.height = fbH;
cursorX = Math.max(0, Math.min(fbW - 1, cursorX));
cursorY = Math.max(0, Math.min(fbH - 1, cursorY));
layoutCursor();
}
ctx.drawImage(bmp, x, y, w, h);
bmp.close();
} catch (e) {
console.error(e);
} finally {
sendJson({ t: 'ack', id: fid });
}
});
}
function handleText(str) {
try {
const m = JSON.parse(str);
if (m.t === 'status') {
infoLine.textContent = `${m.w}×${m.h} · ${m.rot}° · OLED ${m.screen} · Bright ${m.brightness}%`;
screenBtn.classList.toggle('active', m.screen === 'off');
screenBtn.textContent = m.screen === 'off' ? 'OLED Off' : 'OLED On';
oskBtn.classList.toggle('active', m.osk === 1);
if (m.brightness >= 5) {
briSlider.value = m.brightness;
briVal.textContent = String(m.brightness);
}
}
} catch (_) {}
}
function connectWs() {
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
if (ws) { try { ws.close(); } catch (_) {} }
setStatusDot('', 'Connecting');
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const q = token ? ('?token=' + encodeURIComponent(token)) : '';
const sock = new WebSocket(proto + '//' + location.host + '/ws' + q);
sock.binaryType = 'arraybuffer';
ws = sock;
sock.onopen = () => {
setStatusDot('ok', 'Connected');
loginMask.classList.remove('open');
};
sock.onmessage = (ev) => {
if (typeof ev.data === 'string') handleText(ev.data);
else handleBinary(ev.data);
};
sock.onclose = async () => {
if (ws !== sock) return;
releaseAllKeys();
setStatusDot('err', 'Disconnected');
await bootstrap();
};
}
async function bootstrap() {
try {
const r = await fetch('/api/info', { cache: 'no-store' });
const info = await r.json();
authRequired = !!info.auth_required;
if (!authRequired) {
loginMask.classList.remove('open');
connectWs();
return;
}
if (token) {
connectWs();
return;
}
loginMask.classList.add('open');
passInput.focus();
} catch (_) {
setStatusDot('err', 'Offline');
reconnectTimer = setTimeout(bootstrap, 2000);
}
}
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
loginErr.textContent = '';
try {
const r = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password: passInput.value })
});
const d = await r.json();
if (!r.ok || !d.ok) {
loginErr.textContent = d.error || 'Invalid password';
return;
}
token = d.token || '';
localStorage.setItem('chandra_remote_token', token);
passInput.value = '';
connectWs();
} catch (_) {
loginErr.textContent = 'Connection failed';
}
});
/* ---- Touch & Trackpad pointer handling ---- */
let pointers = new Map();
let gesture = null;
function clearLongTimer() {
if (gesture && gesture.longTimer) {
clearTimeout(gesture.longTimer);
gesture.longTimer = null;
}
}
stage.addEventListener('pointerdown', (e) => {
if (e.target.closest('#pillWrap') || e.target.closest('#kbdBar') || e.target.closest('#loginMask')) return;
if (document.activeElement && document.activeElement !== document.body && document.activeElement !== kbdInput) {
document.activeElement.blur();
}
e.preventDefault();
stage.setPointerCapture(e.pointerId);
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (pointers.size === 1) {
const [fx, fy] = clientToFb(e.clientX, e.clientY);
gesture = {
mode: 'one',
sx: e.clientX, sy: e.clientY,
lx: e.clientX, ly: e.clientY,
sfx: fx, sfy: fy,
fx, fy, moved: false, dragging: false, longFired: false,
longTimer: setTimeout(() => {
if (!gesture || gesture.mode !== 'one' || gesture.moved) return;
gesture.longFired = true;
if (navigator.vibrate) navigator.vibrate(25);
const rx = trackpadMode ? cursorX : gesture.sfx;
const ry = trackpadMode ? cursorY : gesture.sfy;
sendJson({ t: 'tap', x: rx, y: ry, b: 3 });
}, 450)
};
} else if (pointers.size === 2) {
clearLongTimer();
if (gesture && gesture.dragging) sendJson({ t: 'btn', b: 1, d: 0 });
const pts = [...pointers.values()];
const cx = (pts[0].x + pts[1].x) / 2;
const cy = (pts[0].y + pts[1].y) / 2;
const [fx, fy] = clientToFb(cx, cy);
gesture = { mode: 'two', sx: cx, sy: cy, lx: cx, ly: cy, fx, fy, moved: false };
}
});
stage.addEventListener('pointermove', (e) => {
if (!pointers.has(e.pointerId) || !gesture) return;
e.preventDefault();
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (gesture.mode === 'one' && pointers.size === 1) {
const dist = Math.hypot(e.clientX - gesture.sx, e.clientY - gesture.sy);
if (trackpadMode) {
const dx = (e.clientX - gesture.lx) * 1.45;
const dy = (e.clientY - gesture.ly) * 1.45;
gesture.lx = e.clientX;
gesture.ly = e.clientY;
if (dist > 8) { gesture.moved = true; clearLongTimer(); }
cursorX = Math.max(0, Math.min(canvas.width - 1, Math.round(cursorX + dx)));
cursorY = Math.max(0, Math.min(canvas.height - 1, Math.round(cursorY + dy)));
layoutCursor();
const now = performance.now();
if (now - lastPtrSent >= 16) {
lastPtrSent = now;
sendJson({ t: 'ptr', x: cursorX, y: cursorY });
}
return;
}
const [fx, fy] = clientToFb(e.clientX, e.clientY);
gesture.fx = fx; gesture.fy = fy;
if (!gesture.moved && dist > 14) {
gesture.moved = true;
clearLongTimer();
if (!gesture.longFired) {
gesture.dragging = true;
sendJson({ t: 'ptr', x: gesture.sfx, y: gesture.sfy });
sendJson({ t: 'btn', b: 1, d: 1 });
sendJson({ t: 'ptr', x: fx, y: fy });
}
} else if (gesture.dragging) {
const now = performance.now();
if (now - lastPtrSent >= 16) {
lastPtrSent = now;
sendJson({ t: 'ptr', x: fx, y: fy });
}
}
} else if (gesture.mode === 'two' && pointers.size >= 2) {
const pts = [...pointers.values()];
const cx = (pts[0].x + pts[1].x) / 2;
const cy = (pts[0].y + pts[1].y) / 2;
if (Math.hypot(cx - gesture.sx, cy - gesture.sy) > 8) gesture.moved = true;
const dx = Math.round(gesture.lx - cx);
const dy = Math.round(gesture.ly - cy);
gesture.lx = cx; gesture.ly = cy;
if (dx !== 0 || dy !== 0) {
const sx = trackpadMode ? cursorX : gesture.fx;
const sy = trackpadMode ? cursorY : gesture.fy;
sendJson({ t: 'scroll', x: sx, y: sy, dx, dy });
}
}
});
function onPointerFinish(e) {
if (!pointers.has(e.pointerId)) return;
pointers.delete(e.pointerId);
if (!gesture) return;
clearLongTimer();
if (gesture.mode === 'one' && pointers.size === 0) {
if (gesture.dragging) {
const [fx, fy] = clientToFb(e.clientX, e.clientY);
sendJson({ t: 'ptr', x: fx, y: fy });
sendJson({ t: 'btn', b: 1, d: 0 });
} else if (!gesture.moved && !gesture.longFired) {
const tx = trackpadMode ? cursorX : gesture.sfx;
const ty = trackpadMode ? cursorY : gesture.sfy;
sendJson({ t: 'tap', x: tx, y: ty, b: 1 });
}
gesture = null;
} else if (gesture.mode === 'two' && pointers.size === 0) {
if (!gesture.moved) {
const tx = trackpadMode ? cursorX : gesture.fx;
const ty = trackpadMode ? cursorY : gesture.fy;
sendJson({ t: 'tap', x: tx, y: ty, b: 3 });
}
gesture = null;
}
}
stage.addEventListener('pointerup', onPointerFinish);
stage.addEventListener('pointercancel', onPointerFinish);
stage.addEventListener('wheel', (e) => {
e.preventDefault();
const [fx, fy] = trackpadMode ? [cursorX, cursorY] : clientToFb(e.clientX, e.clientY);
sendJson({ t: 'scroll', x: fx, y: fy, dx: Math.round(e.deltaX), dy: Math.round(e.deltaY) });
}, { passive: false });
/* ---- Global desktop physical-keyboard forwarding ---- */
const pressedKeys = new Map();
function eventToKeysym(e) {
switch (e.key) {
case 'Backspace': return 0xFF08;
case 'Tab': return 0xFF09;
case 'Enter': return e.code === 'NumpadEnter' ? 0xFF8D : 0xFF0D;
case 'Escape': return 0xFF1B;
case 'Insert': return 0xFF63;
case 'Delete': return 0xFFFF;
case 'Home': return 0xFF50;
case 'End': return 0xFF57;
case 'PageUp': return 0xFF55;
case 'PageDown': return 0xFF56;
case 'ArrowLeft': return 0xFF51;
case 'ArrowUp': return 0xFF52;
case 'ArrowRight': return 0xFF53;
case 'ArrowDown': return 0xFF54;
case 'Shift': return e.code === 'ShiftRight' ? 0xFFE2 : 0xFFE1;
case 'Control': return e.code === 'ControlRight' ? 0xFFE4 : 0xFFE3;
case 'Alt': return e.code === 'AltRight' ? 0xFFEA : 0xFFE9;
case 'AltGraph': return 0xFE03;
case 'Meta': return e.code === 'MetaRight' ? 0xFFEC : 0xFFEB;
case 'CapsLock': return 0xFFE5;
case 'NumLock': return 0xFF7F;
case 'ContextMenu': return 0xFF67;
case 'PrintScreen': return 0xFF61;
case 'Pause': return 0xFF13;
case 'AudioVolumeDown': return 0x1008FF11;
case 'AudioVolumeMute': return 0x1008FF12;
case 'AudioVolumeUp': return 0x1008FF13;
}
const fm = /^F([1-9]|1[0-2])$/.exec(e.key);
if (fm) return 0xFFBE + (Number(fm[1]) - 1);
if (e.key.length === 1) {
const cp = e.key.codePointAt(0);
if (cp >= 0x20 && cp <= 0x7E) return cp;
}
if ((e.ctrlKey || e.altKey || e.metaKey) && e.code) {
const km = /^Key([A-Z])$/.exec(e.code);
if (km) {
const ch = e.shiftKey ? km[1] : km[1].toLowerCase();
return ch.charCodeAt(0);
}
const dm = /^Digit([0-9])$/.exec(e.code);
if (dm) return dm[1].charCodeAt(0);
}
return null;
}
function releaseAllKeys() {
if (pressedKeys.size > 0) {
for (const sym of [...pressedKeys.values()].reverse()) {
sendJson({ t: 'key', k: sym, d: 0 });
}
pressedKeys.clear();
}
sendJson({ t: 'release' });
}
window.addEventListener('keydown', (e) => {
if (!ws || ws.readyState !== WebSocket.OPEN) return;
if (loginMask.classList.contains('open')) return;
if (e.target === passInput || e.target === briSlider || e.target === kbdInput) return;
if (e.isComposing || e.key === 'Unidentified' || e.key === 'Process' || e.key === 'Dead') return;
const sym = eventToKeysym(e);
if (sym !== null) {
e.preventDefault();
const id = e.code || e.key;
if (e.repeat && pressedKeys.has(id)) return;
pressedKeys.set(id, sym);
sendJson({ t: 'key', k: sym, d: 1 });
} else if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
e.preventDefault();
sendJson({ t: 'text', s: e.key });
}
});
window.addEventListener('keyup', (e) => {
if (!ws || ws.readyState !== WebSocket.OPEN) return;
if (loginMask.classList.contains('open')) return;
if (e.target === passInput || e.target === briSlider || e.target === kbdInput) return;
const id = e.code || e.key;
if (pressedKeys.has(id)) {
e.preventDefault();
const sym = pressedKeys.get(id);
pressedKeys.delete(id);
sendJson({ t: 'key', k: sym, d: 0 });
}
});
window.addEventListener('blur', releaseAllKeys);
document.addEventListener('visibilitychange', () => {
if (document.hidden) releaseAllKeys();
});
/* ---- Android Gboard sentinel-space keyboard bridge ---- */
function setKbOpen(open) {
kbOpen = open;
kbBtn.classList.toggle('active', open);
kbdBar.classList.toggle('open', open);
if (open) {
kbdInput.value = ' ';
kbdInput.focus();
kbdInput.setSelectionRange(1, 1);
} else {
kbdInput.blur();
stickyMods = 0;
document.querySelectorAll('.kmod').forEach(b => b.classList.remove('active'));
}
}
kbBtn.addEventListener('click', () => setKbOpen(!kbOpen));
document.getElementById('kbHideBtn').addEventListener('click', () => setKbOpen(false));
document.querySelectorAll('.kmod').forEach(btn => {
btn.addEventListener('click', () => {
const bit = Number(btn.dataset.bit);
stickyMods ^= bit;
btn.classList.toggle('active', (stickyMods & bit) !== 0);
kbdInput.focus();
});
});
document.querySelectorAll('.kspecial').forEach(btn => {
btn.addEventListener('click', () => {
const code = Number(btn.dataset.code);
sendJson({ t: 'ktap', c: code, m: stickyMods });
stickyMods = 0;
document.querySelectorAll('.kmod').forEach(b => b.classList.remove('active'));
kbdInput.focus();
});
});
function sendTextWithMods(txt) {
if (!txt) return;
if (stickyMods && txt.length === 1 && txt.charCodeAt(0) >= 0x20 && txt.charCodeAt(0) <= 0x7E) {
const m = stickyMods;
if (m & 4) sendJson({ t: 'key', k: 0xFFE3, d: 1 });
if (m & 8) sendJson({ t: 'key', k: 0xFFE9, d: 1 });
sendJson({ t: 'key', k: txt.charCodeAt(0), d: 1 });
sendJson({ t: 'key', k: txt.charCodeAt(0), d: 0 });
if (m & 8) sendJson({ t: 'key', k: 0xFFE9, d: 0 });
if (m & 4) sendJson({ t: 'key', k: 0xFFE3, d: 0 });
stickyMods = 0;
document.querySelectorAll('.kmod').forEach(b => b.classList.remove('active'));
return;
}
sendJson({ t: 'text', s: txt });
}
kbdInput.addEventListener('keydown', (e) => {
keyHandled = false;
const map = {
Enter: 28, Backspace: 14, Tab: 15, Escape: 1, Delete: 111,
ArrowLeft: 105, ArrowUp: 103, ArrowRight: 106, ArrowDown: 108,
Home: 102, End: 107, PageUp: 104, PageDown: 109
};
if (e.key in map) {
e.preventDefault();
keyHandled = true;
let m = stickyMods;
if (e.shiftKey) m |= 1;
if (e.ctrlKey) m |= 4;
if (e.altKey) m |= 8;
sendJson({ t: 'ktap', c: map[e.key], m });
stickyMods = 0;
document.querySelectorAll('.kmod').forEach(b => b.classList.remove('active'));
kbdInput.value = ' ';
return;
}
if ((e.ctrlKey || e.altKey || e.metaKey) && e.key.length === 1) {
e.preventDefault();
keyHandled = true;
if (e.ctrlKey) sendJson({ t: 'key', k: 0xFFE3, d: 1 });
if (e.altKey) sendJson({ t: 'key', k: 0xFFE9, d: 1 });
if (e.metaKey) sendJson({ t: 'key', k: 0xFFEB, d: 1 });
sendJson({ t: 'key', k: e.key.charCodeAt(0), d: 1 });
sendJson({ t: 'key', k: e.key.charCodeAt(0), d: 0 });
if (e.metaKey) sendJson({ t: 'key', k: 0xFFEB, d: 0 });
if (e.altKey) sendJson({ t: 'key', k: 0xFFE9, d: 0 });
if (e.ctrlKey) sendJson({ t: 'key', k: 0xFFE3, d: 0 });
}
});
kbdInput.addEventListener('input', (e) => {
if (e.isComposing) return;
if (keyHandled) {
keyHandled = false;
kbdInput.value = ' ';
return;
}
const v = kbdInput.value;
if (e.inputType === 'deleteContentBackward' || v.length === 0) {
sendJson({ t: 'ktap', c: 14, m: 0 });
} else {
const added = v.startsWith(' ') ? v.slice(1) : v;
if (added) sendTextWithMods(added);
}
kbdInput.value = ' ';
kbdInput.setSelectionRange(1, 1);
});
kbdInput.addEventListener('compositionend', (e) => {
if (e.data) sendJson({ t: 'text', s: e.data });
kbdInput.value = ' ';
kbdInput.setSelectionRange(1, 1);
});
/* ---- UI controls ---- */
document.getElementById('pillWrap').addEventListener('click', (e) => {
const btn = e.target.closest('button');
if (btn && btn !== kbBtn) btn.blur();
});
menuBtn.addEventListener('click', () => drawer.classList.toggle('open'));
modeBtn.addEventListener('click', () => {
trackpadMode = !trackpadMode;
modeBtn.textContent = trackpadMode ? 'Pad' : 'Touch';
modeBtn.classList.toggle('active', trackpadMode);
layoutCursor();
});
document.querySelectorAll('[data-ctl]').forEach(btn => {
btn.addEventListener('click', () => {
sendJson({ t: 'ctl', cmd: btn.dataset.ctl });
});
});
briSlider.addEventListener('input', () => {
briVal.textContent = briSlider.value;
});
briSlider.addEventListener('change', () => {
sendJson({ t: 'ctl', cmd: 'brightness ' + briSlider.value });
});
document.querySelectorAll('.qbtn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.qbtn').forEach(x => x.classList.remove('active'));
btn.classList.add('active');
sendJson({ t: 'cfg', q: Number(btn.dataset.q), fps: Number(btn.dataset.fps) });
});
});
document.getElementById('clipBtn').addEventListener('click', async () => {
let txt = '';
try { txt = await navigator.clipboard.readText(); } catch (_) {}
if (!txt) txt = prompt('Text to copy to phone clipboard:') || '';
if (txt) sendJson({ t: 'clip', s: txt });
});
document.getElementById('pasteBtn').addEventListener('click', async () => {
let txt = '';
try { txt = await navigator.clipboard.readText(); } catch (_) {}
if (!txt) txt = prompt('Text to type on phone:') || '';
if (txt) sendJson({ t: 'text', s: txt });
kbdInput.focus();
});
document.getElementById('fsBtn').addEventListener('click', () => {
if (!document.fullscreenElement) document.documentElement.requestFullscreen?.();
else document.exitFullscreen?.();
});
window.addEventListener('resize', layoutCursor);
bootstrap();
})();
</script>
</body>
</html>