67 lines
2.6 KiB
JavaScript
67 lines
2.6 KiB
JavaScript
export function screen({ call, notice, onBusy }) {
|
|
const $ = (id) => document.getElementById(id);
|
|
const state = { target: "", available: false, blocked: false, working: false, active: false, ready: false, phase: "", disposed: false };
|
|
let timer, error, reportedBusy = false;
|
|
function reportBusy() {
|
|
const busy = state.working || (state.active && !state.ready);
|
|
if (busy === reportedBusy) return;
|
|
reportedBusy = busy;
|
|
onBusy(busy);
|
|
}
|
|
function render() {
|
|
$("screen-start").disabled = state.working || state.blocked || !state.available;
|
|
$("screen-start").textContent = state.working ? "正在连接…" : state.active ? "显示投屏窗口" : "打开投屏窗口";
|
|
$("screen-stop").disabled = state.working || !state.active;
|
|
$("screen-status").textContent = state.active ? state.ready ? "正在独立窗口中投屏 · 默认鼠标控制" : state.phase || "正在建立视频连接…" : "让手机,来到桌面。";
|
|
}
|
|
async function status() {
|
|
if (state.disposed) return;
|
|
try {
|
|
const result = await call("screenWindowStatus", {});
|
|
if (state.disposed) return;
|
|
if (!state.working) { state.active = result.active; state.ready = !!result.ready; state.phase = result.phase || ""; }
|
|
if (result.error && result.error.message !== error) {
|
|
error = result.error.message;
|
|
notice(error);
|
|
}
|
|
reportBusy();
|
|
render();
|
|
} catch { /* Closing the plugin also closes the native session. */ }
|
|
if (!state.disposed) timer = setTimeout(status, 1000);
|
|
}
|
|
async function action(method, args) {
|
|
if (state.working) return;
|
|
state.working = true;
|
|
reportBusy();
|
|
render();
|
|
try {
|
|
const result = await call(method, args);
|
|
state.active = result.active;
|
|
state.ready = !!result.ready;
|
|
state.phase = result.phase || "";
|
|
error = undefined;
|
|
} catch (error) { notice(error.message || String(error)); }
|
|
finally {
|
|
state.working = false;
|
|
reportBusy();
|
|
if (!state.disposed) render();
|
|
}
|
|
}
|
|
$("screen-start").onclick = () => {
|
|
if (!state.available || state.blocked) return;
|
|
const name = $("hdc-target").selectedOptions[0]?.textContent || "Harmony";
|
|
return action("screenWindowOpen", { target: state.target, name });
|
|
};
|
|
$("screen-stop").onclick = () => action("screenWindowStop", {});
|
|
window.addEventListener("pagehide", () => { state.disposed = true; clearTimeout(timer); });
|
|
void status();
|
|
render();
|
|
return {
|
|
configure(target, available, blocked) {
|
|
Object.assign(state, { target, available, blocked });
|
|
render();
|
|
},
|
|
hide() { /* The independent window owns its session until closed. */ },
|
|
};
|
|
}
|