123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717 | // invoke() is typed against the Commands table in types.d.ts, so command
// names, argument objects, and result types are all checked against main.rs.
function invoke<C extends keyof Commands>(
cmd: C,
...args: Commands[C]["args"] extends null ? [] : [Commands[C]["args"]]
): Promise<Commands[C]["result"]> {
return window.__TAURI__.core.invoke(cmd, args[0] ?? undefined) as Promise<Commands[C]["result"]>;
}
const appWindow = window.__TAURI__.window.getCurrentWindow();
// ── State ─────────────────────────────────────────────────────────────────────
let networks: Network[] = [];
let selectedSsid: string | null = null;
let wifiEnabled = true;
let scanning = false;
let busy = false; // a connect/disconnect is in flight
let statusMsg = "";
let statusError = false;
let statusTimer: number | undefined = undefined;
let info: InfoState | null = null; // set while the info view is open
let infoNet: Network | null = null; // the Network the info view was opened for
let connectingTo: string | null = null; // SSID when the password view is open
let hiddenJoin = false; // password view is in join-hidden-network mode
let pwReturnNet: Network | null = null; // reopen this network's info page when leaving the password view
let forgetArmed = false;
let forgetTimer: number | undefined = undefined;
let wgStatus: WireguardStatus | null = null; // null until first check
let wgBusy = false; // a WireGuard up/down is in flight
// Static element ids → their element types; $() catches typos and gives each
// lookup the right type. "info-pw" is created dynamically by the info view.
interface Elements {
"close-btn": HTMLButtonElement;
"scan-btn": HTMLButtonElement;
"wifi-toggle": HTMLInputElement;
"conn-status": HTMLSpanElement;
"status-text": HTMLSpanElement;
"network-list": HTMLDivElement;
"vpn-bar": HTMLDivElement;
"vpn-row": HTMLDivElement;
"vpn-sub": HTMLDivElement;
"vpn-spinner": HTMLDivElement;
"vpn-toggle": HTMLInputElement;
"view-list": HTMLDivElement;
"view-password": HTMLDivElement;
"view-info": HTMLDivElement;
"pw-title": HTMLHeadingElement;
"pw-sub": HTMLParagraphElement;
"pw-ssid-row": HTMLDivElement;
"pw-ssid": HTMLInputElement;
"pw-input": HTMLInputElement;
"pw-eye": HTMLButtonElement;
"pw-status": HTMLParagraphElement;
"pw-cancel": HTMLButtonElement;
"pw-connect": HTMLButtonElement;
"pw-spinner": HTMLDivElement;
"info-ssid": HTMLHeadingElement;
"info-conn": HTMLParagraphElement;
"info-status": HTMLParagraphElement;
"info-action": HTMLButtonElement;
"info-body": HTMLDivElement;
"info-noprofile": HTMLParagraphElement;
"info-forget": HTMLButtonElement;
"info-save": HTMLButtonElement;
"info-back": HTMLButtonElement;
"info-pw": HTMLInputElement;
}
const $ = <I extends keyof Elements>(id: I): Elements[I] =>
document.getElementById(id) as Elements[I];
// ── Rendering ─────────────────────────────────────────────────────────────────
type ViewName = "list" | "password" | "info";
function currentView(): ViewName {
for (const name of ["list", "password", "info"] as const) {
if (!$(`view-${name}`).classList.contains("hidden")) return name;
}
return "list";
}
function showView(name: ViewName): void {
$("view-list").classList.toggle("hidden", name !== "list");
$("view-password").classList.toggle("hidden", name !== "password");
$("view-info").classList.toggle("hidden", name !== "info");
}
function setStatus(msg: string, { error = false, sticky = false } = {}): void {
statusMsg = msg;
statusError = error;
clearTimeout(statusTimer);
if (msg && !sticky) {
statusTimer = setTimeout(() => { statusMsg = ""; statusError = false; renderChrome(); }, 6000);
}
renderChrome();
}
function barsFor(signal: number): string {
const active = signal >= 75 ? 4 : signal >= 50 ? 3 : signal >= 25 ? 2 : 1;
let html = '<span class="bars">';
for (let i = 0; i < 4; i++) html += `<i class="${i < active ? "on" : ""}"></i>`;
return html + "</span>";
}
const CHECK_SVG = `<span class="icon check"><svg width="14" height="12" viewBox="0 0 14 12">
<path class="stroke" d="M2 6.5 L5.5 10 L12 2" fill="none" stroke-width="2"/></svg></span>`;
const LOCK_SVG = `<span class="icon lock"><svg width="12" height="14" viewBox="0 0 12 14">
<path class="stroke" d="M3.5 6 V4 a2.5 2.5 0 0 1 5 0 V6" fill="none" stroke-width="1.4"/>
<rect class="fill" x="2" y="6" width="8" height="6" rx="1"/></svg></span>`;
const WIFI_EMPTY_SVG = `<svg width="38" height="31" viewBox="0 0 24 20" fill="none"
stroke="currentColor" stroke-width="1.8" stroke-linecap="round">
<path d="M2.4 6.8 a14 14 0 0 1 19.2 0"/>
<path d="M5.6 10.6 a9.3 9.3 0 0 1 12.8 0"/>
<path d="M8.8 14.3 a4.8 4.8 0 0 1 6.4 0"/>
<circle cx="12" cy="17.4" r="1.5" fill="currentColor" stroke="none"/></svg>`;
const CHEV_SVG = `<span class="icon chev"><svg width="7" height="12" viewBox="0 0 7 12">
<path class="stroke" d="M1 1 L6 6 L1 11" fill="none" stroke-width="1.6"
stroke-linecap="round" stroke-linejoin="round"/></svg></span>`;
function renderList(): void {
const list = $("network-list");
if (!wifiEnabled) {
list.innerHTML = `<div class="empty">${WIFI_EMPTY_SVG}<div>Wi-Fi is turned off</div></div>`;
return;
}
if (networks.length === 0) {
list.innerHTML = `<div class="empty">${WIFI_EMPTY_SVG}<div>${
scanning ? "Scanning for networks…" : "No networks found"}</div></div>`;
return;
}
list.innerHTML = "";
const card = el("div", "info-card list-card");
for (const net of networks) {
const row = el("div", "row");
if (net.inUse) row.classList.add("in-use");
if (net.ssid === selectedSsid) row.classList.add("selected");
const sub = net.inUse ? "Connected"
: net.known ? "Saved"
: net.secured ? "Secured" : "Open";
const icon = net.inUse ? CHECK_SVG : net.secured ? LOCK_SVG : "";
row.title = `Signal: ${net.signal}%`;
row.innerHTML = `${barsFor(net.signal)}
<span class="labels"><div class="ssid"></div><div class="sub">${sub}</div></span>${icon}${CHEV_SVG}`;
row.querySelector(".ssid")!.textContent = net.ssid;
row.addEventListener("click", () => {
if (busy) return;
selectedSsid = net.ssid;
openInfoView(net);
});
card.appendChild(row);
}
list.appendChild(card);
const otherCard = el("div", "info-card other-card");
const other = el("div", "row other");
other.innerHTML = `<span class="labels"><div class="ssid">Other network…</div>
<div class="sub">Join a hidden network by name</div></span>`;
other.addEventListener("click", () => { if (!busy) openPasswordView(null, true); });
otherCard.appendChild(other);
list.appendChild(otherCard);
}
function renderChrome(): void {
// Header
const conn = networks.find((n) => n.inUse);
const cs = $("conn-status");
if (!wifiEnabled) {
cs.textContent = "Wi-Fi Off";
cs.classList.remove("connected");
} else if (conn) {
cs.textContent = `Connected: ${conn.ssid}`;
cs.classList.add("connected");
} else {
cs.textContent = "Not connected";
cs.classList.remove("connected");
}
$("wifi-toggle").checked = wifiEnabled;
const scanBtn = $("scan-btn");
scanBtn.classList.toggle("hidden", !wifiEnabled);
scanBtn.classList.toggle("spinning", scanning);
scanBtn.disabled = scanning || busy;
scanBtn.title = scanning ? "Scanning…" : "Scan for networks";
// Footer
const st = $("status-text");
st.textContent = statusMsg || (scanning ? "Scanning for networks…" : "");
st.classList.toggle("error", statusError && !!statusMsg);
}
function renderVpn(): void {
const bar = $("vpn-bar");
const wg = wgStatus;
const show = wg !== null && wg.installed;
bar.classList.toggle("hidden", !show);
if (!wg || !show) return;
$("vpn-row").classList.toggle("in-use", wg.up);
$("vpn-sub").textContent = wgBusy ? ($("vpn-toggle").checked ? "Starting…" : "Stopping…")
: wg.up ? `Active: ${wg.interface}`
: "Inactive";
if (!wgBusy) $("vpn-toggle").checked = wg.up;
$("vpn-toggle").disabled = wgBusy;
$("vpn-spinner").classList.toggle("hidden", !wgBusy);
}
function render(): void {
renderList();
renderChrome();
renderVpn();
}
// ── Actions ───────────────────────────────────────────────────────────────────
async function refreshQuick(): Promise<void> {
try {
networks = await invoke("quick_scan");
} catch (_) { /* keep the old list */ }
render();
}
async function doScan(): Promise<void> {
scanning = true;
setStatus("");
render();
try {
networks = await invoke("scan");
} catch (e) {
setStatus(String(e), { error: true, sticky: true });
}
scanning = false;
render();
}
async function refreshWireguard(): Promise<void> {
try {
wgStatus = await invoke("wireguard_status");
} catch (_) { /* keep the old status */ }
renderVpn();
}
// ── Password view ─────────────────────────────────────────────────────────────
function openPasswordView(ssid: string | null, hidden: boolean): void {
connectingTo = ssid;
hiddenJoin = hidden;
pwReturnNet = hidden ? null : infoNet;
$("pw-title").textContent = hidden ? "Join hidden network" : ssid;
$("pw-sub").textContent = hidden
? "Leave the password blank for open networks"
: "Enter the password to connect";
$("pw-ssid-row").classList.toggle("hidden", !hidden);
$("pw-ssid").value = "";
$("pw-input").value = "";
$("pw-input").type = "password";
$("pw-eye").innerHTML = EYE_SVG;
$("pw-eye").title = "Show password";
$("pw-status").textContent = "";
$("pw-status").classList.remove("error");
setPwBusy(false);
showView("password");
(hidden ? $("pw-ssid") : $("pw-input")).focus();
}
function cancelPasswordView(): void {
if (busy) return;
connectingTo = null;
const ret = pwReturnNet;
pwReturnNet = null;
if (ret) openInfoView(ret);
else showView("list");
}
function setPwBusy(b: boolean, msg = ""): void {
busy = b;
$("pw-spinner").classList.toggle("hidden", !b);
$("pw-cancel").disabled = b;
$("pw-ssid").disabled = b;
$("pw-input").disabled = b;
$("pw-eye").disabled = b;
$("pw-status").textContent = msg;
$("pw-status").classList.remove("error");
updatePwButton();
}
function updatePwButton(): void {
const ssid = hiddenJoin ? $("pw-ssid").value.trim() : connectingTo;
const pw = $("pw-input").value;
// WPA passphrases are 8–63 chars; hidden networks may be open, so allow blank there.
const pwOk = hiddenJoin ? (pw.length === 0 || pw.length >= 8) : pw.length >= 8;
$("pw-connect").disabled = busy || !ssid || !pwOk;
}
async function submitPassword(): Promise<void> {
if (busy || $("pw-connect").disabled) return;
const ssid = hiddenJoin ? $("pw-ssid").value.trim() : connectingTo;
if (!ssid) return;
const pw = $("pw-input").value;
setPwBusy(true, `Connecting to ${ssid}…`);
try {
if (hiddenJoin) {
await invoke("connect_hidden", { ssid, password: pw || null });
} else {
await invoke("connect", { ssid, password: pw });
}
busy = false;
connectingTo = null;
setStatus(`Connected to ${ssid}`);
await refreshQuick();
// Return to the info page we came from, now showing the connected state.
const ret = pwReturnNet;
pwReturnNet = null;
const net = ret && networks.find((n) => n.ssid === ssid);
if (net) await openInfoView(net);
else showView("list");
} catch (e) {
// A failed attempt leaves behind a broken profile with the bad password;
// clean it up so the network doesn't show as "Saved". (Safe: this view is
// only reachable for networks with no pre-existing profile.)
if (!hiddenJoin) invoke("forget", { ssid }).catch(() => {});
setPwBusy(false);
$("pw-status").textContent = String(e);
$("pw-status").classList.add("error");
$("pw-input").focus();
$("pw-input").select();
}
}
// ── Info view ─────────────────────────────────────────────────────────────────
async function copyText(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (_) {
const ta = document.createElement("textarea");
ta.value = text;
document.body.append(ta);
ta.select();
const ok = document.execCommand("copy");
ta.remove();
return ok;
}
}
const COPY_SVG = `<svg width="13" height="13" viewBox="0 0 13 13">
<rect x="4.2" y="4.2" width="7" height="7" rx="1.4" fill="none" stroke="currentColor" stroke-width="1.3"/>
<path d="M8.8 1.8 H3.2 A1.4 1.4 0 0 0 1.8 3.2 V8.8" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>`;
const TICK_SVG = `<svg width="13" height="13" viewBox="0 0 13 13">
<path d="M2.5 7 L5.3 9.8 L10.5 3.5" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
const EYE_SVG = `<svg width="14" height="13" viewBox="0 0 14 13">
<path d="M1.5 6.5 C3.5 3.2 10.5 3.2 12.5 6.5 C10.5 9.8 3.5 9.8 1.5 6.5 Z" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/>
<circle cx="7" cy="6.5" r="1.7" fill="currentColor"/></svg>`;
const EYE_OFF_SVG = `<svg width="14" height="13" viewBox="0 0 14 13">
<path d="M1.5 6.5 C3.5 3.2 10.5 3.2 12.5 6.5 C10.5 9.8 3.5 9.8 1.5 6.5 Z" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/>
<circle cx="7" cy="6.5" r="1.7" fill="currentColor"/>
<path d="M3 11.5 L11 1.5" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>`;
function el<K extends keyof HTMLElementTagNameMap>(
tag: K, cls?: string, text?: string,
): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text != null) e.textContent = text;
return e;
}
function iconBtn(svg: string, title: string): HTMLButtonElement {
const b = el("button", "icon-btn");
b.title = title;
b.innerHTML = svg;
return b;
}
function copyIconBtn(getValue: () => string, title = "Copy"): HTMLButtonElement {
const b = iconBtn(COPY_SVG, title);
b.addEventListener("click", async () => {
if (await copyText(getValue())) {
b.innerHTML = TICK_SVG;
b.classList.add("done");
setTimeout(() => { b.innerHTML = COPY_SVG; b.classList.remove("done"); }, 1200);
}
});
return b;
}
function infoCard(parent: HTMLElement, heading: string | null): HTMLDivElement {
if (heading) parent.append(el("div", "info-sec", heading));
const card = el("div", "info-card");
parent.append(card);
return card;
}
function addRow(card: HTMLElement, label: string, valueNode: HTMLElement,
copyGetter?: () => string): HTMLDivElement {
const row = el("div", "irow");
row.append(el("span", "ilabel", label), valueNode);
if (copyGetter) row.append(copyIconBtn(copyGetter));
card.append(row);
return row;
}
const val = (text: string) => el("span", "ival", text);
async function openInfoView(net: Network): Promise<void> {
const fetched = await invoke("fetch_info", { ssid: net.ssid, inUse: net.inUse });
const inf: InfoState = { ...fetched, secured: net.secured };
info = inf;
infoNet = net;
$("info-ssid").textContent = inf.ssid;
const ic = $("info-conn");
ic.textContent = net.inUse ? "Currently connected" : "Not connected";
ic.classList.toggle("connected", net.inUse);
$("info-status").textContent = "";
$("info-status").classList.remove("error");
const act = $("info-action");
act.textContent = net.inUse ? "Disconnect" : "Connect";
act.className = net.inUse ? "btn disconnect" : "btn connect";
act.disabled = false;
const body = $("info-body");
body.innerHTML = "";
// ── Saved profile card (password first — it's the main event) ──
if (inf.hasProfile) {
const ssid = inf.ssid;
const prof = infoCard(body, null);
if (inf.secured) {
const savedPw = inf.password;
const input = document.createElement("input");
input.type = "password";
input.id = "info-pw";
input.className = "pw";
input.value = savedPw;
input.placeholder = "(none saved)";
input.autocomplete = "off";
input.title = "Click to edit";
input.addEventListener("input", () => {
$("info-save").classList.toggle("hidden", input.value === savedPw);
});
const eye = iconBtn(EYE_SVG, "Show password");
eye.addEventListener("click", () => {
const show = input.type === "password";
input.type = show ? "text" : "password";
eye.innerHTML = show ? EYE_OFF_SVG : EYE_SVG;
eye.title = show ? "Hide password" : "Show password";
});
const row = el("div", "irow");
row.append(el("span", "ilabel", "Password"), input, eye,
copyIconBtn(() => input.value, "Copy password"));
prof.append(row);
}
const acRow = el("div", "irow");
acRow.append(el("span", "ilabel", "Auto-connect"), el("span", "ival"));
const toggle = el("label", "toggle small");
const cb = document.createElement("input");
cb.type = "checkbox";
cb.checked = inf.autoconnect !== false;
toggle.append(cb, el("span", "knob"));
acRow.append(toggle);
prof.append(acRow);
cb.addEventListener("change", async () => {
try {
await invoke("set_autoconnect", { ssid, enabled: cb.checked });
$("info-status").textContent = "";
} catch (err) {
cb.checked = !cb.checked;
$("info-status").textContent = String(err);
}
});
}
// ── Details card ──
const details = infoCard(body, inf.hasProfile ? "Details" : null);
const sig = el("span", "ival sigval");
sig.innerHTML = `${barsFor(net.signal)}<span>${net.signal}%</span>`;
addRow(details, "Signal", sig);
if (inf.security) addRow(details, "Security", val(inf.security));
const freq = [inf.band, inf.channel && `Ch. ${inf.channel}`]
.filter(Boolean).join(" · ");
if (freq) addRow(details, "Frequency", val(freq));
if (inf.rate) addRow(details, "Max rate", val(inf.rate));
if (inf.bssid) addRow(details, "BSSID", val(inf.bssid), () => inf.bssid);
// ── Network card (populated only while connected) ──
if (inf.ip4Address || inf.ip4Gateway || inf.ip4Dns) {
const netc = infoCard(body, "Network");
if (inf.ip4Address) addRow(netc, "IP Address", val(inf.ip4Address), () => inf.ip4Address);
if (inf.ip4Gateway) addRow(netc, "Gateway", val(inf.ip4Gateway), () => inf.ip4Gateway);
if (inf.ip4Dns) addRow(netc, "DNS", val(inf.ip4Dns), () => inf.ip4Dns);
}
forgetArmed = false;
clearTimeout(forgetTimer);
$("info-forget").textContent = "Forget";
$("info-noprofile").classList.toggle("hidden", inf.hasProfile);
$("info-forget").classList.toggle("hidden", !inf.hasProfile);
$("info-save").classList.add("hidden"); // appears once the password is edited
showView("info");
}
function closeInfoView(): void {
info = null;
infoNet = null;
clearTimeout(forgetTimer);
forgetArmed = false;
showView("list");
}
function setInfoBusy(b: boolean, msg = ""): void {
busy = b;
for (const id of ["info-action", "info-back", "info-forget", "info-save"] as const) {
$(id).disabled = b;
}
const s = $("info-status");
s.classList.remove("error");
s.textContent = msg;
}
// Run connect/disconnect from the info view, then re-render it with fresh state.
async function infoRun(ssid: string, progress: string, fn: () => Promise<unknown>): Promise<void> {
setInfoBusy(true, progress);
let err = "";
try { await fn(); } catch (e) { err = String(e); }
busy = false;
await refreshQuick();
if (currentView() !== "info" || !info || info.ssid !== ssid) return;
const net = networks.find((n) => n.ssid === ssid);
if (net) {
await openInfoView(net);
if (err) {
$("info-status").textContent = err;
$("info-status").classList.add("error");
}
} else {
closeInfoView();
if (err) setStatus(err, { error: true, sticky: true });
}
}
// ── Event wiring ──────────────────────────────────────────────────────────────
$("close-btn").addEventListener("click", () => appWindow.close());
$("scan-btn").addEventListener("click", doScan);
$("wifi-toggle").addEventListener("change", async () => {
wifiEnabled = $("wifi-toggle").checked;
if (wifiEnabled) {
setStatus("Turning Wi-Fi on…", { sticky: true });
render();
try {
await invoke("set_wifi_enabled", { enabled: true });
setStatus("");
await doScan();
} catch (err) {
setStatus(String(err), { error: true, sticky: true });
render();
}
} else {
networks = [];
selectedSsid = null;
setStatus("");
render();
invoke("set_wifi_enabled", { enabled: false }).catch(() => {});
}
});
$("vpn-toggle").addEventListener("change", async () => {
if (!wgStatus || wgBusy) return;
const up = $("vpn-toggle").checked;
const iface = wgStatus.interface;
wgBusy = true;
renderVpn();
try {
await invoke("set_wireguard", { up, interface: iface });
setStatus(up ? `WireGuard ${iface} is up` : `WireGuard ${iface} is down`);
} catch (err) {
setStatus(String(err), { error: true, sticky: true });
}
wgBusy = false;
await refreshWireguard(); // re-syncs the toggle with reality (reverts on failure)
});
$("pw-cancel").addEventListener("click", cancelPasswordView);
$("pw-connect").addEventListener("click", submitPassword);
$("pw-input").addEventListener("input", () => {
// Editing clears stale errors; a too-short passphrase explains the disabled button.
const s = $("pw-status");
s.classList.remove("error");
const len = $("pw-input").value.length;
s.textContent = len > 0 && len < 8 ? "Wi-Fi passwords are at least 8 characters" : "";
updatePwButton();
});
$("pw-ssid").addEventListener("input", updatePwButton);
$("pw-input").addEventListener("keydown", (e) => {
if (e.key === "Enter") submitPassword();
});
$("pw-ssid").addEventListener("keydown", (e) => {
if (e.key === "Enter") $("pw-input").focus();
});
$("pw-eye").innerHTML = EYE_SVG;
$("pw-eye").addEventListener("click", () => {
const input = $("pw-input");
const show = input.type === "password";
input.type = show ? "text" : "password";
$("pw-eye").innerHTML = show ? EYE_OFF_SVG : EYE_SVG;
$("pw-eye").title = show ? "Hide password" : "Show password";
});
$("info-back").addEventListener("click", closeInfoView);
$("info-action").addEventListener("click", () => {
if (busy || !info) return;
const ssid = info.ssid;
const hasProfile = info.hasProfile;
const net = networks.find((n) => n.ssid === ssid) || infoNet;
if (!net) return;
if (net.inUse) {
infoRun(ssid, `Disconnecting…`, () => invoke("disconnect", { ssid }));
} else if (hasProfile) {
infoRun(ssid, `Connecting…`, () => invoke("connect_saved", { ssid }));
} else if (net.secured) {
openPasswordView(ssid, false);
} else {
infoRun(ssid, `Connecting…`, () => invoke("connect", { ssid, password: null }));
}
});
$("info-forget").addEventListener("click", async () => {
if (!info) return;
// Two-step confirm: first click arms, second click within 3s executes.
if (!forgetArmed) {
forgetArmed = true;
$("info-forget").textContent = "Really forget?";
forgetTimer = setTimeout(() => {
forgetArmed = false;
$("info-forget").textContent = "Forget";
}, 3000);
return;
}
clearTimeout(forgetTimer);
const ssid = info.ssid;
closeInfoView();
try {
await invoke("forget", { ssid });
setStatus(`Forgot ${ssid}`);
if (selectedSsid === ssid) selectedSsid = null;
} catch (e) {
setStatus(String(e), { error: true, sticky: true });
}
render();
refreshQuick();
});
$("info-save").addEventListener("click", async () => {
if (!info) return;
const ssid = info.ssid;
const password = $("info-pw").value;
closeInfoView();
try {
await invoke("save_password", { ssid, password });
setStatus(`Password updated for ${ssid}`);
} catch (e) {
setStatus(String(e), { error: true, sticky: true });
}
render();
});
// ── Keyboard navigation ───────────────────────────────────────────────────────
document.addEventListener("keydown", (e) => {
const view = currentView();
if (view === "list") {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
if (!networks.length) return;
e.preventDefault();
const idx = networks.findIndex((n) => n.ssid === selectedSsid);
let next;
if (idx === -1) next = e.key === "ArrowDown" ? 0 : networks.length - 1;
else next = Math.max(0, Math.min(networks.length - 1, idx + (e.key === "ArrowDown" ? 1 : -1)));
selectedSsid = networks[next].ssid;
renderList();
renderChrome();
document.querySelector("#network-list .row.selected")?.scrollIntoView({ block: "nearest" });
} else if (e.key === "Enter" || e.key === "ArrowRight") {
const sel = networks.find((n) => n.ssid === selectedSsid);
if (sel && !busy) openInfoView(sel);
} else if (e.key === "Escape") {
appWindow.close();
}
} else if (view === "password") {
if (e.key === "Escape") cancelPasswordView();
} else if (view === "info") {
if (e.key === "Escape" || e.key === "ArrowLeft") closeInfoView();
}
});
// ── Init ──────────────────────────────────────────────────────────────────────
(async () => {
wifiEnabled = await invoke("get_wifi_enabled");
render();
refreshWireguard();
if (wifiEnabled) {
await refreshQuick();
doScan();
}
})();
// Keep the list and signal strengths fresh while idle (no active rescan —
// this just re-reads NetworkManager's scan cache, which it refreshes itself).
setInterval(() => {
if (currentView() !== "list" || busy) return;
if (wifiEnabled && !scanning) refreshQuick();
if (!wgBusy) refreshWireguard();
}, 15000);
|