const PROTOCOL = 1;
function mods(e) {
return { c: !!e.ctrlKey, s: !!e.shiftKey, a: !!e.altKey, m: !!e.metaKey };
}
export function connect({ url, token, canvas, role = "control", onEvent } = {}) {
if (!canvas) throw new Error("connect: canvas is required");
const listeners = new Map();
const emit = (type, detail) => {
(listeners.get(type) || []).forEach((fn) => fn(detail));
if (onEvent) onEvent(type, detail);
};
const g = canvas.getContext("2d");
const stats = { frames: 0, bytes: 0, lastSeq: 0 };
let ws = null;
let closed = false;
let myRole = role;
let backoff = 250;
let drawChain = Promise.resolve();
const ime = document.createElement("textarea");
ime.setAttribute("autocapitalize", "off");
ime.setAttribute("autocomplete", "off");
ime.setAttribute("spellcheck", "false");
Object.assign(ime.style, { position: "fixed", left: "0px", top: "0px", width: "1px", height: "1px", opacity: "0", border: "0", padding: "0", resize: "none", pointerEvents: "none" });
document.body.appendChild(ime);
let composing = false;
const send = (msg) => {
if (ws && ws.readyState === 1) ws.send(JSON.stringify(msg));
};
const control = () => myRole === "control";
const cssSize = () => {
const r = canvas.parentElement ? canvas.parentElement.getBoundingClientRect() : canvas.getBoundingClientRect();
return { w: Math.max(64, Math.floor(r.width)), h: Math.max(64, Math.floor(r.height)), dpr: window.devicePixelRatio || 1 };
};
let ppp = window.devicePixelRatio || 1;
const pos = (e) => {
const r = canvas.getBoundingClientRect();
const k = canvas.width ? canvas.width / ppp / Math.max(1, r.width) : 1;
const kh = canvas.height ? canvas.height / ppp / Math.max(1, r.height) : 1;
return { x: (e.clientX - r.left) * k, y: (e.clientY - r.top) * kh };
};
const sendResize = () => {
const s = cssSize();
ppp = s.dpr;
send({ t: "resize", ...s });
};
async function onFrame(buf) {
const dv = new DataView(buf);
if (dv.getUint8(0) !== 1) return;
const keyframe = (dv.getUint8(1) & 1) === 1;
const n = dv.getUint16(2, true);
const seq = dv.getUint32(4, true);
const w = dv.getUint16(8, true);
const h = dv.getUint16(10, true);
let off = 12;
const tiles = [];
for (let i = 0; i < n; i++) {
const x = dv.getUint16(off, true), y = dv.getUint16(off + 2, true);
const tw = dv.getUint16(off + 4, true), th = dv.getUint16(off + 6, true);
const codec = dv.getUint8(off + 8);
const len = dv.getUint32(off + 10, true);
off += 14;
const blob = new Blob([new Uint8Array(buf, off, len)], { type: codec === 2 ? "image/jpeg" : "image/png" });
off += len;
tiles.push({ x, y, tw, th, bitmap: createImageBitmap(blob) });
}
stats.bytes += buf.byteLength;
const decoded = Promise.all(tiles.map((t) => t.bitmap));
drawChain = drawChain.then(async () => {
const bitmaps = await decoded;
if (canvas.width !== w || canvas.height !== h) {
canvas.width = w;
canvas.height = h;
}
tiles.forEach((t, i) => {
g.drawImage(bitmaps[i], t.x, t.y);
bitmaps[i].close && bitmaps[i].close();
});
stats.frames++;
stats.lastSeq = seq;
send({ t: "ack", seq });
emit("frame", { seq, keyframe, tiles: n, w, h });
}).catch((e) => console.warn("brep-stream: frame", e));
}
function onControl(msg) {
switch (msg.t) {
case "welcome":
backoff = 250;
myRole = msg.role;
if (msg.role !== "control" && msg.ppp) ppp = msg.ppp;
emit("ready", msg);
emit("role", { role: myRole });
if (control()) sendResize();
break;
case "role":
myRole = msg.role;
emit("role", { role: myRole });
if (control()) sendResize();
break;
case "cursor":
canvas.style.cursor = msg.css;
break;
case "clipboard":
if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(msg.s).catch(() => {});
emit("clipboard", { text: msg.s });
break;
case "open_url":
window.open(msg.url, "_blank", "noopener");
break;
case "ime_area": {
const r = canvas.getBoundingClientRect();
if (msg.x !== undefined) Object.assign(ime.style, { left: `${r.left + msg.x}px`, top: `${r.top + msg.y + msg.h}px` });
break;
}
case "upload": {
const head = uploads.shift();
if (head) postUpload(head, msg.id);
break;
}
case "error":
if (msg.code === "upload" && uploads.length) {
uploads.shift().reject(new Error(msg.msg));
pumpUploads();
break;
}
emit("error", msg);
if (msg.code === "auth" || msg.code === "version") closed = true;
break;
default:
emit(msg.t, msg);
}
}
function open() {
const { w, h, dpr } = cssSize();
ws = new WebSocket(url);
ws.binaryType = "arraybuffer";
ws.onopen = () => ws.send(JSON.stringify({ t: "hello", v: PROTOCOL, token, role, w, h, dpr }));
ws.onmessage = (ev) => {
if (typeof ev.data === "string") onControl(JSON.parse(ev.data));
else onFrame(ev.data);
};
ws.onclose = () => {
for (const item of uploads.splice(0)) item.reject(new Error("the connection closed"));
announcing = null;
emit("close", {});
if (!closed) {
setTimeout(open, backoff);
backoff = Math.min(backoff * 2, 5000);
}
};
}
const httpBase = url.replace(/^ws/, "http").replace(/\/ws(\?.*)?$/, "");
const auth = { Authorization: `Bearer ${token}` };
const uploads = [];
let announcing = null;
function pumpUploads() {
announcing = uploads[0] || null;
if (announcing) send({ t: "drop", name: announcing.file.name, size: announcing.file.size });
}
function postUpload(item, id) {
fetch(`${httpBase}/uploads/${id}`, { method: "POST", headers: auth, body: item.file })
.then(async (r) => { if (!r.ok) throw new Error(await r.text()); return r.json(); })
.then(item.resolve, item.reject)
.finally(pumpUploads);
}
function upload(file) {
return new Promise((resolve, reject) => {
if (!control()) return reject(new Error("only the controlling page uploads"));
uploads.push({ file, resolve, reject });
if (uploads.length === 1 && !announcing) pumpUploads();
});
}
async function download(id, name) {
const r = await fetch(`${httpBase}/downloads/${id}`, { headers: auth });
if (!r.ok) throw new Error(await r.text());
const blob = await r.blob();
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = name || "download";
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(a.href), 10000);
return blob.size;
}
canvas.addEventListener("dragover", (e) => { if (control()) e.preventDefault(); });
canvas.addEventListener("drop", (e) => {
if (!control()) return;
e.preventDefault();
for (const file of e.dataTransfer ? e.dataTransfer.files : []) {
upload(file).catch((err) => emit("error", { code: "upload", name: file.name, msg: String(err.message || err) }));
}
});
const buttons = { 0: 0, 2: 1, 1: 2, 3: 3, 4: 4 };
canvas.style.touchAction = "none";
canvas.addEventListener("contextmenu", (e) => e.preventDefault());
canvas.addEventListener("pointermove", (e) => {
if (!control()) return;
if (e.pointerType === "touch") return touch(e, "move");
const events = e.getCoalescedEvents ? e.getCoalescedEvents() : [e];
const last = events[events.length - 1] || e;
send({ t: "pm", ...pos(last) });
});
canvas.addEventListener("pointerdown", (e) => {
if (!control()) return;
ime.focus({ preventScroll: true });
canvas.setPointerCapture(e.pointerId);
if (e.pointerType === "touch") return touch(e, "start");
e.preventDefault();
send({ t: "pb", ...pos(e), b: buttons[e.button] ?? 0, down: true, mods: mods(e) });
});
canvas.addEventListener("pointerup", (e) => {
if (!control()) return;
if (e.pointerType === "touch") return touch(e, "end");
send({ t: "pb", ...pos(e), b: buttons[e.button] ?? 0, down: false, mods: mods(e) });
});
canvas.addEventListener("pointercancel", (e) => {
if (control() && e.pointerType === "touch") touch(e, "cancel");
});
canvas.addEventListener("pointerleave", (e) => {
if (control() && e.pointerType !== "touch") send({ t: "leave" });
});
function touch(e, phase) {
send({ t: "touch", id: e.pointerId, phase, ...pos(e), force: e.pressure || null });
}
canvas.addEventListener("wheel", (e) => {
if (!control()) return;
e.preventDefault();
send({ t: "wheel", dx: e.deltaX, dy: e.deltaY, mode: e.deltaMode, mods: mods(e) });
}, { passive: false });
ime.addEventListener("keydown", (e) => {
if (!control() || composing || e.isComposing || e.keyCode === 229) return;
send({ t: "key", key: e.key, code: e.code, down: true, repeat: e.repeat, mods: mods(e) });
const printable = e.key.length === 1 || (e.key.length === 2 && e.key.codePointAt(0) > 0xffff);
if (printable && !e.ctrlKey && !e.metaKey) send({ t: "text", s: e.key });
const paste = (e.ctrlKey || e.metaKey) && (e.key === "v" || e.key === "V");
if (!paste) e.preventDefault();
});
ime.addEventListener("keyup", (e) => {
if (!control() || composing) return;
send({ t: "key", key: e.key, code: e.code, down: false, mods: mods(e) });
});
ime.addEventListener("compositionstart", () => { composing = true; send({ t: "ime", phase: "start" }); });
ime.addEventListener("compositionupdate", (e) => send({ t: "ime", phase: "update", s: e.data || "" }));
ime.addEventListener("compositionend", (e) => {
composing = false;
send({ t: "ime", phase: "commit", s: e.data || "" });
ime.value = "";
});
ime.addEventListener("paste", (e) => {
e.preventDefault();
const s = e.clipboardData ? e.clipboardData.getData("text/plain") : "";
if (control() && s) send({ t: "paste", s });
});
ime.addEventListener("input", () => { if (!composing) ime.value = ""; });
ime.addEventListener("focus", () => send({ t: "focus", on: true }));
ime.addEventListener("blur", () => send({ t: "focus", on: false }));
let resizeTimer = 0;
const ro = new ResizeObserver(() => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => { if (control()) sendResize(); }, 50);
});
ro.observe(canvas.parentElement || canvas);
open();
return {
on(type, fn) { if (!listeners.has(type)) listeners.set(type, []); listeners.get(type).push(fn); return this; },
takeControl() { send({ t: "take_control" }); },
quality(jpeg) { send({ t: "quality", jpeg }); },
upload,
download,
focus() { ime.focus({ preventScroll: true }); },
get role() { return myRole; },
stats,
close() { closed = true; ro.disconnect(); ime.remove(); if (ws) ws.close(); },
};
}