//! Pair a device with the active server. use opencode_api::generated::{PairingCode, ServerInfo}; use opencode_ui::dialog::{DialogCx, layout}; use opencode_ui::keymap::Slash; use crate::prelude::*; pub fn install(tui: &Rc) { let command = TuiCommand::new("server.pair", bind!(tui, |tui, _, _| show(&tui))) .bind(Bind::Off) .title("Pair device") .group("System") .palette() .slash(Slash::new("pair").aliases(["web"])); tui.keymap.install("pair", [KeymapLayer::global(vec![command]), KeymapLayer::default().bindings(["server.pair"])]); } pub fn show(tui: &Tui) { // Read once: a build in a new theme draws the same code again. let loaded: Loaded = Rc::default(); let shown: Shown = Rc::default(); let (result, target) = (loaded.clone(), shown.clone()); tui.dialogs.replace( move |cx| { cx.dialogs.set_centered(true); let body = View::new(&cx.app); fill(cx, &body, result.borrow().as_ref()); *target.borrow_mut() = Some((Rc::downgrade(cx), body.clone())); layout(cx, &header(cx, HeaderProps::new("Pair")), &body, None) }, None, DialogOptions::new(DialogSize::Large), ); load(tui, loaded, shown); } /// The pairing once read, or why it could not be. type Loaded = Rc>>>; type Shown = Rc, View)>>>; pub struct Pairing { pub links: Vec, pub localhost: Option, pub minutes: i64, pub loopback: bool, } pub fn pairing(server: &ServerInfo, pairing: &PairingCode) -> Pairing { let link = |base: &url::Url| { opencode_api::js::join_url(base, &format!("/auth/connect/{}", pairing.code)) .map(String::from) .unwrap_or_default() }; let urls: Vec = server.urls.iter().filter_map(|url| opencode_api::js::parse_url(url).ok()).collect(); let localhost = server .urls .first() .and_then(|url| opencode_api::js::parse_url(url).ok()) .and_then(|mut local| opencode_api::js::set_host(&mut local, Some("localhost")).ok().map(|()| local)) .map(|local| link(&local)); Pairing { links: urls.iter().map(link).collect(), localhost, minutes: (pairing.expires_in as f64 / 60.0).round() as i64, loopback: urls.iter().any(|url| matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))), } } fn load(tui: &Tui, loaded: Loaded, shown: Shown) { let client = tui.data.client().clone(); tui.app.spawn( async move { let (server, code) = futures_util::future::join(client.server_info(), client.server_pair()).await; Ok::<_, opencode_api::error::Error>(pairing(&server?, &code?)) }, move |_, result| { *loaded.borrow_mut() = Some(result.map_err(|error| error.to_string())); let Some((cx, body)) = shown.borrow().clone() else { return }; let Some(cx) = cx.upgrade() else { return }; fill(&cx, &body, loaded.borrow().as_ref()); cx.app.request_redraw(); }, ); } fn fill(cx: &DialogCx, body: &View, loaded: Option<&Result>) { let theme = &cx.theme; body.clear(); match loaded { None => { body.add(&Text::new(&cx.app, "Loading server information…").fg(theme.text.muted)); } Some(Ok(value)) => { body.add(&content(cx, value)); } Some(Err(error)) => { body.add( &Text::new(&cx.app, "Could not load server information").fg(theme.text.feedback.error.base).bold(), ); body.add(&Text::new(&cx.app, error.clone()).fg(theme.text.muted)); body.add(&Text::new(&cx.app, "Close and reopen Pair to try again.").fg(theme.text.muted)); } } } fn content(cx: &DialogCx, value: &Pairing) -> View { let app = &cx.app; let theme = &cx.theme; let (width, height) = app.size(); let horizontal = width >= 96; let link = |url: &str| { let text = Text::new(app, vec![url.to_owned().fg(theme.text.base).link(url)]); crate::features::links::open_on_click(app, &text, url.to_owned()); text }; let side = View::new(app).shrink(0.0).gap(1); if horizontal { side.width(29); } else { side.width(Length::Percent(100.0)); } side.add( &Text::new(app, format!("Open a link to connect. Links work once and expire in {} minutes.", value.minutes)) .fg(theme.text.muted) .wrap(WrapMode::Word), ); if let Some(url) = &value.localhost { side.add(&View::new(app).child(&Text::new(app, "This device").fg(theme.text.muted)).child(&link(url))); } let links = View::new(app).child(&Text::new(app, "Links").fg(theme.text.muted)); for url in &value.links { links.add(&link(url)); } side.add(&links); if value.loopback { side.add( &Text::new(app, "Run `opencode service set hostname 0.0.0.0` to access the service remotely.") .fg(theme.text.muted) .wrap(WrapMode::Word), ); } let code = View::new(app).shrink(0.0); if horizontal { code.grow(1.0).align_items(Align::End); } else { code.width(Length::Percent(100.0)).align_items(Align::Center); } if let Some(url) = value.links.first() { code.add(&Text::new(app, opencode_ui::qr::render_unicode_compact(url, 1)).fg(theme.text.base)); } let row = View::new(app).gap(2).child(&side).child(&code); if horizontal { row.row().align_items(Align::Start); } else { row.align_items(Align::Center); } if height >= 36 { return row; } let scroll = ScrollBox::new(app).scrollbars(false).height((8.max(i32::from(height) - i32::from(height) / 4 - 6)) as u32); scroll.add(&row); cx.keep_scroll(&scroll); View::new(app).child(&scroll) }