Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

thinkterm-web: publish the chrome as data through a wasm Client

RoversX3aa138de4c8f
diff --git a/thinkterm-web/Cargo.toml b/thinkterm-web/Cargo.toml
index e75eef90..1911c9d4 100644
--- a/thinkterm-web/Cargo.toml
+++ b/thinkterm-web/Cargo.toml
@@ -21,9 +21,13 @@ codec.workspace = true
euclid.workspace = true
futures.workspace = true
log.workspace = true
+nucleo-matcher.workspace = true
+serde.workspace = true
+serde_json.workspace = true
termwiz = { workspace = true, features = ["use_serde"] }
thinkterm-font-core.workspace = true
thinkterm-font-web.workspace = true
+thinkterm-i18n.workspace = true
thinkterm-proto.workspace = true
thinkterm-render = { workspace = true, features = ["wgpu"] }
thinkterm-session.workspace = true
@@ -45,10 +49,10 @@ web-sys = { workspace = true, features = [
"BinaryType", "CanvasRenderingContext2d", "Clipboard", "ClipboardEvent",
"CloseEvent", "CompositionEvent",
"console", "CssStyleDeclaration", "DataTransfer", "Document", "DomRect",
- "DomRectReadOnly", "Element", "Event", "EventTarget", "FocusEvent", "History",
- "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "HtmlTextAreaElement", "ImageData",
+ "DomRectReadOnly", "Element", "Event", "EventTarget", "FocusEvent",
+ "HtmlCanvasElement", "HtmlElement", "HtmlTextAreaElement", "ImageData",
"InputEvent",
"KeyboardEvent", "Location", "MessageEvent", "MouseEvent", "Navigator",
- "Performance", "PointerEvent", "ResizeObserver", "ResizeObserverEntry", "Storage",
+ "Performance", "PointerEvent", "ResizeObserver", "ResizeObserverEntry",
"WebSocket", "WheelEvent", "Window",
] }
diff --git a/thinkterm-web/src/agents.rs b/thinkterm-web/src/agents.rs
new file mode 100644
index 00000000..8904d1df
--- /dev/null
+++ b/thinkterm-web/src/agents.rs
@@ -0,0 +1,171 @@
+//! The right-hand Agents panel as data: one row per pane an agent runs
+//! in, as the desktop's panel lists them (`agent_panel.rs`), and the
+//! one-line summary above them.
+
+use crate::tree::TreeModel;
+use serde::Serialize;
+use thinkterm_i18n::{tr, tr_args, FluentArgs};
+use thinkterm_proto::{AgentState, PaneId, WindowId};
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct AgentRow {
+ pub pane: PaneId,
+ pub window: Option<WindowId>,
+ /// The pane is in the window this page shows.
+ pub here: bool,
+ pub agent_id: String,
+ pub name: String,
+ pub title: String,
+ pub state: &'static str,
+ pub state_label: String,
+ /// "Project · Thread", or the workspace when no thread claims it.
+ pub place: String,
+ /// The brand or fallback icon the page draws.
+ pub icon: &'static str,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct AgentsView {
+ pub rows: Vec<AgentRow>,
+ pub summary: String,
+}
+
+/// The curated names the desktop uses; anything else is its id, title-cased.
+pub fn display_name(agent_id: &str) -> String {
+ match agent_id {
+ "claude" => "Claude Code".into(),
+ "codex" => "Codex".into(),
+ "copilot" => "Copilot CLI".into(),
+ "cursor" => "Cursor Agent".into(),
+ "pi" => "Pi".into(),
+ "opencode" => "OpenCode".into(),
+ "kimi" => "Kimi Code".into(),
+ "omp" => "OMP".into(),
+ "soul" => "Soul".into(),
+ other => {
+ let mut chars = other.chars();
+ match chars.next() {
+ Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
+ None => "Agent".into(),
+ }
+ }
+ }
+}
+
+/// Brand icons the page has (simple-icons: claude, githubcopilot); `bot` otherwise.
+pub fn icon(agent_id: &str) -> &'static str {
+ match agent_id {
+ "claude" => "brand-claude",
+ "copilot" => "brand-copilot",
+ _ => "bot",
+ }
+}
+
+fn state_key(state: AgentState) -> (&'static str, &'static str) {
+ match state {
+ AgentState::Working => ("working", "right-agents-state-working"),
+ AgentState::Blocked => ("blocked", "right-agents-state-blocked"),
+ AgentState::Idle => ("idle", "right-agents-state-idle"),
+ AgentState::Unknown => ("unknown", "right-agents-state-unknown"),
+ }
+}
+
+/// The rows, sorted as the desktop sorts them: by place, agent, pane --
+/// never floating the current window, so a switch does not reorder them.
+pub fn rows(tree: &TreeModel, current_window: WindowId, title_of: impl Fn(PaneId) -> Option<String>) -> Vec<AgentRow> {
+ let mut rows: Vec<AgentRow> = tree
+ .agent_entries()
+ .map(|(pane, agent_id, state, title)| {
+ let (place, window) = tree.place_of_pane(pane);
+ let (state_name, state_label) = state_key(state);
+ AgentRow {
+ pane,
+ window,
+ here: window == Some(current_window),
+ name: display_name(agent_id),
+ title: title_of(pane).unwrap_or_else(|| crate::navbar::display_title(title).0),
+ state: state_name,
+ state_label: tr(state_label),
+ place,
+ icon: icon(agent_id),
+ agent_id: agent_id.to_string(),
+ }
+ })
+ .collect();
+ rows.sort_by(|a, b| {
+ a.place
+ .to_lowercase()
+ .cmp(&b.place.to_lowercase())
+ .then(a.agent_id.cmp(&b.agent_id))
+ .then(a.pane.cmp(&b.pane))
+ });
+ rows
+}
+
+/// "2 working · 1 needs input", else idle and unknown counted apart,
+/// else "No agents detected".
+pub fn summary(rows: &[AgentRow]) -> String {
+ let count = |s: &str| rows.iter().filter(|r| r.state == s).count();
+ let (working, blocked, idle, unknown) = (count("working"), count("blocked"), count("idle"), count("unknown"));
+ if rows.is_empty() {
+ return tr("right-agents-none");
+ }
+ let part = |key: &str, n: usize| {
+ let mut args = FluentArgs::new();
+ args.set("count", n as i64);
+ tr_args(key, &args)
+ };
+ let mut parts = Vec::new();
+ if working > 0 {
+ parts.push(part("right-agents-count-working", working));
+ }
+ if blocked > 0 {
+ parts.push(part("right-agents-count-blocked", blocked));
+ }
+ if parts.is_empty() {
+ if idle > 0 {
+ parts.push(part("right-agents-count-idle", idle));
+ }
+ if unknown > 0 {
+ parts.push(part("right-agents-count-unknown", unknown));
+ }
+ }
+ parts.join(" · ")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn row(pane: PaneId, agent: &str, state: &'static str, place: &str) -> AgentRow {
+ AgentRow {
+ pane,
+ window: None,
+ here: false,
+ agent_id: agent.into(),
+ name: display_name(agent),
+ title: String::new(),
+ state,
+ state_label: String::new(),
+ place: place.into(),
+ icon: icon(agent),
+ }
+ }
+
+ #[test]
+ fn names_and_icons_follow_the_desktop() {
+ assert_eq!(display_name("claude"), "Claude Code");
+ assert_eq!(display_name("gemini"), "Gemini");
+ assert_eq!(icon("claude"), "brand-claude");
+ assert_eq!(icon("gemini"), "bot");
+ }
+
+ #[test]
+ fn the_summary_counts_like_the_desktop() {
+ assert_eq!(summary(&[]), "No agents detected");
+ let rows = vec![row(1, "claude", "working", "a"), row(2, "codex", "working", "a"), row(3, "pi", "blocked", "b")];
+ assert_eq!(summary(&rows), "2 working · 1 needs input");
+ let quiet = vec![row(1, "claude", "idle", "a"), row(2, "codex", "unknown", "a"), row(3, "pi", "unknown", "a")];
+ assert_eq!(summary(&quiet), "1 idle · 2 unknown");
+ }
+}
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rs
index 0c871ae3..0c07142d 100644
--- a/thinkterm-web/src/app.rs
+++ b/thinkterm-web/src/app.rs
@@ -14,6 +14,7 @@ use std::rc::Rc;
use std::sync::Arc;
use termwiz::input::{KeyCode, Modifiers};
use thinkterm_font_core::FontShaper as _;
+use thinkterm_i18n::tr;
use thinkterm_font_web::FontSet;
use thinkterm_proto::{PaneId, TabId};
use thinkterm_render::atlas::OutOfTextureSpace;
@@ -88,7 +89,6 @@ pub struct Setup {
pub fonts: Rc<FontSet>,
pub canvas: web_sys::HtmlCanvasElement,
pub textarea: web_sys::HtmlTextAreaElement,
- pub status: Option<web_sys::Element>,
/// Kept so the page can reopen the socket by itself.
pub url: String,
pub token: String,
@@ -99,11 +99,10 @@ pub struct Setup {
pub dpr: f64,
pub cols: usize,
pub rows: usize,
- pub strip: Option<crate::chrome::TabStrip>,
- pub navs: Option<crate::navbar::NavBars>,
- pub side: Option<crate::sidebar::Sidebar>,
/// `?font=` was given: the size is the user's, not the desktop's.
pub font_pinned: bool,
+ /// The browser's languages, for switching the locale by preference.
+ pub languages: Vec<String>,
}
/// One pane on the page: its session and the state that is the page's
@@ -158,7 +157,6 @@ pub struct Inner {
fonts: Rc<FontSet>,
canvas: web_sys::HtmlCanvasElement,
textarea: web_sys::HtmlTextAreaElement,
- status: Option<web_sys::Element>,
tab_id: TabId,
/// Tabs this page has shown, most recent first: a thread opens on
/// the tab it was left at, not the window's active one, since the
@@ -170,6 +168,11 @@ pub struct Inner {
cols: usize,
rows: usize,
font_pinned: bool,
+ languages: Vec<String>,
+ /// Palette picks, most recent first; the page keeps them across loads.
+ recent: Vec<String>,
+ /// The page's preferences, as it handed them over.
+ settings: crate::settings::WebSettings,
/// Word/line selection extends by units; the pointer is down.
selecting: bool,
/// The pane a drag started in; it keeps the drag until the release.
@@ -216,15 +219,15 @@ pub struct Inner {
/// default: a page opened to "see my terminal" wants the one being
/// used. Choosing a pane here turns it off.
following: bool,
- strip: Option<crate::chrome::TabStrip>,
- navs: Option<crate::navbar::NavBars>,
- /// The bars' last markup, so an unchanged layout costs no DOM work.
- nav_html: std::cell::RefCell<String>,
+ /// The page's display layer, told once per animation frame that
+ /// something it shows changed; it reads the views it wants.
+ on_change: Option<js_sys::Function>,
+ notify_pending: Rc<Cell<bool>>,
+ /// What the status views report: the current remark and the summary.
+ toast: RefCell<Option<crate::views::Toast>>,
+ summary: RefCell<String>,
/// The timer that hides the passing remark, so a new one restarts it.
- toast_timer: Cell<Option<i32>>,
tree: crate::tree::TreeModel,
- side: Option<crate::sidebar::Sidebar>,
- side_html: RefCell<String>,
session_refresh_pending: bool,
/// A thread's delete button was pressed once, and when.
deleting: Option<(String, f64)>,
@@ -351,6 +354,14 @@ impl Inner {
}
}
+/// The toast for a request that failed: `what` is a `web-act-*` key.
+fn failed(what: &str, err: &dyn std::fmt::Display) -> String {
+ let mut args = thinkterm_i18n::FluentArgs::new();
+ args.set("what", tr(what));
+ args.set("error", format!("{err:#}"));
+ thinkterm_i18n::tr_args("web-toast-failed", &args)
+}
+
impl App {
pub fn new(setup: Setup) -> Rc<Self> {
let mut panes = std::collections::BTreeMap::new();
@@ -367,7 +378,6 @@ impl App {
fonts: setup.fonts,
canvas: setup.canvas,
textarea: setup.textarea,
- status: setup.status,
tab_id: setup.tab_id,
recent_tabs: vec![setup.tab_id],
window_id: setup.window_id,
@@ -393,19 +403,20 @@ impl App {
connected_since: None,
capacity: Capacity::new(),
font_pinned: setup.font_pinned,
+ languages: setup.languages,
+ recent: Vec::new(),
+ settings: crate::settings::WebSettings::default(),
quads: HeapQuadAllocator::default(),
vertices: Vec::new(),
pane_fonts: Default::default(),
layout: None,
tab_layout: None,
following: true,
- strip: setup.strip,
- navs: setup.navs,
- nav_html: std::cell::RefCell::new(String::new()),
- toast_timer: Cell::new(None),
+ on_change: None,
+ notify_pending: Rc::new(Cell::new(false)),
+ toast: RefCell::new(None),
+ summary: RefCell::new(String::new()),
tree: crate::tree::TreeModel::default(),
- side: setup.side,
- side_html: RefCell::new(String::new()),
session_refresh_pending: false,
deleting: None,
editing: crate::sidebar::Editing::None,
@@ -498,73 +509,107 @@ impl App {
/// desktop has no status line, and neither does the page. It stays
/// while the connection is down: that is not a remark but the state.
fn set_status(inner: &Inner, text: &str) {
- let Some(el) = &inner.status else {
- return;
- };
- el.set_text_content(Some(text));
- let _ = el.remove_attribute("hidden");
- let Some(window) = web_sys::window() else {
- return;
- };
- if let Some(id) = inner.toast_timer.take() {
- window.clear_timeout_with_handle(id);
- }
+ *inner.toast.borrow_mut() = Some(crate::views::Toast {
+ text: text.to_string(),
+ sticky: inner.disconnected.is_some(),
+ at: monotonic_ms(),
+ });
if inner.disconnected.is_some() {
// Not a remark but the state: probes read it there too.
- let _ = el.set_attribute("data-summary", text);
- return;
+ *inner.summary.borrow_mut() = text.to_string();
}
- let el = el.clone();
- let hide = Closure::once_into_js(move || {
- let _ = el.set_attribute("hidden", "");
- });
- inner.toast_timer.set(
- window
- .set_timeout_with_callback_and_timeout_and_arguments_0(hide.as_ref().unchecked_ref(), 4000)
- .ok(),
- );
+ Self::notify(inner);
}
pub fn hide_status(&self) {
- if let Some(el) = &self.inner.borrow().status {
- let _ = el.set_attribute("hidden", "");
- }
+ let inner = self.inner.borrow();
+ *inner.toast.borrow_mut() = None;
+ Self::notify(&inner);
}
- /// The card the desktop shows over a terminal another device holds,
- /// with its words; hidden when this page may type.
- fn show_card(inner: &Inner) {
- let Some(card) = web_sys::window()
- .and_then(|w| w.document())
- .and_then(|d| d.get_element_by_id("card"))
- else {
- return;
- };
+ /// The desktop's words over a terminal another device holds, or none
+ /// when this page may type.
+ fn card(inner: &Inner) -> Option<crate::views::Card> {
let lease = inner.link.lease();
- let words = match lease.mode {
+ match lease.mode {
Some(codec::FrontendAccessMode::Handoff) if !lease.owns_viewport() => Some(if lease.owner.is_some() {
- ("Terminal is being used on another device", "Click or scroll to continue")
+ crate::views::Card { title: tr("web-card-busy-title"), hint: tr("web-card-busy-hint") }
} else {
- ("Terminal is available", "Click or scroll to take control")
+ crate::views::Card { title: tr("web-card-free-title"), hint: tr("web-card-free-hint") }
}),
_ => None,
+ }
+ }
+
+ /// Tell the display layer that a view changed: once per task, so a
+ /// burst of changes is one notice. A task rather than an animation
+ /// frame, since the page's frames are the terminal's, and a notice
+ /// that waited for one would be counted -- and paced -- as a paint.
+ fn notify(inner: &Inner) {
+ let Some(cb) = inner.on_change.clone() else {
+ return;
};
- match words {
- Some((title, hint)) => {
- if let Some(t) = card.query_selector(".title").ok().flatten() {
- t.set_text_content(Some(title));
- }
- if let Some(h) = card.query_selector(".hint").ok().flatten() {
- h.set_text_content(Some(hint));
- }
- let _ = card.remove_attribute("hidden");
- }
- None => {
- let _ = card.set_attribute("hidden", "");
+ if inner.notify_pending.replace(true) {
+ return;
+ }
+ let pending = Rc::clone(&inner.notify_pending);
+ let tick = Closure::once_into_js(move || {
+ pending.set(false);
+ if let Err(err) = cb.call0(&JsValue::NULL) {
+ log::warn!("the page's change handler failed: {err:?}");
}
+ });
+ let queued = web_sys::window()
+ .map(|w| w.set_timeout_with_callback_and_timeout_and_arguments_0(tick.as_ref().unchecked_ref(), 0).is_ok())
+ .unwrap_or(false);
+ if !queued {
+ inner.notify_pending.set(false);
}
}
+ /// The language changed: every view carries text, so all are stale.
+ pub fn locale_changed(&self) {
+ let inner = self.inner.borrow();
+ Self::render_strip(&inner);
+ }
+
+ pub fn set_on_change(&self, cb: js_sys::Function) {
+ let mut inner = self.inner.borrow_mut();
+ inner.on_change = Some(cb);
+ drop(inner);
+ Self::notify(&self.inner.borrow());
+ }
+
+ pub fn sidebar_view(&self) -> crate::views::SidebarView {
+ let inner = self.inner.borrow();
+ crate::views::SidebarView {
+ rows: Self::side_rows(&inner),
+ editing: inner.editing.clone(),
+ space: inner.tree.current_space().map(|s| s.id.clone()),
+ }
+ }
+
+ pub fn tabs_view(&self) -> crate::views::TabsView {
+ let inner = self.inner.borrow();
+ let (tabs, controls) = Self::strip_model(&inner).unwrap_or_default();
+ crate::views::TabsView { tabs, controls }
+ }
+
+ pub fn navs_view(&self) -> crate::views::NavsView {
+ Self::nav_views(&self.inner.borrow())
+ }
+
+ pub fn status_view(&self) -> crate::views::StatusView {
+ let inner = self.inner.borrow();
+ let toast = inner.toast.borrow().clone();
+ let summary = inner.summary.borrow().clone();
+ crate::views::StatusView { toast, card: Self::card(&inner), summary }
+ }
+
+ pub fn layout_view(&self) -> String {
+ Self::layout_json(&self.inner.borrow())
+ }
+
/// The server pushed something for us.
pub fn on_push(self: &Rc<Self>, pdu: Pdu) {
let inner = self.inner.borrow();
@@ -581,7 +626,7 @@ impl App {
let cell = &inner.panes[&removed.pane_id];
cell.session.set_dead(true);
if removed.pane_id == inner.focused_pane {
- Self::set_status(&inner, "the pane was closed on the server");
+ Self::set_status(&inner, &tr("web-toast-pane-closed"));
}
// Something else to show, if the server has anything.
drop(inner);
@@ -628,13 +673,13 @@ impl App {
self.inner.borrow_mut().tree.apply_tree(state.tree);
// The session view is not pushed with it: ask.
self.refresh_session_soon();
- Self::render_side(&self.inner.borrow());
+ Self::notify(&self.inner.borrow());
}
Pdu::ThinkTermSessionState(state) => {
drop(inner);
let changed = self.inner.borrow_mut().tree.apply_session(state);
if changed {
- Self::render_side(&self.inner.borrow());
+ Self::notify(&self.inner.borrow());
}
}
Pdu::AgentStatusChanged(codec::AgentStatusChanged { pane_id, status }) => {
@@ -872,10 +917,7 @@ impl App {
}
// The one-line summary is for probes and tests; the page shows
// the card and the strip's hint instead.
- if let Some(el) = &inner.status {
- let _ = el.set_attribute("data-summary", &text);
- }
- Self::show_card(&inner);
+ *inner.summary.borrow_mut() = text;
Self::render_strip(&inner);
}
@@ -1190,7 +1232,7 @@ impl App {
.await;
app.focus_pane(pane, false);
app.act(
- "resize the pane",
+ "web-act-resize-pane",
Pdu::AdjustPaneSize(codec::AdjustPaneSize { pane_id: pane, direction, amount }),
|_, _| {},
);
@@ -1628,17 +1670,16 @@ impl App {
self.request_frame();
}
- pub fn strip_element(&self) -> Option<web_sys::EventTarget> {
- let inner = self.inner.borrow();
- let strip = inner.strip.as_ref()?;
- let target: &web_sys::EventTarget = strip.element().as_ref();
- Some(target.clone())
- }
-
/// What the page has laid out, as JSON on the canvas element for the
/// smoke tests and anyone else curious: `canvas.dataset.layout`.
/// Rewritten whenever the strip is, which is whenever it changes.
fn publish_layout(inner: &Inner) {
+ let json = Self::layout_json(inner);
+ let _ = inner.canvas.set_attribute("data-layout", &json);
+ }
+
+ /// The layout as a probe reads it.
+ fn layout_json(inner: &Inner) -> String {
let lease = inner.link.lease();
let dpr = inner.dpr.max(0.1);
let (cw, ch) = (
@@ -1700,7 +1741,7 @@ impl App {
None => json.push_str(",\"cols\":null,\"rows\":null,\"zoomed\":null,\"panes\":[],\"dividers\":[]"),
}
json.push('}');
- let _ = inner.canvas.set_attribute("data-layout", &json);
+ json
}
/// Draw the tab strip from what the page knows.
@@ -1739,11 +1780,8 @@ impl App {
crate::navbar::nav_rows(Self::nav_css(inner) * inner.dpr, inner.glyphs.metrics.cell_size.height as f64)
}
- /// One bar per drawn pane, positioned from the layout's cells.
- fn render_navs(inner: &Inner) {
- let Some(navs) = &inner.navs else {
- return;
- };
+ /// One bar per drawn pane, as the page shows them.
+ fn nav_views(inner: &Inner) -> Vec<crate::navbar::NavView> {
let mut views = Vec::new();
if let Some(layout) = &inner.tab_layout {
let dpr = inner.dpr.max(0.1);
@@ -1791,92 +1829,17 @@ impl App {
});
}
}
- let html = crate::navbar::NavBars::html(&views);
- let mut last = inner.nav_html.borrow_mut();
- if *last != html {
- navs.set(&html);
- *last = html;
- }
+ views
}
- pub fn navs_element(&self) -> Option<web_sys::EventTarget> {
- let inner = self.inner.borrow();
- inner.navs.as_ref().map(|n| n.element().clone().into())
- }
-
- /// The sidebar from the model, when its markup changed.
- fn render_side(inner: &Inner) {
- let Some(side) = &inner.side else {
- return;
- };
+ /// The sidebar's rows from the model, with the pending delete shown.
+ fn side_rows(inner: &Inner) -> Vec<crate::tree::Row> {
let deleting = inner
.deleting
.as_ref()
.filter(|(_, since)| monotonic_ms() - since < CLOSE_CONFIRM_MS)
.map(|(id, _)| id.as_str());
- let rows = inner.tree.rows_with(inner.tab_id, &inner.workspace, inner.window_id, deleting);
- let html = crate::sidebar::html(&rows, &inner.editing);
- let mut last = inner.side_html.borrow_mut();
- if *last != html {
- side.set(&html);
- *last = html;
- if inner.editing != crate::sidebar::Editing::None {
- if let Some(input) = side.element().query_selector("input").ok().flatten() {
- if let Ok(input) = input.dyn_into::<web_sys::HtmlInputElement>() {
- let _ = input.focus();
- input.select();
- }
- }
- }
- }
- let _ = side.element().set_attribute("data-rows", &Self::rows_json(&rows));
- }
-
- /// The rows as a probe reads them.
- fn rows_json(rows: &[crate::tree::Row]) -> String {
- use crate::tree::Row;
- let mut json = String::from("[");
- for (i, row) in rows.iter().enumerate() {
- if i > 0 {
- json.push(',');
- }
- let esc = |s: &str| s.replace('\\', "\\\\").replace('"', "\\\"");
- match row {
- Row::Space { name } => json.push_str(&format!("{{\"kind\":\"space\",\"name\":\"{}\"}}", esc(name))),
- Row::NewThread => json.push_str("{\"kind\":\"new-thread\"}"),
- Row::Pinned => json.push_str("{\"kind\":\"pinned\"}"),
- Row::Workspaces => json.push_str("{\"kind\":\"workspaces\"}"),
- Row::Project { id, name, collapsed, archived, .. } => json.push_str(&format!(
- "{{\"kind\":\"project\",\"id\":\"{}\",\"name\":\"{}\",\"collapsed\":{collapsed},\"archived\":{archived}}}",
- esc(id),
- esc(name)
- )),
- Row::Thread(t) => json.push_str(&format!(
- "{{\"kind\":\"thread\",\"id\":\"{}\",\"project\":\"{}\",\"name\":\"{}\",\"status\":\"{:?}\",\"dot\":\"{:?}\",\"pinned\":{},\"live\":{},\"selected\":{}}}",
- esc(&t.id),
- esc(&t.project_id),
- esc(&t.name),
- t.status,
- t.dot,
- t.pinned,
- t.live,
- t.selected
- )),
- Row::Archived { count, open } => json.push_str(&format!("{{\"kind\":\"archived\",\"count\":{count},\"open\":{open}}}")),
- Row::Others => json.push_str("{\"kind\":\"others\"}"),
- Row::Window { window_id, title, selected } => json.push_str(&format!(
- "{{\"kind\":\"window\",\"id\":{window_id},\"title\":\"{}\",\"selected\":{selected}}}",
- esc(title)
- )),
- }
- }
- json.push(']');
- json
- }
-
- pub fn side_element(&self) -> Option<web_sys::EventTarget> {
- let inner = self.inner.borrow();
- inner.side.as_ref().map(|s| s.element().clone().into())
+ inner.tree.rows_with(inner.tab_id, &inner.workspace, inner.window_id, deleting)
}
/// Ask the server for its tree, its session view and the agents in
@@ -1905,6 +1868,7 @@ impl App {
inner.tree.agents.clear();
for e in entries {
inner.tree.apply_agent(e.pane_id, Some(&e.status));
+ inner.tree.record_agent_details(e.pane_id, &e.status.agent_id, &e.title);
}
}
Err(err) => log::warn!("fetching agent statuses: {err:#}"),
@@ -1924,7 +1888,7 @@ impl App {
match state {
Ok(state) => {
self.inner.borrow_mut().tree.apply_session(state);
- Self::render_side(&self.inner.borrow());
+ Self::notify(&self.inner.borrow());
}
Err(err) => log::warn!("fetching the session view: {err:#}"),
}
@@ -1994,12 +1958,12 @@ impl App {
if !inner.tree.collapsed.remove(&id) {
inner.tree.collapsed.insert(id);
}
- Self::render_side(inner);
+ Self::notify(inner);
}
SideClick::ToggleArchived => {
let inner = &mut *self.inner.borrow_mut();
inner.tree.archived_open = !inner.tree.archived_open;
- Self::render_side(inner);
+ Self::notify(inner);
}
other => self.on_side_write(other),
}
@@ -2057,7 +2021,7 @@ impl App {
fn kill_panes(self: &Rc<Self>, panes: Vec<PaneId>) {
for pane_id in panes {
- self.act("close the pane", Pdu::KillPane(codec::KillPane { pane_id }), |_, _| {});
+ self.act("web-act-close-pane", Pdu::KillPane(codec::KillPane { pane_id }), |_, _| {});
}
}
@@ -2071,10 +2035,7 @@ impl App {
SideClick::NewThread(project) => {
let (project, size) = {
let inner = self.inner.borrow();
- let selected = inner.tree.selected_thread(inner.tab_id, &inner.workspace).map(String::from);
- let project = project
- .or_else(|| selected.and_then(|t| inner.tree.project_of(&t).map(|p| p.id.clone())))
- .or_else(|| inner.tree.session.as_ref().and_then(|s| s.projects.first().map(|p| p.id.clone())));
+ let project = project.or_else(|| inner.tree.default_project(inner.tab_id, &inner.workspace));
let size = inner.link.lease().canonical_size.unwrap_or_default();
(project, size)
};
@@ -2104,7 +2065,7 @@ impl App {
app.fetch_tree();
app.activate_thread(r.thread_id);
}
- Err(err) => Self::set_status(&app.inner.borrow(), &format!("could not start a thread: {err:#}")),
+ Err(err) => Self::set_status(&app.inner.borrow(), &failed("web-act-start-thread", &err)),
}
});
}
@@ -2113,17 +2074,17 @@ impl App {
SideClick::NewProject => {
let inner = &mut *self.inner.borrow_mut();
inner.editing = Editing::NewProject;
- Self::render_side(inner);
+ Self::notify(inner);
}
SideClick::RenameThread(id) => {
let inner = &mut *self.inner.borrow_mut();
inner.editing = Editing::Thread(id);
- Self::render_side(inner);
+ Self::notify(inner);
}
SideClick::RenameProject(id) => {
let inner = &mut *self.inner.borrow_mut();
inner.editing = Editing::Project(id);
- Self::render_side(inner);
+ Self::notify(inner);
}
SideClick::Pin(id, on) => {
self.mutate(crate::tree::set_pinned(&id, on, Self::now_secs()), |_| {});
@@ -2139,7 +2100,7 @@ impl App {
}
_ => {
inner.deleting = Some((id.clone(), now));
- Self::render_side(&inner);
+ Self::notify(&inner);
false
}
}
@@ -2167,9 +2128,8 @@ impl App {
SideClick::Unarchive(id) => {
self.mutate(crate::tree::archive_project(&id, false, Self::now_secs()), |_| {});
}
- SideClick::SpaceMenu => {
- Self::set_status(&self.inner.borrow(), "Spaces are managed on the desktop");
- }
+ // The page opens the Space menu itself (`context_menu("space")`).
+ SideClick::SpaceMenu => {}
_ => {}
}
}
@@ -2182,14 +2142,14 @@ impl App {
"Escape" => {
let inner = &mut *self.inner.borrow_mut();
inner.editing = Editing::None;
- Self::render_side(inner);
+ Self::notify(inner);
let _ = inner.textarea.focus();
}
"Enter" => {
{
let inner = &mut *self.inner.borrow_mut();
inner.editing = Editing::None;
- Self::render_side(inner);
+ Self::notify(inner);
let _ = inner.textarea.focus();
}
let value = value.trim().to_string();
@@ -2199,15 +2159,14 @@ impl App {
match editing {
Editing::Thread(id) => self.mutate(crate::tree::rename_thread(&id, &value, Self::now_secs()), |_| {}),
Editing::Project(id) => self.mutate(crate::tree::rename_project(&id, &value), |_| {}),
+ Editing::Space(id) => self.mutate(crate::tree::rename_space(&id, &value), |_| {}),
Editing::NewProject => {
if !(value.starts_with('/') || value.starts_with('~')) {
Self::set_status(&self.inner.borrow(), "a project is a directory: ~/dir or /dir");
return;
}
- let space = {
- let inner = self.inner.borrow();
- inner.tree.tree.as_ref().and_then(|t| t.spaces.first().map(|s| s.id.clone()))
- };
+ // The new project lands in the Space on show.
+ let space = self.inner.borrow().tree.current_space().map(|s| s.id.clone());
let project = Self::new_id("project");
let thread = Self::new_id("thread");
let intent = crate::tree::create_project(space.as_deref(), project, thread.clone(), &value, Self::now_secs());
@@ -2265,7 +2224,7 @@ impl App {
Ok(r) => workspace = Some(r.workspace),
Err(err) => {
log::warn!("opening thread {id}: {err:#}");
- Self::set_status(&app.inner.borrow(), &format!("could not open the thread: {err:#}"));
+ Self::set_status(&app.inner.borrow(), &failed("web-act-open-thread", &err));
return;
}
}
@@ -2305,24 +2264,16 @@ impl App {
});
}
- /// The sidebar's width, kept per browser, within the desktop's bounds.
- pub fn set_sidebar_width(&self, css: f64) {
- let css = css.clamp(crate::sidebar::MIN_WIDTH, crate::sidebar::MAX_WIDTH);
- if let Some(doc) = web_sys::window().and_then(|w| w.document()) {
- if let Some(root) = doc.document_element().and_then(|e| e.dyn_into::<web_sys::HtmlElement>().ok()) {
- let _ = root.style().set_property("--side-w", &format!("{css:.0}px"));
- }
- }
- crate::sidebar::store_width(css);
- }
-
+ /// Something the chrome shows changed: the probe's attribute is
+ /// rewritten and the page is told.
fn render_strip(inner: &Inner) {
Self::publish_layout(inner);
- Self::render_navs(inner);
- Self::render_side(inner);
- let (Some(strip), Some(layout)) = (&inner.strip, &inner.layout) else {
- return;
- };
+ Self::notify(inner);
+ }
+
+ /// The strip's tabs and state, once there is a listing.
+ fn strip_model(inner: &Inner) -> Option<(Vec<crate::chrome::TabView>, crate::chrome::Controls)> {
+ let layout = inner.layout.as_ref()?;
let tabs = crate::chrome::model(layout, inner.focused_pane, inner.title(), Some(inner.window_id));
let (cols, rows) = inner
.tab_layout
@@ -2338,7 +2289,7 @@ impl App {
.map(|(tab, _)| tab),
clipped: (cols > inner.cols || rows > inner.rows).then_some((inner.cols, inner.rows)),
};
- strip.render(&tabs, controls);
+ Some((tabs, controls))
}
/// List the server's panes again, redraw the strip, and bring the tab
@@ -2401,7 +2352,7 @@ impl App {
let mut inner = self.inner.borrow_mut();
inner.layout = Some(list);
Self::render_strip(&inner);
- Self::set_status(&inner, "the server has no panes to show");
+ Self::set_status(&inner, &tr("web-toast-no-panes"));
return;
};
let (link, tab_changed) = {
@@ -2436,7 +2387,7 @@ impl App {
inner.switching = false;
if let Err(err) = outcome {
log::warn!("switching to tab {}: {err:#}", layout.tab_id);
- Self::set_status(&inner, &format!("could not switch tabs: {err:#}"));
+ Self::set_status(&inner, &failed("web-act-switch-tabs", &err));
return;
}
}
@@ -2499,7 +2450,7 @@ impl App {
if !dragging {
if let Err(err) = link.report_viewport(tab_id).await {
log::warn!("reporting the tab shape: {err:#}");
- Self::set_status(&self.inner.borrow(), &format!("could not report the tab's shape: {err:#}"));
+ Self::set_status(&self.inner.borrow(), &failed("web-act-report-shape", &err));
}
}
// A listing that changed nothing (the timer's, mostly) is not a
@@ -2633,7 +2584,7 @@ impl App {
// A stack member behind the drawn one: the server
// brings it to the front, then it is focused.
self.act(
- "activate the pane",
+ "web-act-activate-pane",
Pdu::ActivatePaneInStack(codec::ActivatePaneInStack { pane_id }),
move |app, _| app.switch_to_pane(pane_id, true),
);
@@ -2641,18 +2592,6 @@ impl App {
self.switch_to_pane(pane_id, true);
}
}
- Click::Sidebar => {
- if let Some(body) = web_sys::window().and_then(|w| w.document()).and_then(|d| d.body()) {
- let off = body.get_attribute("data-side").as_deref() == Some("off");
- if off {
- let _ = body.remove_attribute("data-side");
- } else {
- let _ = body.set_attribute("data-side", "off");
- }
- }
- // The canvas's box moved; its observer resizes it.
- let _ = self.inner.borrow().textarea.focus();
- }
Click::CloseTab(tab_id) => {
let panes: Vec<PaneId> = {
let mut inner = self.inner.borrow_mut();
@@ -2683,7 +2622,7 @@ impl App {
};
for pane_id in panes {
self.act(
- "close the tab",
+ "web-act-close-tab",
Pdu::KillPane(codec::KillPane { pane_id }),
|_, _| {},
);
@@ -2765,7 +2704,7 @@ impl App {
Err(err) => {
log::warn!("{what}: {err:#}");
let inner = app.inner.borrow();
- Self::set_status(&inner, &format!("could not {what}: {err:#}"));
+ Self::set_status(&inner, &failed(what, &err));
}
}
let _ = app.inner.borrow().textarea.focus();
@@ -2785,7 +2724,7 @@ impl App {
(inner.window_id, inner.workspace.clone(), size)
};
self.act(
- "open a new tab",
+ "web-act-new-tab",
Pdu::SpawnV2(codec::SpawnV2 {
domain: thinkterm_proto::SpawnTabDomain::CurrentPaneDomain,
window_id: Some(window_id),
@@ -2805,14 +2744,19 @@ impl App {
/// Split the focused pane; the new pane takes the focus.
pub fn split(self: &Rc<Self>, pane: Option<PaneId>, direction: thinkterm_proto::SplitDirection) {
+ self.split_at(pane, direction, true);
+ }
+
+ /// Split with the new pane after (`second`) or before the target.
+ pub fn split_at(self: &Rc<Self>, pane: Option<PaneId>, direction: thinkterm_proto::SplitDirection, second: bool) {
let pane_id = self.target_pane(pane);
self.act(
- "split the pane",
+ "web-act-split-pane",
Pdu::SplitPane(codec::SplitPane {
pane_id,
split_request: thinkterm_proto::SplitRequest {
direction,
- target_is_second: true,
+ target_is_second: second,
top_level: false,
size: thinkterm_proto::SplitSize::Percent(50),
},
@@ -2829,6 +2773,415 @@ impl App {
);
}
+ /// A context menu for something on the page: `kind` names what was
+ /// clicked, `id` which one. Empty when there is nothing to offer.
+ pub fn context_menu(&self, kind: &str, id: &str) -> Vec<crate::menu::MenuItem> {
+ use crate::menu;
+ let inner = self.inner.borrow();
+ let menu = match kind {
+ "pane" => id.parse().ok().map(|pane| menu::for_pane(pane, inner.link.lease().mode)),
+ "tab" => id.parse().ok().and_then(|tab: TabId| {
+ let (tabs, _) = Self::strip_model(&inner)?;
+ let index = tabs.iter().position(|t| t.tab_id == tab)?;
+ Some(menu::for_tab(tab, index, tabs.len(), tabs[index].target))
+ }),
+ "thread" => Self::side_rows(&inner).into_iter().find_map(|row| match row {
+ crate::tree::Row::Thread(t) if t.id == id => Some(menu::for_thread(&t)),
+ _ => None,
+ }),
+ "project" => Some(menu::for_project(id, inner.tree.live_panes_of_project(id).len())),
+ "archived-project" => Some(menu::for_archived_project(id, inner.tree.thread_count_of_project(id))),
+ "sidebar-options" => Some(menu::for_sidebar_options(inner.tree.archived_open, inner.tree.archived_count())),
+ "space" => Some(menu::for_space(&inner.tree.spaces())),
+ "notifications" => Some(menu::for_notifications()),
+ _ => None,
+ };
+ menu.unwrap_or_default()
+ }
+
+ /// The Agents panel: every pane an agent runs in, and the summary line.
+ pub fn agents_view(&self) -> crate::agents::AgentsView {
+ let inner = self.inner.borrow();
+ let rows = crate::agents::rows(&inner.tree, inner.window_id, |pane| {
+ inner.panes.get(&pane).map(|c| crate::navbar::display_title(&c.title).0)
+ });
+ let summary = crate::agents::summary(&rows);
+ crate::agents::AgentsView { rows, summary }
+ }
+
+ /// Bring an agent's pane on show: switch to it here, or open the
+ /// thread that holds it when it is in another window.
+ pub fn agent_reveal(self: &Rc<Self>, pane: PaneId) -> bool {
+ let (here, thread) = {
+ let inner = self.inner.borrow();
+ let here = inner.tab_layout.as_ref().is_some_and(|l| l.panes.iter().any(|p| p.stack.iter().any(|m| m.pane_id == pane)))
+ || inner.layout.as_ref().is_some_and(|l| {
+ l.tabs
+ .iter()
+ .filter(|t| t.window_and_tab_ids().is_some_and(|(w, _)| w == inner.window_id))
+ .any(|t| crate::layout::leaves(t).iter().any(|e| e.pane_id == pane))
+ });
+ let thread = inner.tree.session.as_ref().and_then(|s| {
+ s.projects.iter().flat_map(|p| p.threads.iter()).find(|t| t.tabs.iter().any(|tab| tab.pane_ids.contains(&pane))).map(|t| t.id.clone())
+ });
+ (here, thread)
+ };
+ if here {
+ self.switch_to_pane(pane, true);
+ return true;
+ }
+ match thread {
+ Some(id) => {
+ let space = self.inner.borrow().tree.project_of(&id).map(|p| p.space_id.clone());
+ if let Some(space) = space {
+ self.set_space(&space);
+ }
+ self.activate_thread(id);
+ true
+ }
+ None => {
+ // A window no thread claims: its listing knows the pane.
+ self.switch_to_pane(pane, true);
+ true
+ }
+ }
+ }
+
+ /// The page's preferences, as the model holds them.
+ pub fn settings_view(&self) -> crate::settings::WebSettings {
+ self.inner.borrow().settings.clone()
+ }
+
+ /// The page's stored preferences, at boot: applied whole.
+ pub fn apply_settings(self: &Rc<Self>, json: &str) -> Result<(), String> {
+ let settings = crate::settings::WebSettings::parse(json)?;
+ self.inner.borrow_mut().settings = settings.clone();
+ self.apply_language(&settings.language);
+ self.set_font_mode(settings.font);
+ Ok(())
+ }
+
+ /// One preference changed on the page.
+ pub fn set_setting(self: &Rc<Self>, key: &str, value: &str) -> Result<(), String> {
+ let (language, font) = {
+ let mut inner = self.inner.borrow_mut();
+ inner.settings.set(key, value)?;
+ (inner.settings.language.clone(), inner.settings.font)
+ };
+ match key {
+ "language" => self.apply_language(&language),
+ "font" => self.set_font_mode(font),
+ _ => Self::notify(&self.inner.borrow()),
+ }
+ Ok(())
+ }
+
+ fn apply_language(&self, preference: &str) {
+ let languages = self.inner.borrow().languages.clone();
+ thinkterm_i18n::activate_preference(preference, &languages);
+ self.locale_changed();
+ }
+
+ /// The base font: a size of the page's own, or the desktop's cell
+ /// again. Pinning rasterises at that size and refits the grid.
+ pub fn set_font_mode(self: &Rc<Self>, mode: crate::settings::FontMode) {
+ use crate::settings::FontMode;
+ match mode {
+ FontMode::Pinned { pt } => {
+ let pt = pt.clamp(6.0, 72.0);
+ let mut inner = self.inner.borrow_mut();
+ inner.font_pinned = true;
+ if (inner.glyphs.size_pt - pt).abs() >= 0.125 {
+ let dpi = (96.0 * inner.dpr) as u32;
+ Self::rerasterise(&mut inner, pt, dpi);
+ inner.cols = 0;
+ }
+ drop(inner);
+ self.resize();
+ self.request_frame();
+ }
+ FontMode::Follow => {
+ self.inner.borrow_mut().font_pinned = false;
+ self.match_desktop_cell();
+ self.request_frame();
+ }
+ }
+ }
+
+ /// What the palette can find, from the model, ranked for `query`.
+ pub fn palette(&self, query: &str) -> crate::palette::Results {
+ use crate::palette::{path_terms, Entry, Group};
+ let inner = self.inner.borrow();
+ let mut entries = Vec::new();
+ if let Some(session) = &inner.tree.session {
+ let space_name = |id: &str| session.spaces.iter().find(|s| s.id == id).map(|s| s.name.clone()).unwrap_or_default();
+ for project in &session.projects {
+ for thread in &project.threads {
+ let icon = match inner.tree.status_of(thread) {
+ crate::tree::Status::Running => "loader-circle",
+ crate::tree::Status::NeedsAttention => "circle-alert",
+ crate::tree::Status::Done => "circle-check",
+ crate::tree::Status::Idle => "square-terminal",
+ };
+ entries.push(Entry {
+ id: format!("thread:{}", thread.id),
+ title: thread.name.clone(),
+ subtitle: project.name.clone(),
+ icon,
+ accessory: space_name(&project.space_id),
+ group: Group::Threads,
+ terms: path_terms(&project.path),
+ });
+ }
+ }
+ }
+ if let Some((tabs, _)) = Self::strip_model(&inner) {
+ for tab in tabs {
+ entries.push(Entry {
+ id: format!("tab:{}", tab.tab_id),
+ title: tab.label,
+ subtitle: String::new(),
+ icon: "square-terminal",
+ accessory: String::new(),
+ group: Group::Tabs,
+ terms: tab.title,
+ });
+ }
+ }
+ if let Some(layout) = &inner.tab_layout {
+ for place in &layout.panes {
+ for member in &place.stack {
+ let raw = inner.panes.get(&member.pane_id).map(|c| c.title.as_str()).unwrap_or(&member.title);
+ let (title, _) = crate::navbar::display_title(raw);
+ entries.push(Entry {
+ id: format!("pane:{}", member.pane_id),
+ title,
+ subtitle: String::new(),
+ icon: "square-terminal",
+ accessory: String::new(),
+ group: Group::Panes,
+ terms: raw.to_string(),
+ });
+ }
+ }
+ }
+ let spaces = inner.tree.spaces();
+ if spaces.len() > 1 {
+ for space in spaces {
+ entries.push(Entry {
+ id: format!("space:{}", space.id),
+ title: space.name,
+ subtitle: String::new(),
+ icon: if space.default { "house" } else { "layers" },
+ accessory: String::new(),
+ group: Group::Spaces,
+ terms: String::new(),
+ });
+ }
+ }
+ entries.extend(crate::palette::commands());
+ crate::palette::results(query, entries, &inner.recent)
+ }
+
+ /// The page's remembered picks, given back at boot.
+ pub fn set_recent(&self, ids: Vec<String>) {
+ self.inner.borrow_mut().recent = ids;
+ }
+
+ /// Do what a palette pick asks. `page` names what only the page can
+ /// do (its sidebar, its settings panel, remembering the language).
+ pub fn palette_run(self: &Rc<Self>, id: &str) -> crate::views::PaletteOutcome {
+ use crate::sidebar::SideClick;
+ let mut outcome = crate::views::PaletteOutcome { handled: true, page: None, recent: Vec::new() };
+ let (kind, arg) = id.split_once(':').unwrap_or((id, ""));
+ match (kind, arg) {
+ ("thread", id) => {
+ // A thread in another Space: the sidebar follows it there.
+ let space = self.inner.borrow().tree.project_of(id).map(|p| p.space_id.clone());
+ if let Some(space) = space {
+ self.set_space(&space);
+ }
+ self.activate_thread(id.to_string());
+ }
+ ("tab", id) => {
+ let target = id.parse().ok().and_then(|tab: TabId| {
+ let inner = self.inner.borrow();
+ Self::strip_model(&inner)?.0.into_iter().find(|t| t.tab_id == tab).map(|t| t.target)
+ });
+ match target {
+ Some(pane) => self.switch_to_pane(pane, true),
+ None => outcome.handled = false,
+ }
+ }
+ ("pane", id) => match id.parse() {
+ Ok(pane) => self.switch_to_pane(pane, true),
+ Err(_) => outcome.handled = false,
+ },
+ ("space", id) => outcome.handled = self.set_space(id),
+ ("cmd", "new-thread") => self.on_side_click(SideClick::NewThread(None)),
+ ("cmd", "new-tab") => self.new_tab(),
+ ("cmd", "split-right") => self.split(None, thinkterm_proto::SplitDirection::Horizontal),
+ ("cmd", "split-down") => self.split(None, thinkterm_proto::SplitDirection::Vertical),
+ ("cmd", "zoom") => self.toggle_zoom(None),
+ ("cmd", "close-pane") => self.close_pane(),
+ ("cmd", "take-over") => self.take_over(),
+ ("cmd", "follow") => self.on_chrome_click(crate::chrome::Click::Follow),
+ ("cmd", "toggle-sidebar") | ("cmd", "settings") => outcome.page = Some(arg.to_string()),
+ ("cmd", "font-up") => self.step_font(1.0),
+ ("cmd", "font-down") => self.step_font(-1.0),
+ ("cmd", "font-reset") => self.step_font(0.0),
+ _ => outcome.handled = false,
+ }
+ if outcome.handled {
+ let inner = &mut *self.inner.borrow_mut();
+ crate::palette::remember(&mut inner.recent, id);
+ outcome.recent = inner.recent.clone();
+ }
+ outcome
+ }
+
+ /// Show a Space in the sidebar; false when the server has no such Space.
+ pub fn set_space(&self, id: &str) -> bool {
+ let inner = &mut *self.inner.borrow_mut();
+ let known = inner.tree.set_space(id);
+ if known {
+ inner.editing = crate::sidebar::Editing::None;
+ Self::notify(inner);
+ }
+ known
+ }
+
+ /// Every pane of a tab, from the last listing.
+ fn tab_panes(inner: &Inner, tab: TabId) -> Vec<PaneId> {
+ inner
+ .layout
+ .as_ref()
+ .and_then(|l| l.tabs.iter().find(|t| t.window_and_tab_ids().is_some_and(|(_, id)| id == tab)))
+ .map(|node| crate::layout::leaves(node).iter().map(|e| e.pane_id).collect())
+ .unwrap_or_default()
+ }
+
+ /// Do what a menu row asks. Copy hands the selection back for the
+ /// page to put on the clipboard; Paste asks the page to read it.
+ pub fn menu_action(self: &Rc<Self>, id: &str) -> crate::views::MenuOutcome {
+ use crate::menu::{MenuAction, Side};
+ use crate::sidebar::SideClick;
+ let mut outcome = crate::views::MenuOutcome { handled: true, copy: None, paste: false };
+ let Some(action) = MenuAction::parse(id) else {
+ outcome.handled = false;
+ return outcome;
+ };
+ match action {
+ MenuAction::Copy => outcome.copy = Self::selection_text(&self.inner.borrow()),
+ MenuAction::Paste => outcome.paste = true,
+ MenuAction::Split { pane, side } => {
+ use thinkterm_proto::SplitDirection::{Horizontal, Vertical};
+ let (direction, second) = match side {
+ Side::Right => (Horizontal, true),
+ Side::Left => (Horizontal, false),
+ Side::Down => (Vertical, true),
+ Side::Up => (Vertical, false),
+ };
+ self.split_at(Some(pane), direction, second);
+ }
+ MenuAction::FrontendAccess(mode) => {
+ let (tab_id, viewport) = {
+ let inner = self.inner.borrow();
+ let viewport = inner.link.lease().claim_viewport();
+ (inner.tab_id, viewport)
+ };
+ match viewport {
+ Some(viewport) => self.act(
+ "web-act-set-access",
+ Pdu::SetFrontendAccessMode(codec::SetFrontendAccessMode { mode, tab_id, viewport }),
+ |_, _| {},
+ ),
+ None => outcome.handled = false,
+ }
+ }
+ MenuAction::CloseTabsLeft(tab) | MenuAction::CloseTabsRight(tab) | MenuAction::CloseOtherTabs(tab) => {
+ let panes: Vec<PaneId> = {
+ let inner = self.inner.borrow();
+ let tabs = Self::strip_model(&inner).map(|(t, _)| t).unwrap_or_default();
+ let at = tabs.iter().position(|t| t.tab_id == tab).unwrap_or(0);
+ tabs.iter()
+ .enumerate()
+ .filter(|(i, t)| match action {
+ MenuAction::CloseTabsLeft(_) => *i < at,
+ MenuAction::CloseTabsRight(_) => *i > at,
+ _ => t.tab_id != tab,
+ })
+ .flat_map(|(_, t)| Self::tab_panes(&inner, t.tab_id))
+ .collect()
+ };
+ self.kill_panes(panes);
+ }
+ MenuAction::NewTabRight => self.new_tab(),
+ MenuAction::Zoom(pane) => self.toggle_zoom(Some(pane)),
+ MenuAction::Pin(id, on) => self.on_side_click(SideClick::Pin(id, on)),
+ MenuAction::RenameThread(id) => self.on_side_click(SideClick::RenameThread(id)),
+ MenuAction::DeleteThread(id) => {
+ // The desktop's menu deletes at once; the two presses are
+ // the sidebar button's.
+ let panes = Self::thread_panes(&self.inner.borrow(), &id);
+ self.kill_panes(panes);
+ self.mutate(crate::tree::delete_thread(&id), |_| {});
+ }
+ MenuAction::MarkUnread(id) => self.mutate(crate::tree::set_unread(&id, true), |_| {}),
+ MenuAction::RenameProject(id) => self.on_side_click(SideClick::RenameProject(id)),
+ MenuAction::NewThread(id) => self.on_side_click(SideClick::NewThread(Some(id))),
+ MenuAction::ToggleCollapsed(id) => self.on_side_click(SideClick::ToggleProject(id)),
+ MenuAction::ArchiveProject(id) => self.on_side_click(SideClick::Archive(id)),
+ MenuAction::UnarchiveProject(id) => self.on_side_click(SideClick::Unarchive(id)),
+ MenuAction::RemoveProject(id) => {
+ let panes = self.inner.borrow().tree.live_panes_of_project(&id);
+ self.kill_panes(panes);
+ self.mutate(crate::tree::remove_project(&id), |_| {});
+ }
+ MenuAction::ShowArchived => self.on_side_click(SideClick::ToggleArchived),
+ MenuAction::SwitchSpace(id) => outcome.handled = self.set_space(&id),
+ MenuAction::NewSpace => {
+ let id = Self::new_id("space");
+ let count = self.inner.borrow().tree.spaces().len();
+ let name = format!("Space {}", count + 1);
+ let chosen = id.clone();
+ self.mutate(crate::tree::create_space(id, &name), move |app| {
+ app.set_space(&chosen);
+ });
+ }
+ MenuAction::RenameSpace(id) => {
+ let inner = &mut *self.inner.borrow_mut();
+ inner.editing = crate::sidebar::Editing::Space(id);
+ Self::notify(inner);
+ }
+ MenuAction::DeleteSpace(id) => {
+ let panes: Vec<PaneId> = {
+ let inner = self.inner.borrow();
+ inner
+ .tree
+ .session
+ .as_ref()
+ .map(|s| {
+ s.projects
+ .iter()
+ .filter(|p| p.space_id == id)
+ .flat_map(|p| inner.tree.live_panes_of_project(&p.id))
+ .collect()
+ })
+ .unwrap_or_default()
+ };
+ self.kill_panes(panes);
+ self.mutate(crate::tree::delete_space(&id), |app| {
+ let first = app.inner.borrow().tree.spaces().first().map(|s| s.id.clone());
+ if let Some(first) = first {
+ app.set_space(&first);
+ }
+ });
+ }
+ }
+ outcome
+ }
+
/// The pane a bar's button or a chord acts on: the bar's pane, which
/// the page focuses first as the desktop does, else the focused one.
fn target_pane(self: &Rc<Self>, pane: Option<PaneId>) -> PaneId {
@@ -2850,7 +3203,7 @@ impl App {
(inner.tab_id, zoomed)
};
self.act(
- "zoom the pane",
+ "web-act-zoom-pane",
Pdu::SetPaneZoomed(codec::SetPaneZoomed {
containing_tab_id: tab_id,
pane_id,
@@ -2864,7 +3217,7 @@ impl App {
pub fn close_pane(self: &Rc<Self>) {
let pane_id = self.inner.borrow().focused_pane;
self.act(
- "close the pane",
+ "web-act-close-pane",
Pdu::KillPane(codec::KillPane { pane_id }),
|_, _| {},
);
@@ -2921,7 +3274,7 @@ impl App {
}
Err(err) => {
let inner = app.inner.borrow();
- Self::set_status(&inner, &format!("could not resize the tab: {err:#}"));
+ Self::set_status(&inner, &failed("web-act-resize-tab", &err));
}
}
});
@@ -2932,7 +3285,7 @@ impl App {
pub fn take_over(self: &Rc<Self>) {
let (link, tab_id) = {
let inner = self.inner.borrow();
- Self::set_status(&inner, "taking the terminal over…");
+ Self::set_status(&inner, &tr("web-toast-taking-over"));
// Taken by an interaction here: at this page's own shape.
inner.link.lease_mut().fit = true;
(inner.link.clone(), inner.tab_id)
@@ -2948,13 +3301,13 @@ impl App {
Ok(false) => {
let mut inner = app.inner.borrow_mut();
inner.after_take_over = None;
- Self::set_status(&inner, "the server did not hand the terminal over");
+ Self::set_status(&inner, &tr("web-toast-not-handed-over"));
None
}
Err(err) => {
let mut inner = app.inner.borrow_mut();
inner.after_take_over = None;
- Self::set_status(&inner, &format!("could not take over: {err:#}"));
+ Self::set_status(&inner, &failed("web-act-take-over", &err));
None
}
};
@@ -3134,7 +3487,7 @@ impl App {
);
}
Err(err) => {
- Self::set_status(&inner, &format!("could not size the font: {err:#}"));
+ Self::set_status(&inner, &failed("web-act-size-font", &err));
return;
}
}
@@ -3265,7 +3618,7 @@ impl App {
inner.cols = cols;
inner.rows = rows;
// The bars are placed from the cell size, which may just have moved.
- Self::render_navs(&inner);
+ Self::notify(&inner);
if changed {
// The page's grid is its own business: the tab keeps the
// desktop's size and this canvas letterboxes it. Only a page
diff --git a/thinkterm-web/src/bridge.rs b/thinkterm-web/src/bridge.rs
new file mode 100644
index 00000000..3a164b8d
--- /dev/null
+++ b/thinkterm-web/src/bridge.rs
@@ -0,0 +1,201 @@
+//! The handle the page holds: what the chrome shows, as JSON (`views`),
+//! and the few things it can ask for. The display layer is not told what
+//! changed, only that something did; it reads the views it draws.
+
+use crate::app::App;
+use std::rc::Rc;
+use wasm_bindgen::prelude::*;
+
+#[wasm_bindgen]
+pub struct Client {
+ app: Rc<App>,
+}
+
+impl Client {
+ pub(crate) fn new(app: Rc<App>) -> Self {
+ Self { app }
+ }
+}
+
+fn json<T: serde::Serialize>(value: &T) -> String {
+ serde_json::to_string(value).unwrap_or_else(|err| format!("{{\"error\":{:?}}}", err.to_string()))
+}
+
+#[wasm_bindgen]
+impl Client {
+ /// Called once right away, then once per task in which any view
+ /// changed.
+ pub fn on_change(&self, callback: js_sys::Function) {
+ self.app.set_on_change(callback);
+ }
+
+ pub fn sidebar(&self) -> String {
+ json(&self.app.sidebar_view())
+ }
+
+ pub fn tabs(&self) -> String {
+ json(&self.app.tabs_view())
+ }
+
+ pub fn navs(&self) -> String {
+ json(&self.app.navs_view())
+ }
+
+ pub fn status(&self) -> String {
+ json(&self.app.status_view())
+ }
+
+ pub fn layout(&self) -> String {
+ self.app.layout_view()
+ }
+
+ /// The page's own labels in the active locale, keyed by catalogue id.
+ pub fn strings(&self) -> String {
+ json(&crate::views::strings())
+ }
+
+ /// Switch the language: a preference (`"system"` or a tag) and the
+ /// browser's own list. Returns the locale it resolved to.
+ pub fn set_locale(&self, preference: String, languages: Vec<String>) -> String {
+ let code = thinkterm_i18n::activate_preference(&preference, &languages);
+ self.app.locale_changed();
+ code.to_string()
+ }
+
+ /// A click in the sidebar: `kind` names the row or button, `id` the
+ /// thread, project or window it is about, `flag` the pin state.
+ /// Returns false for a kind the model does not know.
+ pub fn side_click(&self, kind: String, id: Option<String>, flag: Option<bool>) -> bool {
+ use crate::sidebar::SideClick;
+ let click = match (kind.as_str(), id) {
+ ("thread", Some(id)) => SideClick::Thread(id),
+ ("window", Some(id)) => match id.parse() {
+ Ok(w) => SideClick::Window(w),
+ Err(_) => return false,
+ },
+ ("toggle-project", Some(id)) => SideClick::ToggleProject(id),
+ ("toggle-archived", _) => SideClick::ToggleArchived,
+ ("new-thread", project) => SideClick::NewThread(project),
+ ("new-project", _) => SideClick::NewProject,
+ ("pin", Some(id)) => SideClick::Pin(id, flag.unwrap_or(true)),
+ ("delete", Some(id)) => SideClick::Delete(id),
+ ("rename-thread", Some(id)) => SideClick::RenameThread(id),
+ ("rename-project", Some(id)) => SideClick::RenameProject(id),
+ ("archive", Some(id)) => SideClick::Archive(id),
+ ("unarchive", Some(id)) => SideClick::Unarchive(id),
+ ("space-menu", _) => SideClick::SpaceMenu,
+ _ => return false,
+ };
+ self.app.on_side_click(click);
+ true
+ }
+
+ /// The context menu for `kind` ("pane", "tab", "thread", "project",
+ /// "archived-project", "sidebar-options") and `id`: JSON `MenuItem[]`.
+ pub fn context_menu(&self, kind: String, id: String) -> String {
+ json(&self.app.context_menu(&kind, &id))
+ }
+
+ /// Perform a menu row's action by its id: JSON `MenuOutcome`.
+ pub fn menu_action(&self, id: String) -> String {
+ json(&self.app.menu_action(&id))
+ }
+
+ /// The Agents panel: JSON `AgentsView`.
+ pub fn agents(&self) -> String {
+ json(&self.app.agents_view())
+ }
+
+ /// Bring an agent's pane on show.
+ pub fn agent_reveal(&self, pane: u32) -> bool {
+ self.app.agent_reveal(pane as usize)
+ }
+
+ /// The languages the page can be set to: JSON `[{preference, label}]`,
+ /// "system" first, labelled in the active locale.
+ pub fn languages(&self) -> String {
+ let list: Vec<serde_json::Value> = thinkterm_i18n::LANGUAGE_OPTIONS
+ .iter()
+ .map(|o| serde_json::json!({ "preference": o.preference, "label": thinkterm_i18n::language_option_label(*o) }))
+ .collect();
+ json(&list)
+ }
+
+ /// The page's preferences as the model holds them: JSON `WebSettings`.
+ pub fn settings(&self) -> String {
+ json(&self.app.settings_view())
+ }
+
+ /// The stored preferences, whole, at boot. Returns an error text or "".
+ pub fn apply_settings(&self, json: String) -> String {
+ self.app.apply_settings(&json).err().unwrap_or_default()
+ }
+
+ /// One preference (`key` as in the JSON, `value` as JSON). Returns an
+ /// error text or "".
+ pub fn set_setting(&self, key: String, value: String) -> String {
+ self.app.set_setting(&key, &value).err().unwrap_or_default()
+ }
+
+ /// The search palette's entries for `query`, ranked: JSON `Results`.
+ pub fn palette(&self, query: String) -> String {
+ json(&self.app.palette(&query))
+ }
+
+ /// Perform a palette pick by its entry id: JSON `PaletteOutcome`.
+ pub fn palette_run(&self, id: String) -> String {
+ json(&self.app.palette_run(&id))
+ }
+
+ /// The page's remembered picks (most recent first), at boot.
+ pub fn set_recent(&self, ids: Vec<String>) {
+ self.app.set_recent(ids);
+ }
+
+ /// Show a Space in the sidebar (the page remembers the last one).
+ pub fn set_space(&self, id: String) -> bool {
+ self.app.set_space(&id)
+ }
+
+ /// A key the page pressed for the user (its key bar on a phone), by
+ /// its DOM name ("Escape", "ArrowUp", "c"), with modifiers. Returns
+ /// whether the terminal took it.
+ pub fn key(&self, name: String, ctrl: bool, alt: bool, shift: bool) -> bool {
+ let dom = crate::keymap::DomKey { key: &name, code: "", ctrl, alt, shift, meta: false, composing: false };
+ match crate::keymap::map_key(&dom) {
+ Some((key, mods)) => self.app.key_down(key, mods, shift),
+ None => false,
+ }
+ }
+
+ /// Text from the page's clipboard, typed into the focused pane.
+ pub fn paste(&self, text: String) {
+ self.app.paste(&text);
+ }
+
+ /// Enter or Escape in the sidebar's inline input, with its value.
+ pub fn side_key(&self, key: String, value: String) {
+ self.app.on_side_key(&key, value);
+ }
+
+ /// A click on the tab row or a pane's bar. Returns false for an
+ /// action the model does not know.
+ pub fn chrome_click(&self, action: String, pane: Option<u32>, tab: Option<u32>) -> bool {
+ use crate::chrome::Click;
+ let pane = pane.map(|p| p as usize);
+ let click = match (action.as_str(), pane, tab) {
+ ("pane", Some(p), _) => Click::Pane(p),
+ ("follow", _, _) => Click::Follow,
+ ("new-tab", _, _) => Click::NewTab,
+ ("split-right", p, _) => Click::SplitRight(p),
+ ("split-below", p, _) => Click::SplitBelow(p),
+ ("zoom", p, _) => Click::Zoom(p),
+ ("close", _, _) => Click::Close,
+ ("close-pane", Some(p), _) => Click::ClosePane(p),
+ ("close-tab", _, Some(t)) => Click::CloseTab(t as usize),
+ _ => return false,
+ };
+ self.app.on_chrome_click(click);
+ true
+ }
+}
diff --git a/thinkterm-web/src/canvas.rs b/thinkterm-web/src/canvas.rs
index 5c042a97..3dfcb076 100644
--- a/thinkterm-web/src/canvas.rs
+++ b/thinkterm-web/src/canvas.rs
@@ -25,7 +25,7 @@ pub const MAX_FALLBACK_CELLS: u8 = 4;
/// The fonts the canvas draws with, in CSS order.
///
/// The page gives the terminal no font stack of its own -- `#term` is a
-/// bare canvas, and the two names in `app.js` identify the files we parse
+/// bare canvas, and the two names in `ui/src/main.ts` identify the files we parse
/// ourselves, not CSS families -- so this is it, and `?glyphfont=`
/// replaces it.
///
diff --git a/thinkterm-web/src/chrome.rs b/thinkterm-web/src/chrome.rs
index 0a6d2d1c..2f8cd82a 100644
--- a/thinkterm-web/src/chrome.rs
+++ b/thinkterm-web/src/chrome.rs
@@ -12,11 +12,16 @@ use thinkterm_proto::layout::{PaneEntry, PaneNode};
use thinkterm_proto::{PaneId, TabId, WindowId};
/// One tab in the strip.
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct TabView {
+ #[serde(rename = "tab")]
pub tab_id: TabId,
+ #[serde(rename = "window")]
pub window_id: WindowId,
+ /// The tab's title as the server has it: the tooltip.
pub title: String,
+ /// What the capsule says: the desktop's title rule applied.
+ pub label: String,
/// The pane a click on the tab shows: the one on show if it is in
/// this tab, else the tab's active pane.
pub target: PaneId,
@@ -26,8 +31,9 @@ pub struct TabView {
pub panes: Vec<PaneView>,
}
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct PaneView {
+ #[serde(rename = "pane")]
pub pane_id: PaneId,
pub title: String,
pub current: bool,
@@ -35,6 +41,19 @@ pub struct PaneView {
pub use crate::layout::leaves;
+/// The state the strip shows besides its tabs.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize)]
+pub struct Controls {
+ pub following: bool,
+ pub fit: bool,
+ /// The tab whose close button was pressed once and waits for the
+ /// press that means it.
+ #[serde(rename = "closing")]
+ pub closing_tab: Option<TabId>,
+ /// The page shows less than the tab: the grid it fits.
+ pub clipped: Option<(usize, usize)>,
+}
+
/// The pane a tab is showing: its active one, or the first.
pub fn active_pane(node: &PaneNode) -> Option<PaneEntry> {
match node {
@@ -122,6 +141,7 @@ pub fn model(
tabs.push(TabView {
tab_id: first.tab_id,
window_id: first.window_id,
+ label: crate::navbar::display_title(&title).0,
title,
target,
current: is_current,
@@ -131,170 +151,24 @@ pub fn model(
tabs
}
-#[cfg(target_arch = "wasm32")]
-mod dom {
- use super::TabView;
- use thinkterm_proto::{PaneId, TabId};
- use wasm_bindgen::JsCast;
-
- /// The strip's element and what it draws into it.
- pub struct TabStrip {
- root: web_sys::Element,
- }
-
- /// What a click on the strip meant.
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- pub enum Click {
- Pane(PaneId),
- Follow,
- NewTab,
- /// The bar's pane, or the focused one from a chord.
- SplitRight(Option<PaneId>),
- SplitBelow(Option<PaneId>),
- Zoom(Option<PaneId>),
- /// The focused pane's close button (a chord, or a bar).
- Close,
- /// A capsule's own close button.
- ClosePane(PaneId),
- /// A tab's close button: every pane of it.
- CloseTab(TabId),
- /// The sidebar toggle at the row's start.
- Sidebar,
- }
-
- /// The state the strip shows.
- #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
- pub struct Controls {
- pub following: bool,
- pub fit: bool,
- /// The tab whose close button was pressed once and waits for the
- /// press that means it.
- pub closing_tab: Option<TabId>,
- /// The page shows less than the tab: the grid it fits.
- pub clipped: Option<(usize, usize)>,
- }
-
- fn escape(text: &str) -> String {
- let mut out = String::with_capacity(text.len());
- for c in text.chars() {
- match c {
- '&' => out.push_str("&amp;"),
- '<' => out.push_str("&lt;"),
- '>' => out.push_str("&gt;"),
- '"' => out.push_str("&quot;"),
- c => out.push(c),
- }
- }
- out
- }
-
- /// Titles are shown short; the full one is the tooltip.
- fn short(title: &str) -> String {
- const MAX: usize = 28;
- if title.chars().count() <= MAX {
- title.to_string()
- } else {
- let head: String = title.chars().take(MAX - 1).collect();
- format!("{head}…")
- }
- }
-
- impl TabStrip {
- pub fn mount(id: &str) -> Option<Self> {
- let root = web_sys::window()?.document()?.get_element_by_id(id)?;
- Some(Self { root })
- }
-
- pub fn element(&self) -> &web_sys::Element {
- &self.root
- }
-
- /// Redraw the whole strip. It is a few dozen elements; rebuilding
- /// them is cheaper to get right than diffing them.
- pub fn render(&self, tabs: &[TabView], controls: Controls) {
- let following = controls.following;
- let icon = crate::icons::svg;
- let mut html = format!(
- "<span class=\"act\" data-action=\"sidebar\" title=\"Show or hide the sidebar\">{}</span>",
- icon("panel-left")
- );
- for tab in tabs {
- let class = if tab.current { "tab current" } else { "tab" };
- let (title, _) = crate::navbar::display_title(&tab.title);
- let (close_class, close_body) = if controls.closing_tab == Some(tab.tab_id) {
- ("x danger", "close?")
- } else {
- ("x", icon("x"))
- };
- html.push_str(&format!(
- "<span class=\"{class}\" data-pane=\"{}\" title=\"{}\">{}<span class=\"t\">{}</span><span class=\"{close_class}\" data-action=\"close-tab\" data-tab=\"{}\" title=\"Close this tab and end its programs. Asks twice.\">{close_body}</span></span>",
- tab.target,
- escape(&tab.title),
- icon("square-terminal"),
- escape(&short(title)),
- tab.tab_id
- ));
- }
- let (class, text, hint) = if following {
- (
- "follow on",
- "following the desktop",
- "This page shows whichever pane the desktop focuses. Click to stay on this one.",
- )
- } else {
- (
- "follow off",
- "staying here",
- "This page stays on this pane. Click to follow the desktop's focus again.",
- )
- };
- html.push_str(&format!(
- "<span class=\"act\" data-action=\"new-tab\" title=\"New tab\">{}</span>",
- icon("plus")
- ));
- if controls.fit {
- html.push_str(
- "<span class=\"trail\"><span class=\"hint\" title=\"The tab is fitted to this window; Ctrl+Shift+F gives the size back\">fitted</span></span>",
- );
- }
- let _ = (following, class, text, hint);
- self.root.set_inner_html(&html);
- }
-
- /// What a click landed on, if anything the strip owns.
- pub fn click_target(ev: &web_sys::MouseEvent) -> Option<Click> {
- let target: web_sys::Element = ev.target()?.dyn_into().ok()?;
- let hit = target.closest("[data-pane],[data-follow],[data-action]").ok()??;
- if hit.has_attribute("data-follow") {
- return Some(Click::Follow);
- }
- if let Some(action) = hit.get_attribute("data-action") {
- // A bar's buttons act on the bar's pane, whichever is focused.
- let bar = hit
- .closest("[data-nav]")
- .ok()
- .flatten()
- .and_then(|nav| nav.get_attribute("data-nav")?.parse::<PaneId>().ok());
- return match action.as_str() {
- "new-tab" => Some(Click::NewTab),
- "split-right" => Some(Click::SplitRight(bar)),
- "split-below" => Some(Click::SplitBelow(bar)),
- "zoom" => Some(Click::Zoom(bar)),
- "close" => Some(Click::Close),
- "close-pane" => hit.get_attribute("data-pane")?.parse().ok().map(Click::ClosePane),
- "close-tab" => hit.get_attribute("data-tab")?.parse().ok().map(Click::CloseTab),
- "sidebar" => Some(Click::Sidebar),
- _ => None,
- };
- }
- hit.get_attribute("data-pane")?.parse().ok().map(Click::Pane)
- }
- }
+/// What a click on the tab row or a pane's bar meant.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Click {
+ Pane(PaneId),
+ Follow,
+ NewTab,
+ /// The bar's pane, or the focused one from a chord.
+ SplitRight(Option<PaneId>),
+ SplitBelow(Option<PaneId>),
+ Zoom(Option<PaneId>),
+ /// The focused pane's close button (a chord, or a bar).
+ Close,
+ /// A capsule's own close button.
+ ClosePane(PaneId),
+ /// A tab's close button: every pane of it.
+ CloseTab(TabId),
}
-#[cfg(target_arch = "wasm32")]
-pub use dom::{Click, Controls, TabStrip};
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/thinkterm-web/src/lib.rs b/thinkterm-web/src/lib.rs
index d5457eee..a9bea2dd 100644
--- a/thinkterm-web/src/lib.rs
+++ b/thinkterm-web/src/lib.rs
@@ -3,6 +3,7 @@
//! `braille`, `fallback`, `keymap`, `lease` and `viewport` are pure and
//! build everywhere; everything that touches the page is `wasm32` only.
+pub mod agents;
pub mod braille;
pub mod chrome;
pub mod fallback;
@@ -11,16 +12,22 @@ pub mod keymap;
pub mod icons;
pub mod layout;
pub mod lease;
+pub mod menu;
pub mod navbar;
+pub mod palette;
+pub mod settings;
pub mod sidebar;
pub mod tree;
pub mod viewport;
+pub mod views;
#[cfg(target_arch = "wasm32")]
mod app;
#[cfg(target_arch = "wasm32")]
mod attach;
#[cfg(target_arch = "wasm32")]
+mod bridge;
+#[cfg(target_arch = "wasm32")]
mod canvas;
#[cfg(target_arch = "wasm32")]
mod emit;
@@ -39,5 +46,7 @@ mod link;
#[cfg(target_arch = "wasm32")]
mod page;
+#[cfg(target_arch = "wasm32")]
+pub use bridge::Client;
#[cfg(target_arch = "wasm32")]
pub use page::{color_check, start};
diff --git a/thinkterm-web/src/menu.rs b/thinkterm-web/src/menu.rs
new file mode 100644
index 00000000..980397bf
--- /dev/null
+++ b/thinkterm-web/src/menu.rs
@@ -0,0 +1,486 @@
+//! The context menus as data: the desktop's lists (`mouseevent.rs`
+//! `*_context_menu_items`) rebuilt from the model, with their conditions,
+//! for a display layer to draw and hand back an action id. Nothing here
+//! knows how a menu looks; everything about what it offers is here.
+
+use crate::tree::{SpaceEntry, ThreadRow};
+use codec::FrontendAccessMode;
+use serde::Serialize;
+use thinkterm_i18n::{tr, tr_args, FluentArgs};
+use thinkterm_proto::{PaneId, TabId};
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct MenuItem {
+ /// The action this row performs (`MenuAction::id`); empty for a
+ /// header, a separator or a row that only opens a submenu.
+ pub id: String,
+ pub label: String,
+ /// A lucide icon name, when the row has one.
+ pub icon: Option<&'static str>,
+ pub kind: Kind,
+ pub enabled: bool,
+ pub checked: bool,
+ pub submenu: Vec<MenuItem>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum Kind {
+ Item,
+ Header,
+ Separator,
+}
+
+impl MenuItem {
+ fn item(action: MenuAction, label: String, icon: Option<&'static str>) -> Self {
+ Self { id: action.id(), label, icon, kind: Kind::Item, enabled: true, checked: false, submenu: Vec::new() }
+ }
+
+ fn submenu(label: String, icon: Option<&'static str>, items: Vec<MenuItem>) -> Self {
+ Self { id: String::new(), label, icon, kind: Kind::Item, enabled: true, checked: false, submenu: items }
+ }
+
+ fn header(label: String) -> Self {
+ Self { id: String::new(), label, icon: None, kind: Kind::Header, enabled: false, checked: false, submenu: Vec::new() }
+ }
+
+ fn separator() -> Self {
+ Self { id: String::new(), label: String::new(), icon: None, kind: Kind::Separator, enabled: false, checked: false, submenu: Vec::new() }
+ }
+
+ fn checked(mut self, checked: bool) -> Self {
+ self.checked = checked;
+ self
+ }
+}
+
+/// What a menu row does. The id is the wire form (`"split:right:12"`),
+/// parsed back when the display layer hands it in.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum MenuAction {
+ Copy,
+ Paste,
+ Split { pane: PaneId, side: Side },
+ FrontendAccess(FrontendAccessMode),
+ CloseTabsLeft(TabId),
+ CloseTabsRight(TabId),
+ CloseOtherTabs(TabId),
+ NewTabRight,
+ Zoom(PaneId),
+ Pin(String, bool),
+ RenameThread(String),
+ DeleteThread(String),
+ MarkUnread(String),
+ RenameProject(String),
+ NewThread(String),
+ ToggleCollapsed(String),
+ ArchiveProject(String),
+ RemoveProject(String),
+ UnarchiveProject(String),
+ ShowArchived,
+ SwitchSpace(String),
+ NewSpace,
+ RenameSpace(String),
+ DeleteSpace(String),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Side {
+ Right,
+ Left,
+ Down,
+ Up,
+}
+
+impl MenuAction {
+ pub fn id(&self) -> String {
+ match self {
+ MenuAction::Copy => "copy".into(),
+ MenuAction::Paste => "paste".into(),
+ MenuAction::Split { pane, side } => {
+ let side = match side {
+ Side::Right => "right",
+ Side::Left => "left",
+ Side::Down => "down",
+ Side::Up => "up",
+ };
+ format!("split:{side}:{pane}")
+ }
+ MenuAction::FrontendAccess(FrontendAccessMode::TmuxLatest) => "access:shared".into(),
+ MenuAction::FrontendAccess(FrontendAccessMode::Handoff) => "access:handoff".into(),
+ MenuAction::CloseTabsLeft(t) => format!("close-tabs-left:{t}"),
+ MenuAction::CloseTabsRight(t) => format!("close-tabs-right:{t}"),
+ MenuAction::CloseOtherTabs(t) => format!("close-other-tabs:{t}"),
+ MenuAction::NewTabRight => "new-tab-right".into(),
+ MenuAction::Zoom(p) => format!("zoom:{p}"),
+ MenuAction::Pin(id, true) => format!("pin:{id}"),
+ MenuAction::Pin(id, false) => format!("unpin:{id}"),
+ MenuAction::RenameThread(id) => format!("rename-thread:{id}"),
+ MenuAction::DeleteThread(id) => format!("delete-thread:{id}"),
+ MenuAction::MarkUnread(id) => format!("unread:{id}"),
+ MenuAction::RenameProject(id) => format!("rename-project:{id}"),
+ MenuAction::NewThread(id) => format!("new-thread:{id}"),
+ MenuAction::ToggleCollapsed(id) => format!("collapse:{id}"),
+ MenuAction::ArchiveProject(id) => format!("archive:{id}"),
+ MenuAction::RemoveProject(id) => format!("remove-project:{id}"),
+ MenuAction::UnarchiveProject(id) => format!("unarchive:{id}"),
+ MenuAction::ShowArchived => "show-archived".into(),
+ MenuAction::SwitchSpace(id) => format!("space:{id}"),
+ MenuAction::NewSpace => "new-space".into(),
+ MenuAction::RenameSpace(id) => format!("rename-space:{id}"),
+ MenuAction::DeleteSpace(id) => format!("delete-space:{id}"),
+ }
+ }
+
+ pub fn parse(id: &str) -> Option<Self> {
+ let mut parts = id.splitn(3, ':');
+ let verb = parts.next()?;
+ let arg = parts.next();
+ let rest = parts.next();
+ let num = |s: Option<&str>| s.and_then(|s| s.parse::<usize>().ok());
+ let text = |s: Option<&str>| s.filter(|s| !s.is_empty()).map(str::to_string);
+ Some(match verb {
+ "copy" => MenuAction::Copy,
+ "paste" => MenuAction::Paste,
+ "split" => {
+ let side = match arg? {
+ "right" => Side::Right,
+ "left" => Side::Left,
+ "down" => Side::Down,
+ "up" => Side::Up,
+ _ => return None,
+ };
+ MenuAction::Split { pane: num(rest)?, side }
+ }
+ "access" => MenuAction::FrontendAccess(match arg? {
+ "shared" => FrontendAccessMode::TmuxLatest,
+ "handoff" => FrontendAccessMode::Handoff,
+ _ => return None,
+ }),
+ "close-tabs-left" => MenuAction::CloseTabsLeft(num(arg)?),
+ "close-tabs-right" => MenuAction::CloseTabsRight(num(arg)?),
+ "close-other-tabs" => MenuAction::CloseOtherTabs(num(arg)?),
+ "new-tab-right" => MenuAction::NewTabRight,
+ "zoom" => MenuAction::Zoom(num(arg)?),
+ "pin" => MenuAction::Pin(text(arg)?, true),
+ "unpin" => MenuAction::Pin(text(arg)?, false),
+ "rename-thread" => MenuAction::RenameThread(text(arg)?),
+ "delete-thread" => MenuAction::DeleteThread(text(arg)?),
+ "unread" => MenuAction::MarkUnread(text(arg)?),
+ "rename-project" => MenuAction::RenameProject(text(arg)?),
+ "new-thread" => MenuAction::NewThread(text(arg)?),
+ "collapse" => MenuAction::ToggleCollapsed(text(arg)?),
+ "archive" => MenuAction::ArchiveProject(text(arg)?),
+ "remove-project" => MenuAction::RemoveProject(text(arg)?),
+ "unarchive" => MenuAction::UnarchiveProject(text(arg)?),
+ "show-archived" => MenuAction::ShowArchived,
+ "space" => MenuAction::SwitchSpace(text(arg)?),
+ "new-space" => MenuAction::NewSpace,
+ "rename-space" => MenuAction::RenameSpace(text(arg)?),
+ "delete-space" => MenuAction::DeleteSpace(text(arg)?),
+ _ => return None,
+ })
+ }
+}
+
+/// The terminal pane's menu (`terminal_context_menu_items`): copy and
+/// paste, the four splits, and the frontend access mode with the
+/// current one checked. Reset Terminal has no PDU and is left out.
+pub fn for_pane(pane: PaneId, access: Option<FrontendAccessMode>) -> Vec<MenuItem> {
+ let mut items = vec![
+ MenuItem::item(MenuAction::Copy, tr("menu-copy"), Some("copy")),
+ MenuItem::item(MenuAction::Paste, tr("menu-paste"), Some("clipboard-paste")),
+ MenuItem::separator(),
+ MenuItem::item(MenuAction::Split { pane, side: Side::Right }, tr("menu-split-right"), Some("square-split-horizontal")),
+ MenuItem::item(MenuAction::Split { pane, side: Side::Left }, tr("menu-split-left"), Some("square-split-horizontal")),
+ MenuItem::item(MenuAction::Split { pane, side: Side::Down }, tr("menu-split-down"), Some("square-split-vertical")),
+ MenuItem::item(MenuAction::Split { pane, side: Side::Up }, tr("menu-split-up"), Some("square-split-vertical")),
+ MenuItem::separator(),
+ ];
+ let mode = |m: FrontendAccessMode, key: &str| {
+ let current = access == Some(m);
+ MenuItem::item(MenuAction::FrontendAccess(m), tr(key), Some(if current { "check" } else { "square-terminal" }))
+ .checked(current)
+ };
+ items.push(MenuItem::submenu(
+ tr("web-menu-frontend-access"),
+ None,
+ vec![
+ mode(FrontendAccessMode::TmuxLatest, "web-menu-access-shared"),
+ mode(FrontendAccessMode::Handoff, "web-menu-access-handoff"),
+ ],
+ ));
+ items
+}
+
+/// A tab's menu (`tab_context_menu_items`) for the tab at `index` of
+/// `count` in its window, showing `active_pane`. Rename and Move need
+/// PDUs the server does not have and are left out.
+pub fn for_tab(tab: TabId, index: usize, count: usize, active_pane: PaneId) -> Vec<MenuItem> {
+ let mut items = Vec::new();
+ let mut close = Vec::new();
+ if index > 0 {
+ close.push(MenuItem::item(MenuAction::CloseTabsLeft(tab), tr("menu-close-tabs-left"), Some("x")));
+ }
+ if index + 1 < count {
+ close.push(MenuItem::item(MenuAction::CloseTabsRight(tab), tr("menu-close-tabs-right"), Some("x")));
+ }
+ if count > 1 {
+ close.push(MenuItem::item(MenuAction::CloseOtherTabs(tab), tr("menu-close-other-tabs"), Some("x")));
+ }
+ if !close.is_empty() {
+ items.extend(close);
+ items.push(MenuItem::separator());
+ }
+ items.push(MenuItem::item(MenuAction::NewTabRight, tr("menu-new-terminal-tab-right"), Some("plus")));
+ items.push(MenuItem::separator());
+ items.push(MenuItem::item(MenuAction::Zoom(active_pane), tr("menu-zoom-pane"), Some("maximize-2")));
+ items
+}
+
+/// A thread row's menu (`workspace_thread_context_menu_items`, the
+/// non-ref branch): pin, rename, delete, mark unread.
+pub fn for_thread(thread: &ThreadRow) -> Vec<MenuItem> {
+ let id = &thread.id;
+ vec![
+ if thread.pinned {
+ MenuItem::item(MenuAction::Pin(id.clone(), false), tr("menu-unpin-thread"), Some("pin-off"))
+ } else {
+ MenuItem::item(MenuAction::Pin(id.clone(), true), tr("menu-pin-thread"), Some("pin"))
+ },
+ MenuItem::item(MenuAction::RenameThread(id.clone()), tr("menu-rename-thread"), Some("pencil")),
+ MenuItem::item(MenuAction::DeleteThread(id.clone()), tr("menu-delete-thread"), Some("trash-2")),
+ MenuItem::item(MenuAction::MarkUnread(id.clone()), tr("menu-mark-unread"), Some("mail")),
+ ]
+}
+
+/// A project row's menu (`project_context_menu_items`): rename, new
+/// thread, collapse, then archive -- flat when nothing runs, a submenu
+/// that says what it closes otherwise -- and remove.
+pub fn for_project(id: &str, live_panes: usize) -> Vec<MenuItem> {
+ let mut items = vec![
+ MenuItem::item(MenuAction::RenameProject(id.into()), tr("menu-rename-project"), Some("pencil")),
+ MenuItem::item(MenuAction::NewThread(id.into()), tr("menu-new-thread"), Some("plus")),
+ MenuItem::item(MenuAction::ToggleCollapsed(id.into()), tr("menu-toggle-threads"), Some("chevron-down")),
+ MenuItem::separator(),
+ ];
+ if live_panes == 0 {
+ items.push(MenuItem::item(MenuAction::ArchiveProject(id.into()), tr("menu-archive-project-quiet"), Some("archive")));
+ } else {
+ let mut args = FluentArgs::new();
+ args.set("panes", live_panes as i64);
+ items.push(MenuItem::submenu(
+ tr("menu-archive-project"),
+ Some("archive"),
+ vec![
+ MenuItem::header(tr_args("menu-archive-project-explain", &args)),
+ MenuItem::item(MenuAction::ArchiveProject(id.into()), tr("menu-archive-project-confirm"), Some("archive")),
+ ],
+ ));
+ }
+ items.push(MenuItem::item(MenuAction::RemoveProject(id.into()), tr("menu-remove-project"), Some("trash-2")));
+ items
+}
+
+/// An archived project's menu (`archived_project_context_menu_items`).
+pub fn for_archived_project(id: &str, threads: usize) -> Vec<MenuItem> {
+ let mut args = FluentArgs::new();
+ args.set("threads", threads as i64);
+ vec![
+ MenuItem::item(MenuAction::UnarchiveProject(id.into()), tr("menu-unarchive-project"), Some("archive-restore")),
+ MenuItem::separator(),
+ MenuItem::submenu(
+ tr("menu-delete-project-permanently"),
+ Some("trash-2"),
+ vec![
+ MenuItem::header(tr_args("menu-delete-project-permanently-explain", &args)),
+ MenuItem::item(MenuAction::RemoveProject(id.into()), tr("menu-delete-project-permanently-confirm"), Some("trash-2")),
+ ],
+ ),
+ ]
+}
+
+/// The Space menu (`space_menu_items`, the local part): every Space with
+/// the current one checked, New Space, Rename, and Delete for a Space
+/// that is not the last one.
+pub fn for_space(spaces: &[SpaceEntry]) -> Vec<MenuItem> {
+ let mut items: Vec<MenuItem> = spaces
+ .iter()
+ .map(|s| {
+ MenuItem::item(
+ MenuAction::SwitchSpace(s.id.clone()),
+ s.name.clone(),
+ Some(if s.default { "house" } else { "layers" }),
+ )
+ .checked(s.current)
+ })
+ .collect();
+ items.push(MenuItem::separator());
+ items.push(MenuItem::item(MenuAction::NewSpace, tr("menu-new-space"), Some("plus")));
+ if let Some(current) = spaces.iter().find(|s| s.current) {
+ let mut args = FluentArgs::new();
+ args.set("name", current.name.as_str());
+ items.push(MenuItem::item(
+ MenuAction::RenameSpace(current.id.clone()),
+ tr_args("menu-rename-named-space", &args),
+ Some("pencil"),
+ ));
+ if spaces.len() > 1 {
+ items.push(MenuItem::item(
+ MenuAction::DeleteSpace(current.id.clone()),
+ tr_args("menu-delete-space", &args),
+ Some("trash-2"),
+ ));
+ }
+ }
+ items
+}
+
+/// The bell's menu: the desktop lists pending work notifications, one row
+/// per thread; the page has none yet, so it is the desktop's empty state.
+pub fn for_notifications() -> Vec<MenuItem> {
+ let mut item = MenuItem::header(tr("menu-no-notifications"));
+ item.kind = Kind::Item;
+ vec![item]
+}
+
+/// The sidebar's view options: what the page has of the desktop's
+/// (`workspace_sidebar_view_options_menu_items`) -- the archived group.
+pub fn for_sidebar_options(show_archived: bool, archived: usize) -> Vec<MenuItem> {
+ let label = if archived > 0 {
+ let mut args = FluentArgs::new();
+ args.set("count", archived as i64);
+ tr_args("menu-show-archived-count", &args)
+ } else {
+ tr("menu-show-archived")
+ };
+ let mut item = MenuItem::item(MenuAction::ShowArchived, label, Some("archive")).checked(show_archived);
+ item.enabled = archived > 0 || show_archived;
+ vec![item]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::tree::{Dot, Status};
+
+ fn labels(items: &[MenuItem]) -> Vec<String> {
+ items
+ .iter()
+ .map(|i| match i.kind {
+ Kind::Separator => "—".into(),
+ Kind::Header => format!("# {}", i.label),
+ Kind::Item if !i.submenu.is_empty() => format!("{} ▸", i.label),
+ Kind::Item => i.label.clone(),
+ })
+ .collect()
+ }
+
+ #[test]
+ fn every_action_survives_its_id() {
+ let all = vec![
+ MenuAction::Copy,
+ MenuAction::Paste,
+ MenuAction::Split { pane: 12, side: Side::Up },
+ MenuAction::FrontendAccess(FrontendAccessMode::TmuxLatest),
+ MenuAction::FrontendAccess(FrontendAccessMode::Handoff),
+ MenuAction::CloseTabsLeft(3),
+ MenuAction::CloseTabsRight(3),
+ MenuAction::CloseOtherTabs(3),
+ MenuAction::NewTabRight,
+ MenuAction::Zoom(7),
+ MenuAction::Pin("thread-a".into(), true),
+ MenuAction::Pin("thread-a".into(), false),
+ MenuAction::RenameThread("thread-a".into()),
+ MenuAction::DeleteThread("thread-a".into()),
+ MenuAction::MarkUnread("thread-a".into()),
+ MenuAction::RenameProject("project-b".into()),
+ MenuAction::NewThread("project-b".into()),
+ MenuAction::ToggleCollapsed("project-b".into()),
+ MenuAction::ArchiveProject("project-b".into()),
+ MenuAction::RemoveProject("project-b".into()),
+ MenuAction::UnarchiveProject("project-b".into()),
+ MenuAction::ShowArchived,
+ MenuAction::SwitchSpace("space-c".into()),
+ MenuAction::NewSpace,
+ MenuAction::RenameSpace("space-c".into()),
+ MenuAction::DeleteSpace("space-c".into()),
+ ];
+ for action in all {
+ assert_eq!(MenuAction::parse(&action.id()), Some(action.clone()), "{}", action.id());
+ }
+ assert_eq!(MenuAction::parse("split:sideways:1"), None);
+ assert_eq!(MenuAction::parse("pin:"), None);
+ assert_eq!(MenuAction::parse("zoom:x"), None);
+ }
+
+ #[test]
+ fn the_pane_menu_checks_the_current_access_mode() {
+ let items = for_pane(4, Some(FrontendAccessMode::Handoff));
+ assert_eq!(
+ labels(&items),
+ ["Copy", "Paste", "—", "Split Right", "Split Left", "Split Down", "Split Up", "—", "Frontend access ▸"]
+ );
+ let modes = &items.last().unwrap().submenu;
+ assert_eq!((modes[0].checked, modes[1].checked), (false, true));
+ assert_eq!(modes[1].icon, Some("check"));
+ assert_eq!(items[3].id, "split:right:4");
+ }
+
+ #[test]
+ fn the_tab_menu_offers_only_the_closes_that_exist() {
+ assert_eq!(labels(&for_tab(1, 0, 1, 9)), ["New Terminal Tab to Right", "—", "Zoom Pane"]);
+ assert_eq!(
+ labels(&for_tab(1, 0, 3, 9)),
+ ["Close Tabs to Right", "Close Other Tabs", "—", "New Terminal Tab to Right", "—", "Zoom Pane"]
+ );
+ assert_eq!(labels(&for_tab(1, 2, 3, 9))[0], "Close Tabs to Left");
+ assert_eq!(labels(&for_tab(1, 1, 3, 9))[..3], ["Close Tabs to Left", "Close Tabs to Right", "Close Other Tabs"]);
+ }
+
+ #[test]
+ fn the_space_menu_keeps_the_last_space() {
+ let one = vec![SpaceEntry { id: "s1".into(), name: "Default".into(), current: true, default: true }];
+ assert_eq!(labels(&for_space(&one)), ["Default", "—", "New Space", "Rename “Default”…"]);
+ assert!(for_space(&one)[0].checked);
+ let two = vec![
+ SpaceEntry { id: "s1".into(), name: "Default".into(), current: false, default: true },
+ SpaceEntry { id: "s2".into(), name: "Work".into(), current: true, default: false },
+ ];
+ let items = for_space(&two);
+ assert_eq!(labels(&items), ["Default", "Work", "—", "New Space", "Rename “Work”…", "Delete “Work”"]);
+ assert_eq!((items[0].checked, items[1].checked), (false, true));
+ assert_eq!(items[5].id, "delete-space:s2");
+ }
+
+ #[test]
+ fn the_thread_menu_flips_pin_and_the_project_menu_explains_an_archive() {
+ let row = ThreadRow {
+ id: "t1".into(),
+ project_id: "p1".into(),
+ name: "main".into(),
+ status: Status::Idle,
+ dot: Dot::Quiet,
+ pinned: true,
+ unread: false,
+ live: true,
+ selected: false,
+ deleting: false,
+ };
+ assert_eq!(labels(&for_thread(&row)), ["Unpin Thread", "Rename Thread…", "Delete Thread", "Mark as Unread"]);
+ assert_eq!(for_thread(&row)[0].id, "unpin:t1");
+ assert_eq!(
+ labels(&for_project("p1", 0)),
+ ["Rename Project…", "New Thread", "Collapse / Expand Threads", "—", "Archive Project", "Remove Project"]
+ );
+ let busy = for_project("p1", 2);
+ assert_eq!(labels(&busy)[4], "Archive Project… ▸");
+ assert_eq!(labels(&busy[4].submenu), ["# Closes 2 running panes; layouts are kept", "Archive and Close Panes"]);
+ let archived = for_archived_project("p1", 1);
+ assert_eq!(labels(&archived), ["Unarchive Project", "—", "Delete Permanently… ▸"]);
+ assert_eq!(labels(&archived[2].submenu)[0], "# Deletes 1 thread for good; this cannot be undone");
+ let options = for_sidebar_options(false, 0);
+ assert!(!options[0].enabled && !options[0].checked);
+ assert_eq!(for_sidebar_options(true, 3)[0].label, "Archived (3)");
+ }
+}
diff --git a/thinkterm-web/src/navbar.rs b/thinkterm-web/src/navbar.rs
index f1b7c343..8e382f7a 100644
--- a/thinkterm-web/src/navbar.rs
+++ b/thinkterm-web/src/navbar.rs
@@ -42,8 +42,9 @@ pub fn content_offset_dev(place: &PanePlacement, nav_dev: f32, cell_h_dev: f32)
}
/// Where a bar goes, in CSS px from the canvas's top-left.
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct NavRect {
+ #[serde(rename = "pane")]
pub pane_id: thinkterm_proto::PaneId,
pub left: f64,
pub top: f64,
@@ -93,7 +94,7 @@ pub fn rects(
/// `terminal_title_for_display`): a bare shell at its prompt is
/// "Terminal", and a leading busy marker (the spinner some agents put in
/// the title) is lifted off into the `busy` flag.
-pub fn display_title(title: &str) -> (&str, bool) {
+pub fn display_title(title: &str) -> (String, bool) {
let trimmed = title.trim_start();
let (title, busy) = match trimmed.chars().next() {
Some(ch) if is_busy_marker(ch) => (trimmed[ch.len_utf8()..].trim_start(), true),
@@ -101,9 +102,9 @@ pub fn display_title(title: &str) -> (&str, bool) {
};
let title = title.trim();
if title.is_empty() || is_default_shell_title(title) {
- ("Terminal", busy)
+ (thinkterm_i18n::tr("web-title-terminal"), busy)
} else {
- (title, busy)
+ (title.to_string(), busy)
}
}
@@ -124,7 +125,7 @@ fn is_default_shell_title(title: &str) -> bool {
}
/// What one bar shows.
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct NavView {
pub rect: NavRect,
pub members: Vec<CapsuleView>,
@@ -134,90 +135,15 @@ pub struct NavView {
pub closing: bool,
}
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct CapsuleView {
+ #[serde(rename = "pane")]
pub pane_id: thinkterm_proto::PaneId,
pub title: String,
pub busy: bool,
pub current: bool,
}
-#[cfg(target_arch = "wasm32")]
-mod dom {
- use super::NavView;
-
- pub struct NavBars {
- root: web_sys::Element,
- }
-
- fn escape(text: &str) -> String {
- let mut out = String::with_capacity(text.len());
- for c in text.chars() {
- match c {
- '&' => out.push_str("&amp;"),
- '<' => out.push_str("&lt;"),
- '>' => out.push_str("&gt;"),
- '"' => out.push_str("&quot;"),
- c => out.push(c),
- }
- }
- out
- }
-
- impl NavBars {
- pub fn mount(id: &str) -> Option<Self> {
- let root = web_sys::window()?.document()?.get_element_by_id(id)?;
- Some(Self { root })
- }
-
- pub fn element(&self) -> &web_sys::Element {
- &self.root
- }
-
- /// The markup for every bar. The caller keeps the last string and
- /// only sets it when it changed: layouts are re-listed often and
- /// mostly unchanged.
- pub fn html(bars: &[NavView]) -> String {
- let icon = crate::icons::svg;
- let mut html = String::new();
- for bar in bars {
- let class = if bar.focused { "nav focused" } else { "nav" };
- html.push_str(&format!(
- "<div class=\"{class}\" data-nav=\"{}\" style=\"left:{:.2}px;top:{:.2}px;width:{:.2}px;height:{:.2}px\"><span class=\"caps\">",
- bar.rect.pane_id, bar.rect.left, bar.rect.top, bar.rect.width, bar.rect.height
- ));
- for m in &bar.members {
- let class = if m.current { "cap current" } else { "cap" };
- let glyph = if m.busy { format!("<span class=\"spin\">{}</span>", icon("loader-circle")) } else { icon("square-terminal").to_string() };
- let (close_class, close_body) = if bar.closing && m.current {
- ("x danger", "close?")
- } else {
- ("x", icon("x"))
- };
- html.push_str(&format!(
- "<span class=\"{class}\" data-pane=\"{}\" title=\"{}\">{glyph}<span class=\"t\">{}</span><span class=\"{close_class}\" data-action=\"close-pane\" data-pane=\"{}\" title=\"Close this pane and end its program. Asks twice.\">{close_body}</span></span>",
- m.pane_id, escape(&m.title), escape(&m.title), m.pane_id
- ));
- }
- html.push_str("</span><span class=\"acts\">");
- html.push_str(&format!("<span class=\"act\" data-action=\"new-tab\" title=\"New tab\">{}</span>", icon("plus")));
- html.push_str(&format!("<span class=\"act\" data-action=\"split-below\" title=\"Split down\">{}</span>", icon("square-split-vertical")));
- html.push_str(&format!("<span class=\"act\" data-action=\"split-right\" title=\"Split right\">{}</span>", icon("square-split-horizontal")));
- let (zoom_icon, zoom_title) = if bar.zoomed { ("minimize-2", "Unzoom") } else { ("maximize-2", "Zoom this pane to the whole tab") };
- html.push_str(&format!("<span class=\"act\" data-action=\"zoom\" title=\"{zoom_title}\">{}</span>", icon(zoom_icon)));
- html.push_str("</span></div>");
- }
- html
- }
-
- pub fn set(&self, html: &str) {
- self.root.set_inner_html(html);
- }
- }
-}
-
-#[cfg(target_arch = "wasm32")]
-pub use dom::NavBars;
#[cfg(test)]
mod tests {
@@ -289,12 +215,17 @@ mod tests {
#[test]
fn titles_read_like_the_desktop_s() {
- assert_eq!(display_title("zsh"), ("Terminal", false));
- assert_eq!(display_title("/usr/bin/fish"), ("Terminal", false));
- assert_eq!(display_title("pwsh.exe"), ("Terminal", false));
- assert_eq!(display_title("vim notes.md"), ("vim notes.md", false));
- assert_eq!(display_title("\u{25d1} claude"), ("claude", true));
- assert_eq!(display_title("\u{2733} claude"), ("\u{2733} claude", false), "the idle marker stays");
- assert_eq!(display_title(" "), ("Terminal", false));
+ let dt = |s: &str| {
+ let (title, busy) = display_title(s);
+ (title, busy)
+ };
+ let t = |s: &str, b: bool| (s.to_string(), b);
+ assert_eq!(dt("zsh"), t("Terminal", false));
+ assert_eq!(dt("/usr/bin/fish"), t("Terminal", false));
+ assert_eq!(dt("pwsh.exe"), t("Terminal", false));
+ assert_eq!(dt("vim notes.md"), t("vim notes.md", false));
+ assert_eq!(dt("\u{25d1} claude"), t("claude", true));
+ assert_eq!(dt("\u{2733} claude"), t("\u{2733} claude", false), "the idle marker stays");
+ assert_eq!(dt(" "), t("Terminal", false));
}
}
diff --git a/thinkterm-web/src/page.rs b/thinkterm-web/src/page.rs
index 89dce1b9..692d5817 100644
--- a/thinkterm-web/src/page.rs
+++ b/thinkterm-web/src/page.rs
@@ -61,7 +61,6 @@ pub fn init() {
pub async fn start(
canvas_id: String,
textarea_id: String,
- status_id: String,
url: String,
token: String,
font_names: Vec<String>,
@@ -72,12 +71,17 @@ pub async fn start(
glyph_font: String,
// `?font=` was given: keep that size rather than the desktop's cell.
font_pinned: bool,
-) -> Result<(), JsValue> {
+ // The language: a preference ("system" or a tag) and the browser's list.
+ locale: String,
+ languages: Vec<String>,
+) -> Result<crate::bridge::Client, JsValue> {
+ thinkterm_i18n::activate_preference(&locale, &languages);
run(
- canvas_id, textarea_id, status_id, url, token, font_names, fonts, size_pt, glyph_font,
- font_pinned,
+ canvas_id, textarea_id, url, token, font_names, fonts, size_pt, glyph_font, font_pinned,
+ languages,
)
.await
+ .map(crate::bridge::Client::new)
.map_err(js_err)
}
@@ -93,7 +97,6 @@ fn families(requested: &str) -> Rc<str> {
async fn run(
canvas_id: String,
textarea_id: String,
- status_id: String,
url: String,
token: String,
font_names: Vec<String>,
@@ -101,15 +104,12 @@ async fn run(
size_pt: f64,
glyph_font: String,
font_pinned: bool,
-) -> Result<()> {
+ languages: Vec<String>,
+) -> Result<Rc<crate::app::App>> {
let canvas: web_sys::HtmlCanvasElement = element(&canvas_id)?;
let textarea: web_sys::HtmlTextAreaElement = element(&textarea_id)?;
- let status: Option<web_sys::Element> = element(&status_id).ok();
- let set_status = |text: &str| {
- if let Some(s) = &status {
- s.set_text_content(Some(text));
- }
- };
+ // The page draws its own status; the boot's progress is logged.
+ let set_status = |text: &str| log::info!("{text}");
let window = web_sys::window().ok_or_else(|| anyhow!("no window"))?;
if js_sys::Reflect::get(&window.navigator(), &JsValue::from_str("gpu"))
.map(|v| v.is_undefined())
@@ -136,8 +136,8 @@ async fn run(
// server keeps a registered client and a TCP session for a page that
// gave up, and the reader keeps answering its pings.
let outcome = start_attached(
- &link, &canvas, &textarea, status.clone(), &url, &token, fonts, size_pt, &glyph_font, dpr,
- dpi, font_pinned,
+ &link, &canvas, &textarea, &url, &token, fonts, size_pt, &glyph_font, dpr,
+ dpi, font_pinned, languages,
)
.await;
if outcome.is_err() {
@@ -150,7 +150,6 @@ async fn start_attached(
link: &WsLink,
canvas: &web_sys::HtmlCanvasElement,
textarea: &web_sys::HtmlTextAreaElement,
- status: Option<web_sys::Element>,
url: &str,
token: &str,
fonts: Rc<FontSet>,
@@ -159,12 +158,9 @@ async fn start_attached(
dpr: f64,
dpi: u32,
font_pinned: bool,
-) -> Result<()> {
- let set_status = |text: &str| {
- if let Some(s) = &status {
- s.set_text_content(Some(text));
- }
- };
+ languages: Vec<String>,
+) -> Result<Rc<crate::app::App>> {
+ let set_status = |text: &str| log::info!("{text}");
set_status("starting WebGPU…");
let rect = canvas.get_bounding_client_rect();
let dev_w = (rect.width() * dpr).floor().max(1.0) as u32;
@@ -242,7 +238,6 @@ async fn start_attached(
fonts,
canvas: canvas.clone(),
textarea: textarea.clone(),
- status,
url: url.to_string(),
token: token.to_string(),
pane_id: attached.pane_id,
@@ -252,10 +247,8 @@ async fn start_attached(
dpr,
cols,
rows,
- strip: crate::chrome::TabStrip::mount("tabs"),
- navs: crate::navbar::NavBars::mount("panes"),
- side: crate::sidebar::Sidebar::mount("side"),
font_pinned,
+ languages,
});
host.events.set_wake(app.wake());
{
@@ -267,68 +260,7 @@ async fn start_attached(
link.set_close_handler(move |reason| app.on_close(reason));
}
crate::input::install(Rc::clone(&app), canvas, textarea);
- // The strip: one listener on its root, so rebuilding its contents
- // costs nothing to keep wired.
- for root in [app.strip_element(), app.navs_element()].into_iter().flatten() {
- let app = Rc::clone(&app);
- crate::input::listen::<web_sys::MouseEvent>(&root, "click", move |ev| {
- if let Some(click) = crate::chrome::TabStrip::click_target(&ev) {
- ev.prevent_default();
- app.on_chrome_click(click);
- }
- });
- }
- if let (Some(root), Some(window)) = (app.side_element(), web_sys::window()) {
- let app2 = Rc::clone(&app);
- crate::input::listen::<web_sys::MouseEvent>(&root, "click", move |ev| {
- if let Some(click) = crate::sidebar::Sidebar::click_target(&ev) {
- ev.prevent_default();
- app2.on_side_click(click);
- }
- });
- {
- let app = Rc::clone(&app);
- crate::input::listen::<web_sys::KeyboardEvent>(&root, "keydown", move |ev| {
- let Some(input) = ev.target().and_then(|t| t.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
- return;
- };
- let key = ev.key();
- if key == "Enter" || key == "Escape" {
- ev.prevent_default();
- app.on_side_key(&key, input.value());
- }
- ev.stop_propagation();
- });
- }
- // The resize handle: drag the panel's edge, within the desktop's bounds.
- let dragging = Rc::new(std::cell::Cell::new(false));
- {
- let dragging = Rc::clone(&dragging);
- crate::input::listen::<web_sys::PointerEvent>(&root, "pointerdown", move |ev| {
- let target: Option<web_sys::Element> = ev.target().and_then(|t| t.dyn_into().ok());
- if target.is_some_and(|t| t.get_attribute("class").as_deref() == Some("handle")) {
- dragging.set(true);
- ev.prevent_default();
- }
- });
- }
- {
- let dragging = Rc::clone(&dragging);
- let app = Rc::clone(&app);
- crate::input::listen::<web_sys::PointerEvent>(&window, "pointermove", move |ev| {
- if dragging.get() {
- app.set_sidebar_width(ev.client_x() as f64);
- }
- });
- }
- crate::input::listen::<web_sys::PointerEvent>(&window, "pointerup", move |_| dragging.set(false));
- if let Some(px) = crate::sidebar::stored_width() {
- app.set_sidebar_width(px);
- }
- }
app.fetch_tree();
- // The boot messages were shown in the status element directly; from
- // here it is the page's passing remark, shown only when there is one.
app.hide_status();
app.refresh_layout();
app.poll_layout(5_000);
@@ -350,8 +282,9 @@ async fn start_attached(
);
}
}
- // The push and close handlers and every DOM listener hold the app.
- Ok(())
+ // The push and close handlers and every DOM listener hold the app;
+ // so does the page, through the handle it gets back.
+ Ok(app)
}
/// Render a mid-grey quad and read the pixel back: linear 0.5 must come
diff --git a/thinkterm-web/src/palette.rs b/thinkterm-web/src/palette.rs
new file mode 100644
index 00000000..12c3c701
--- /dev/null
+++ b/thinkterm-web/src/palette.rs
@@ -0,0 +1,232 @@
+//! The search palette as data: what can be found (threads, tabs, panes,
+//! Spaces, commands), how a query ranks it, and the id a pick hands back.
+//! The ranking is the desktop's (`command_palette.rs` `compute_order`):
+//! nucleo scores, an exact title first, results regrouped under their
+//! section with the best section first.
+
+use nucleo_matcher::pattern::{CaseMatching, Normalization, Pattern};
+use nucleo_matcher::{Config, Matcher, Utf32Str};
+use serde::Serialize;
+use thinkterm_i18n::tr;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum Group {
+ Threads,
+ Tabs,
+ Panes,
+ Spaces,
+ Commands,
+}
+
+impl Group {
+ fn label(self) -> String {
+ match self {
+ Group::Threads => tr("command-palette-group-thread"),
+ Group::Tabs => tr("web-palette-tabs"),
+ Group::Panes => tr("web-palette-panes"),
+ Group::Spaces => tr("command-palette-group-space"),
+ Group::Commands => tr("web-palette-commands"),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Entry {
+ /// `thread:<id>`, `tab:<id>`, `pane:<id>`, `space:<id>`, `cmd:<name>`, `lang:<tag>`.
+ pub id: String,
+ pub title: String,
+ pub subtitle: String,
+ /// A lucide icon name.
+ pub icon: &'static str,
+ /// Right-hand text: a shortcut, a Space, a state.
+ pub accessory: String,
+ pub group: Group,
+ /// Extra words a query may hit (a project's path, a Space's name).
+ #[serde(skip)]
+ pub terms: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Section {
+ pub group: Group,
+ pub label: String,
+ pub entries: Vec<Entry>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Results {
+ pub sections: Vec<Section>,
+ pub placeholder: String,
+ pub empty: String,
+}
+
+/// The fixed commands, with their ids and the keys of their labels.
+const COMMANDS: &[(&str, &str, &str, &str)] = &[
+ // id, label key, icon, shortcut
+ ("new-thread", "menu-new-thread", "circle-plus", ""),
+ ("new-tab", "web-cmd-new-tab", "plus", ""),
+ ("split-right", "menu-split-right", "square-split-horizontal", ""),
+ ("split-down", "menu-split-down", "square-split-vertical", ""),
+ ("zoom", "menu-zoom-pane", "maximize-2", ""),
+ ("close-pane", "web-cmd-close-pane", "x", ""),
+ ("take-over", "web-cmd-take-over", "square-terminal", "Ctrl+Shift+T"),
+ ("follow", "web-cmd-follow", "eye", ""),
+ ("toggle-sidebar", "web-cmd-toggle-sidebar", "panel-left", ""),
+ ("settings", "sidebar-settings", "settings", ""),
+ ("font-up", "web-cmd-font-up", "zoom-in", "Cmd+="),
+ ("font-down", "web-cmd-font-down", "zoom-out", "Cmd+-"),
+ ("font-reset", "web-cmd-font-reset", "rotate-ccw", "Cmd+0"),
+];
+
+pub fn commands() -> Vec<Entry> {
+ let out: Vec<Entry> = COMMANDS
+ .iter()
+ .map(|(id, key, icon, keys)| Entry {
+ id: format!("cmd:{id}"),
+ title: tr(key),
+ subtitle: String::new(),
+ icon,
+ accessory: keys.to_string(),
+ group: Group::Commands,
+ terms: id.replace('-', " "),
+ })
+ .collect();
+ out
+}
+
+/// The last two components of a project path, as the desktop indexes it
+/// (`search_path_terms`): "users"/"documents" must not hit every project.
+pub fn path_terms(path: &str) -> String {
+ let parts: Vec<&str> = path.trim_end_matches('/').rsplit('/').filter(|p| !p.is_empty()).take(2).collect();
+ parts.join(" ")
+}
+
+fn haystack(entry: &Entry) -> String {
+ format!("{} {} {} {}", entry.title, entry.subtitle, entry.accessory, entry.terms)
+}
+
+/// Rank `entries` for `query`: nucleo scores, an exact title match first,
+/// then regrouped under their sections with the best section first.
+/// An empty query lists everything in source order, the `recent` ids
+/// (most recent first) ahead of the rest of their section.
+pub fn rank(query: &str, entries: Vec<Entry>, recent: &[String]) -> Vec<Section> {
+ let order = [Group::Threads, Group::Tabs, Group::Panes, Group::Spaces, Group::Commands];
+ let query = query.trim();
+ let scored: Vec<(u64, Entry)> = if query.is_empty() {
+ entries
+ .into_iter()
+ .map(|e| {
+ let recency = recent.iter().position(|r| *r == e.id).map(|p| u32::MAX as u64 - p as u64).unwrap_or(1);
+ (recency, e)
+ })
+ .collect()
+ } else {
+ let mut matcher = Matcher::new(Config::DEFAULT);
+ let pattern = Pattern::parse(query, CaseMatching::Ignore, Normalization::Smart);
+ let mut buf = Vec::new();
+ entries
+ .into_iter()
+ .filter_map(|e| {
+ if e.title.eq_ignore_ascii_case(query) {
+ return Some((u64::MAX, e));
+ }
+ let hay = haystack(&e);
+ pattern.score(Utf32Str::new(&hay, &mut buf), &mut matcher).map(|s| (s as u64, e))
+ })
+ .collect()
+ };
+ let mut sections: Vec<(u64, Section)> = Vec::new();
+ for group in order {
+ let mut members: Vec<(u64, Entry)> = scored.iter().filter(|(_, e)| e.group == group).cloned().collect();
+ if members.is_empty() {
+ continue;
+ }
+ // Stable: equal scores keep their source order.
+ members.sort_by(|a, b| b.0.cmp(&a.0));
+ let best = members[0].0;
+ sections.push((best, Section { group, label: group.label(), entries: members.into_iter().map(|(_, e)| e).collect() }));
+ }
+ if !query.is_empty() {
+ sections.sort_by(|a, b| b.0.cmp(&a.0));
+ }
+ sections.into_iter().map(|(_, s)| s).collect()
+}
+
+pub fn results(query: &str, entries: Vec<Entry>, recent: &[String]) -> Results {
+ Results {
+ sections: rank(query, entries, recent),
+ placeholder: tr("command-palette-placeholder"),
+ empty: tr("command-palette-empty"),
+ }
+}
+
+/// Remember a pick: most recent first, without duplicates, capped.
+pub fn remember(recent: &mut Vec<String>, id: &str) {
+ recent.retain(|r| r != id);
+ recent.insert(0, id.to_string());
+ recent.truncate(50);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn thread(id: &str, name: &str, project: &str, path: &str) -> Entry {
+ Entry {
+ id: format!("thread:{id}"),
+ title: name.into(),
+ subtitle: project.into(),
+ icon: "square-terminal",
+ accessory: "Default".into(),
+ group: Group::Threads,
+ terms: path_terms(path),
+ }
+ }
+
+ #[test]
+ fn path_terms_keep_the_last_two_components() {
+ assert_eq!(path_terms("/Users/me/Documents/GitHub/thinkterm/"), "thinkterm GitHub");
+ assert_eq!(path_terms("~"), "~");
+ }
+
+ #[test]
+ fn a_typed_thread_name_ranks_its_section_first() {
+ let entries = vec![
+ thread("a", "main", "thinkterm", "/Users/me/GitHub/thinkterm"),
+ thread("b", "notes", "diary", "/Users/me/diary"),
+ ]
+ .into_iter()
+ .chain(commands())
+ .collect();
+ let sections = rank("note", entries, &[]);
+ assert_eq!(sections[0].group, Group::Threads);
+ assert_eq!(sections[0].entries[0].id, "thread:b");
+ // A project's path finds its threads; "users" alone does not.
+ let sections = rank("github", vec![thread("a", "main", "thinkterm", "/Users/me/GitHub/thinkterm")], &[]);
+ assert_eq!(sections.len(), 1);
+ assert!(rank("users", vec![thread("a", "main", "thinkterm", "/Users/me/GitHub/thinkterm")], &[]).is_empty());
+ }
+
+ #[test]
+ fn an_exact_title_beats_a_fuzzy_one_and_recents_lead_an_empty_query() {
+ let entries = vec![thread("a", "zoom lens", "p", ""), thread("b", "zoom", "p", "")];
+ let sections = rank("zoom", entries.clone(), &[]);
+ assert_eq!(sections[0].entries[0].id, "thread:b");
+ let sections = rank("", entries, &["thread:b".into()]);
+ assert_eq!(sections[0].entries[0].id, "thread:b");
+ let mut recent = vec!["cmd:zoom".to_string()];
+ remember(&mut recent, "thread:b");
+ remember(&mut recent, "cmd:zoom");
+ assert_eq!(recent, ["cmd:zoom", "thread:b"]);
+ }
+
+ #[test]
+ fn commands_are_the_desktop_s_where_it_has_them() {
+ let cmds = commands();
+ assert!(cmds.iter().any(|e| e.id == "cmd:take-over" && e.title == "Take Over the Terminal"));
+ assert!(cmds.iter().any(|e| e.id == "cmd:font-reset" && e.title == "Reset font size"));
+ assert!(!cmds.iter().any(|e| e.id.starts_with("lang:")), "the language is a setting, not a command");
+ assert_eq!(rank("", cmds, &[]).len(), 1);
+ }
+}
diff --git a/thinkterm-web/src/settings.rs b/thinkterm-web/src/settings.rs
new file mode 100644
index 00000000..00c586d5
--- /dev/null
+++ b/thinkterm-web/src/settings.rs
@@ -0,0 +1,97 @@
+//! The page's own preferences, as the model holds them: what the page
+//! stores per browser and hands back at boot. The model applies what
+//! concerns it (language, font); the page draws the rest from here.
+
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "kebab-case")]
+pub struct WebSettings {
+ /// `"system"` or a locale tag.
+ pub language: String,
+ pub theme: Theme,
+ pub font: FontMode,
+ pub hover_reveal: bool,
+ pub agents_panel: bool,
+ pub palette_hotkey: Hotkey,
+ pub sidebar_width: f64,
+}
+
+impl Default for WebSettings {
+ fn default() -> Self {
+ Self {
+ language: thinkterm_i18n::SYSTEM_PREFERENCE.to_string(),
+ theme: Theme::Dark,
+ font: FontMode::Follow,
+ hover_reveal: true,
+ agents_panel: false,
+ palette_hotkey: Hotkey::CmdK,
+ sidebar_width: 220.0,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum Theme {
+ Dark,
+ Light,
+ System,
+}
+
+/// The base font size: the desktop's cell, or a size of the page's own.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "mode", rename_all = "kebab-case")]
+pub enum FontMode {
+ Follow,
+ Pinned { pt: f64 },
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum Hotkey {
+ CmdK,
+ CmdShiftP,
+ CtrlShiftP,
+}
+
+impl WebSettings {
+ pub fn parse(json: &str) -> Result<Self, String> {
+ serde_json::from_str(json).map_err(|e| e.to_string())
+ }
+
+ /// One field by its JSON name, from a JSON value.
+ pub fn set(&mut self, key: &str, value: &str) -> Result<(), String> {
+ let mut all = serde_json::to_value(&*self).map_err(|e| e.to_string())?;
+ let value: serde_json::Value = serde_json::from_str(value).map_err(|e| e.to_string())?;
+ let object = all.as_object_mut().ok_or("settings are an object")?;
+ if !object.contains_key(key) {
+ return Err(format!("no setting {key:?}"));
+ }
+ object.insert(key.to_string(), value);
+ *self = serde_json::from_value(all).map_err(|e| e.to_string())?;
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn missing_fields_take_defaults_and_keys_are_checked() {
+ let s = WebSettings::parse(r#"{"theme":"light","font":{"mode":"pinned","pt":14}}"#).unwrap();
+ assert_eq!(s.theme, Theme::Light);
+ assert_eq!(s.font, FontMode::Pinned { pt: 14.0 });
+ assert_eq!(s.language, "system");
+ assert!(s.hover_reveal);
+ let mut s = WebSettings::default();
+ s.set("language", "\"de-DE\"").unwrap();
+ s.set("palette-hotkey", "\"ctrl-shift-p\"").unwrap();
+ assert_eq!((s.language.as_str(), s.palette_hotkey), ("de-DE", Hotkey::CtrlShiftP));
+ assert!(s.set("colour", "1").is_err());
+ assert!(s.set("theme", "\"blue\"").is_err());
+ let json = serde_json::to_value(&s).unwrap();
+ assert_eq!(json["font"], serde_json::json!({"mode": "follow"}));
+ }
+}
diff --git a/thinkterm-web/src/sidebar.rs b/thinkterm-web/src/sidebar.rs
index 5dcae7d1..2ec7f8f0 100644
--- a/thinkterm-web/src/sidebar.rs
+++ b/thinkterm-web/src/sidebar.rs
@@ -2,126 +2,17 @@
//! (`termwindow/ui/sidebar.rs`) as HTML. The markup is built from
//! `tree::Row`s here, on every target; only mounting and clicks are wasm.
-use crate::tree::{Dot, Row, Status};
use thinkterm_proto::WindowId;
-fn escape(text: &str) -> String {
- let mut out = String::with_capacity(text.len());
- for c in text.chars() {
- match c {
- '&' => out.push_str("&amp;"),
- '<' => out.push_str("&lt;"),
- '>' => out.push_str("&gt;"),
- '"' => out.push_str("&quot;"),
- c => out.push(c),
- }
- }
- out
-}
-
-/// A name or path being typed into the panel.
-#[derive(Debug, Clone, PartialEq, Eq, Default)]
+#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize)]
+#[serde(tag = "kind", content = "id", rename_all = "kebab-case")]
pub enum Editing {
#[default]
None,
NewProject,
Thread(String),
Project(String),
-}
-
-/// The panel's markup.
-pub fn html(rows: &[Row], editing: &Editing) -> String {
- let icon = crate::icons::svg;
- let mut h = String::from("<div class=\"handle\"></div><div class=\"list\">");
- let field = |value: &str| format!("<input class=\"rename\" value=\"{}\" spellcheck=\"false\">", escape(value));
- for row in rows {
- match row {
- Row::Space { name } => h.push_str(&format!(
- "<div class=\"row space\">{}<span class=\"t\">{}</span><span class=\"act\" data-action=\"space-menu\" title=\"Space\">{}</span></div>",
- icon("layers"),
- escape(name),
- icon("ellipsis")
- )),
- Row::NewThread => h.push_str(&format!(
- "<div class=\"pill\" data-action=\"new-thread\" title=\"New thread in the project on show\">{}<span>New Thread</span></div>",
- icon("circle-plus")
- )),
- Row::Pinned => h.push_str(&format!("<div class=\"hdr\">{}<span>Pinned</span></div>", icon("pin"))),
- Row::Workspaces => {
- h.push_str(&format!(
- "<div class=\"hdr\"><span>Workspaces</span><span class=\"act\" data-action=\"new-project\" title=\"New project: a directory on the server\">{}</span></div>",
- icon("folder-plus")
- ));
- if *editing == Editing::NewProject {
- h.push_str("<div class=\"path\"><input placeholder=\"~/project or /path on the server\" spellcheck=\"false\"></div>");
- }
- }
- Row::Project { id, name, path, collapsed, archived } => {
- if *archived {
- h.push_str(&format!(
- "<div class=\"row project archived\" data-project=\"{}\" title=\"{}\">{}<span class=\"t\">{}</span><span class=\"hov\"><span class=\"act\" data-action=\"unarchive\" data-project=\"{}\" title=\"Restore\">{}</span></span></div>",
- escape(id), escape(path), icon("archive"), escape(name), escape(id), icon("archive-restore")
- ));
- } else {
- let (chev, folder) = if *collapsed { ("chevron-right", "folder") } else { ("chevron-down", "folder-open") };
- let title = if *editing == Editing::Project(id.clone()) {
- field(name)
- } else {
- format!("<span class=\"t\" data-action=\"rename-project\" data-project=\"{}\">{}</span>", escape(id), escape(name))
- };
- h.push_str(&format!(
- "<div class=\"row project\" data-project=\"{}\" title=\"{}\"><span class=\"chev\">{}</span>{}{title}<span class=\"hov\"><span class=\"act\" data-action=\"new-thread\" data-project=\"{}\" title=\"New thread here\">{}</span><span class=\"act\" data-action=\"archive\" data-project=\"{}\" title=\"Archive this project (ends its programs)\">{}</span></span></div>",
- escape(id), escape(path), icon(chev), icon(folder), escape(id), icon("plus"), escape(id), icon("archive")
- ));
- }
- }
- Row::Thread(t) => {
- let status = match t.status {
- Status::Running => format!("<span class=\"st spin\">{}</span>", icon("loader-circle")),
- Status::NeedsAttention => format!("<span class=\"st alert\">{}</span>", icon("circle-alert")),
- Status::Done => format!("<span class=\"st done\">{}</span>", icon("circle-check")),
- Status::Idle => {
- let dot = match t.dot {
- Dot::Active => "active",
- Dot::Unread => "unread",
- Dot::Pinned => "pinned",
- Dot::Open => "open",
- Dot::Quiet => "quiet",
- };
- format!("<span class=\"st dot {dot}\"></span>")
- }
- };
- let (pin_action, pin_icon, pin_title) = if t.pinned { ("unpin", "pin-off", "Unpin") } else { ("pin", "pin", "Pin") };
- let class = if t.selected { "row thread selected" } else { "row thread" };
- let title = if *editing == Editing::Thread(t.id.clone()) {
- field(&t.name)
- } else {
- format!("<span class=\"t\" data-action=\"rename-thread\" data-thread=\"{}\">{}</span>", escape(&t.id), escape(&t.name))
- };
- let (del_class, del_body) = if t.deleting { ("act danger", "delete?".to_string()) } else { ("act", icon("trash-2").to_string()) };
- h.push_str(&format!(
- "<div class=\"{class}\" data-thread=\"{}\">{status}{title}<span class=\"hov\"><span class=\"act\" data-action=\"{pin_action}\" data-thread=\"{}\" title=\"{pin_title}\">{}</span><span class=\"{del_class}\" data-action=\"delete\" data-thread=\"{}\" title=\"Delete this thread and end its programs. Asks twice.\">{del_body}</span></span></div>",
- escape(&t.id), escape(&t.id), icon(pin_icon), escape(&t.id)
- ));
- }
- Row::Archived { count, open } => h.push_str(&format!(
- "<div class=\"hdr sub\" data-action=\"archived\"><span class=\"chev\">{}</span>{}<span>Archived ({count})</span></div>",
- icon(if *open { "chevron-down" } else { "chevron-right" }),
- icon("archive")
- )),
- Row::Others => h.push_str("<div class=\"hdr\"><span>Other windows</span></div>"),
- Row::Window { window_id, title, selected } => {
- let class = if *selected { "row thread selected" } else { "row thread" };
- h.push_str(&format!(
- "<div class=\"{class}\" data-window=\"{window_id}\"><span class=\"st dot {}\"></span><span class=\"t\">{}</span></div>",
- if *selected { "active" } else { "open" },
- escape(title)
- ));
- }
- }
- }
- h.push_str("</div>");
- h
+ Space(String),
}
/// What a click in the panel meant.
@@ -142,120 +33,6 @@ pub enum SideClick {
SpaceMenu,
}
-#[cfg(target_arch = "wasm32")]
-mod dom {
- use super::SideClick;
- use wasm_bindgen::JsCast;
-
- pub struct Sidebar {
- root: web_sys::Element,
- }
-
- impl Sidebar {
- pub fn mount(id: &str) -> Option<Self> {
- let root = web_sys::window()?.document()?.get_element_by_id(id)?;
- Some(Self { root })
- }
-
- pub fn element(&self) -> &web_sys::Element {
- &self.root
- }
-
- pub fn set(&self, html: &str) {
- self.root.set_inner_html(html);
- }
-
- /// What a click landed on. A click on a row's text or dot is the
- /// row; the small buttons and the headers' actions are their own.
- pub fn click_target(ev: &web_sys::MouseEvent) -> Option<SideClick> {
- let target: web_sys::Element = ev.target()?.dyn_into().ok()?;
- let hit = target.closest("[data-action],[data-thread],[data-window],[data-project]").ok()??;
- let thread = || hit.get_attribute("data-thread");
- let project = || hit.get_attribute("data-project");
- if let Some(action) = hit.get_attribute("data-action") {
- return match action.as_str() {
- "new-thread" => Some(SideClick::NewThread(project())),
- "new-project" => Some(SideClick::NewProject),
- "archived" => Some(SideClick::ToggleArchived),
- "pin" => thread().map(|t| SideClick::Pin(t, true)),
- "unpin" => thread().map(|t| SideClick::Pin(t, false)),
- "delete" => thread().map(SideClick::Delete),
- "archive" => project().map(SideClick::Archive),
- "unarchive" => project().map(SideClick::Unarchive),
- "space-menu" => Some(SideClick::SpaceMenu),
- // A single click on a name is the row; renaming is a double click.
- "rename-thread" if ev.detail() >= 2 => thread().map(SideClick::RenameThread),
- "rename-project" if ev.detail() >= 2 => project().map(SideClick::RenameProject),
- "rename-thread" => thread().map(SideClick::Thread),
- "rename-project" => project().map(SideClick::ToggleProject),
- _ => None,
- };
- }
- if let Some(t) = thread() {
- return Some(SideClick::Thread(t));
- }
- if let Some(w) = hit.get_attribute("data-window") {
- return w.parse().ok().map(SideClick::Window);
- }
- project().map(SideClick::ToggleProject)
- }
- }
-
- /// The panel's width, kept per browser.
- pub fn stored_width() -> Option<f64> {
- let storage = web_sys::window()?.local_storage().ok()??;
- storage.get_item("thinkterm.sidebar").ok()??.parse().ok()
- }
-
- pub fn store_width(px: f64) {
- if let Some(storage) = web_sys::window().and_then(|w| w.local_storage().ok().flatten()) {
- let _ = storage.set_item("thinkterm.sidebar", &format!("{px:.0}"));
- }
- }
-}
-
-#[cfg(target_arch = "wasm32")]
-pub use dom::{store_width, stored_width, Sidebar};
-
-/// The desktop's bounds for the panel, in CSS px.
pub const MIN_WIDTH: f64 = 127.0;
pub const MAX_WIDTH: f64 = 260.0;
pub const DEFAULT_WIDTH: f64 = 220.0;
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::tree::ThreadRow;
-
- #[test]
- fn the_markup_names_what_a_click_lands_on() {
- let rows = vec![
- Row::Space { name: "Default".into() },
- Row::NewThread,
- Row::Workspaces,
- Row::Project { id: "p1".into(), name: "Home".into(), path: "~".into(), collapsed: false, archived: false },
- Row::Thread(ThreadRow {
- id: "t1".into(),
- project_id: "p1".into(),
- name: "main <1>".into(),
- status: Status::Idle,
- dot: Dot::Active,
- pinned: false,
- unread: false,
- live: true,
- selected: true,
- deleting: false,
- }),
- ];
- let h = html(&rows, &Editing::None);
- assert!(h.contains("data-thread=\"t1\""));
- assert!(!h.contains("<input"));
- let h = html(&rows, &Editing::Thread("t1".into()));
- assert!(h.contains("<input class=\"rename\" value=\"main &lt;1&gt;\""));
- assert!(html(&rows, &Editing::NewProject).contains("class=\"path\""));
- assert!(h.contains("main &lt;1&gt;"), "titles are escaped");
- assert!(h.contains("class=\"row thread selected\""));
- assert!(h.contains("data-action=\"new-project\""));
- assert!(h.contains("data-project=\"p1\""));
- }
-}
diff --git a/thinkterm-web/src/tree.rs b/thinkterm-web/src/tree.rs
index f5c3dd22..ac8c8e0e 100644
--- a/thinkterm-web/src/tree.rs
+++ b/thinkterm-web/src/tree.rs
@@ -12,7 +12,7 @@ use codec::{ListPanesResponse, ThinkTermSessionState, ThinkTermSessionThread, Th
use std::collections::{HashMap, HashSet};
use thinkterm_proto::{AgentState, AgentStatus, PaneId, TabId, WindowId};
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum Status {
Idle,
Running,
@@ -20,7 +20,7 @@ pub enum Status {
Done,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum Dot {
Active,
Unread,
@@ -29,22 +29,31 @@ pub enum Dot {
Quiet,
}
-#[derive(Debug, Clone, PartialEq)]
+/// Serialised for the page as `{"kind": …}` rows, the shape the sidebar
+/// probe has always read.
+#[derive(Debug, Clone, PartialEq, serde::Serialize)]
+#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum Row {
- Space { name: String },
+ Space { id: String, name: String },
NewThread,
Pinned,
Workspaces,
Project { id: String, name: String, path: String, collapsed: bool, archived: bool },
Thread(ThreadRow),
- Archived { count: usize, open: bool },
+ Archived { count: usize, open: bool, label: String },
Others,
- Window { window_id: WindowId, title: String, selected: bool },
+ Window {
+ #[serde(rename = "id")]
+ window_id: WindowId,
+ title: String,
+ selected: bool,
+ },
}
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct ThreadRow {
pub id: String,
+ #[serde(rename = "project")]
pub project_id: String,
pub name: String,
pub status: Status,
@@ -58,13 +67,26 @@ pub struct ThreadRow {
pub deleting: bool,
}
+/// A Space as the Space menu lists it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SpaceEntry {
+ pub id: String,
+ pub name: String,
+ pub current: bool,
+ pub default: bool,
+}
+
#[derive(Default)]
pub struct TreeModel {
pub session: Option<ThinkTermSessionState>,
pub tree: Option<ThinkTermTree>,
pub agents: HashMap<PaneId, AgentState>,
+ /// The agent's id and the pane's title as the server reported them.
+ agent_details: HashMap<PaneId, (String, String)>,
pub collapsed: HashSet<String>,
pub archived_open: bool,
+ /// The Space the sidebar shows; the first one until chosen.
+ pub space: Option<String>,
/// Every window on the server, with its workspace and a title.
windows: Vec<(WindowId, String, String)>,
}
@@ -87,13 +109,48 @@ impl TreeModel {
self.tree = Some(tree);
}
+ /// Every pane an agent runs in: pane, agent id, state, reported title.
+ pub fn agent_entries(&self) -> impl Iterator<Item = (PaneId, &str, AgentState, &str)> {
+ self.agents.iter().map(|(pane, state)| {
+ let (id, title) = self
+ .agent_details
+ .get(pane)
+ .map(|(id, title)| (id.as_str(), title.as_str()))
+ .unwrap_or(("", ""));
+ (*pane, id, *state, title)
+ })
+ }
+
+ /// Where a pane is: "Project · Thread" and its window, from the
+ /// thread whose tabs hold it; a window's workspace otherwise.
+ pub fn place_of_pane(&self, pane: PaneId) -> (String, Option<WindowId>) {
+ if let Some(session) = &self.session {
+ for project in &session.projects {
+ for thread in &project.threads {
+ if let Some(tab) = thread.tabs.iter().find(|t| t.pane_ids.contains(&pane)) {
+ return (format!("{} · {}", project.name, thread.name), Some(tab.window_id));
+ }
+ }
+ }
+ }
+ (String::new(), None)
+ }
+
+ /// The title the server reported with an agent's status, when it did.
+ pub fn record_agent_details(&mut self, pane_id: PaneId, agent_id: &str, title: &str) {
+ self.agent_details.insert(pane_id, (agent_id.to_string(), title.to_string()));
+ }
+
pub fn apply_agent(&mut self, pane_id: PaneId, status: Option<&AgentStatus>) {
match status {
Some(s) => {
self.agents.insert(pane_id, s.state);
+ let title = self.agent_details.get(&pane_id).map(|(_, t)| t.clone()).unwrap_or_default();
+ self.agent_details.insert(pane_id, (s.agent_id.clone(), title));
}
None => {
self.agents.remove(&pane_id);
+ self.agent_details.remove(&pane_id);
}
}
}
@@ -116,8 +173,7 @@ impl TreeModel {
.filter(|t| !t.is_empty())
.cloned()
.unwrap_or_else(|| {
- let (title, _) = crate::navbar::display_title(&first.title);
- title.to_string()
+ crate::navbar::display_title(&first.title).0
});
self.windows.push((first.window_id, first.workspace.clone(), title));
}
@@ -132,6 +188,31 @@ impl TreeModel {
.find(|t| t.id == id)
}
+ /// Every pane the project's threads have on the server.
+ pub fn live_panes_of_project(&self, project_id: &str) -> Vec<PaneId> {
+ self.session
+ .as_ref()
+ .and_then(|s| s.projects.iter().find(|p| p.id == project_id))
+ .map(|p| p.threads.iter().flat_map(|t| t.tabs.iter().flat_map(|tab| tab.pane_ids.iter().copied())).collect())
+ .unwrap_or_default()
+ }
+
+ /// How many threads a project has in the tree (archived ones included).
+ pub fn thread_count_of_project(&self, project_id: &str) -> usize {
+ self.tree
+ .as_ref()
+ .and_then(|t| t.projects.iter().find(|p| p.id == project_id))
+ .map(|p| p.threads.len())
+ .unwrap_or(0)
+ }
+
+ pub fn archived_count(&self) -> usize {
+ self.tree
+ .as_ref()
+ .map(|t| t.projects.iter().filter(|p| p.archived_at.is_some()).count())
+ .unwrap_or(0)
+ }
+
pub fn project_of(&self, thread_id: &str) -> Option<&codec::ThinkTermSessionProject> {
self.session
.as_ref()?
@@ -178,6 +259,57 @@ impl TreeModel {
/// The thread on show: the one holding the tab on show, else the one
/// whose workspace the page is in.
+ /// The Space on show: the chosen one while the server still has it,
+ /// else the first.
+ pub fn current_space(&self) -> Option<&codec::ThinkTermSessionSpace> {
+ let spaces = &self.session.as_ref()?.spaces;
+ self.space
+ .as_deref()
+ .and_then(|id| spaces.iter().find(|s| s.id == id))
+ .or_else(|| spaces.first())
+ }
+
+ /// Choose a Space; false when the server has no such Space.
+ pub fn set_space(&mut self, id: &str) -> bool {
+ let known = self.session.as_ref().is_some_and(|s| s.spaces.iter().any(|s| s.id == id));
+ if known {
+ self.space = Some(id.to_string());
+ }
+ known
+ }
+
+ /// Every Space, for the Space menu.
+ pub fn spaces(&self) -> Vec<SpaceEntry> {
+ let current = self.current_space().map(|s| s.id.clone());
+ self.session
+ .as_ref()
+ .map(|s| {
+ s.spaces
+ .iter()
+ .map(|space| SpaceEntry {
+ id: space.id.clone(),
+ name: space.name.clone(),
+ current: current.as_deref() == Some(space.id.as_str()),
+ default: space.is_default,
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+ }
+
+ /// The project a new thread goes to when none is named: the selected
+ /// thread's when it is in the Space on show, else the Space's first.
+ pub fn default_project(&self, current_tab: TabId, current_workspace: &str) -> Option<String> {
+ let space = self.current_space()?.id.clone();
+ let session = self.session.as_ref()?;
+ let selected = self
+ .selected_thread(current_tab, current_workspace)
+ .and_then(|t| self.project_of(t))
+ .filter(|p| p.space_id == space)
+ .map(|p| p.id.clone());
+ selected.or_else(|| session.projects.iter().find(|p| p.space_id == space).map(|p| p.id.clone()))
+ }
+
pub fn selected_thread(&self, current_tab: TabId, current_workspace: &str) -> Option<&str> {
let session = self.session.as_ref()?;
let threads = || session.projects.iter().flat_map(|p| p.threads.iter());
@@ -204,13 +336,14 @@ impl TreeModel {
return rows;
};
let selected = self.selected_thread(current_tab, current_workspace);
- let space_name = session
- .spaces
- .first()
- .map(|s| s.name.clone())
- .unwrap_or_else(|| "Default".to_string());
- rows.push(Row::Space { name: space_name });
+ let space = self.current_space();
+ let space_id = space.map(|s| s.id.clone()).unwrap_or_default();
+ rows.push(Row::Space {
+ id: space_id.clone(),
+ name: space.map(|s| s.name.clone()).unwrap_or_else(|| "Default".to_string()),
+ });
rows.push(Row::NewThread);
+ let in_space = |p: &&codec::ThinkTermSessionProject| p.space_id == space_id;
let thread_row = |t: &ThinkTermSessionThread, project_id: &str| {
let live = !t.tabs.is_empty();
let is_selected = selected == Some(t.id.as_str());
@@ -241,6 +374,7 @@ impl TreeModel {
let pinned: Vec<Row> = session
.projects
.iter()
+ .filter(in_space)
.flat_map(|p| p.threads.iter().filter(|t| t.is_pinned).map(move |t| thread_row(t, &p.id)))
.collect();
if !pinned.is_empty() {
@@ -248,7 +382,7 @@ impl TreeModel {
rows.extend(pinned);
}
rows.push(Row::Workspaces);
- for project in &session.projects {
+ for project in session.projects.iter().filter(in_space) {
let collapsed = self.collapsed.contains(&project.id);
rows.push(Row::Project {
id: project.id.clone(),
@@ -265,10 +399,16 @@ impl TreeModel {
let archived: Vec<&codec::TtProject> = self
.tree
.as_ref()
- .map(|t| t.projects.iter().filter(|p| p.archived_at.is_some()).collect())
+ .map(|t| t.projects.iter().filter(|p| p.archived_at.is_some() && p.space_id == space_id).collect())
.unwrap_or_default();
if !archived.is_empty() {
- rows.push(Row::Archived { count: archived.len(), open: self.archived_open });
+ let mut args = thinkterm_i18n::FluentArgs::new();
+ args.set("count", archived.len() as i64);
+ rows.push(Row::Archived {
+ count: archived.len(),
+ open: self.archived_open,
+ label: thinkterm_i18n::tr_args("menu-show-archived-count", &args),
+ });
if self.archived_open {
for p in archived {
rows.push(Row::Project {
@@ -322,6 +462,11 @@ pub enum Expect {
ProjectExists(String),
ProjectNamed(String, String),
ProjectArchived(String, bool),
+ ThreadUnread(String, bool),
+ ProjectGone(String),
+ SpaceExists(String),
+ SpaceNamed(String, String),
+ SpaceGone(String),
}
impl Expect {
@@ -353,6 +498,25 @@ impl Expect {
Some(_) => Err("the server kept the old name".into()),
None => Err("the project is gone".into()),
},
+ Expect::SpaceExists(id) => tree.spaces.iter().any(|s| &s.id == id).then_some(()).ok_or_else(|| "the server did not create the Space".into()),
+ Expect::SpaceNamed(id, name) => match tree.spaces.iter().find(|s| &s.id == id) {
+ Some(s) if &s.name == name => Ok(()),
+ Some(_) => Err("the server kept the old name".into()),
+ None => Err("the Space is gone".into()),
+ },
+ Expect::SpaceGone(id) => match tree.spaces.iter().find(|s| &s.id == id) {
+ None => Ok(()),
+ Some(_) => Err("the server did not delete the Space".into()),
+ },
+ Expect::ThreadUnread(id, unread) => match thread(id) {
+ Some(t) if t.is_unread == *unread => Ok(()),
+ Some(_) => Err("the server did not change the unread mark".into()),
+ None => Err("the thread is gone".into()),
+ },
+ Expect::ProjectGone(id) => match project(id) {
+ None => Ok(()),
+ Some(_) => Err("the server did not remove the project".into()),
+ },
Expect::ProjectArchived(id, archived) => match project(id) {
Some(p) if p.archived_at.is_some() == *archived => Ok(()),
Some(_) if *archived => Err("the last project of a Space cannot be archived".into()),
@@ -451,6 +615,43 @@ pub fn delete_thread(id: &str) -> Intent {
}
}
+pub fn create_space(id: String, name: &str) -> Intent {
+ Intent {
+ ops: vec![TreeOp::CreateSpace { space_id: id.clone(), name: name.to_string() }],
+ expect: Expect::SpaceExists(id),
+ }
+}
+
+pub fn rename_space(id: &str, name: &str) -> Intent {
+ Intent {
+ ops: vec![TreeOp::RenameSpace { space_id: id.to_string(), name: name.to_string() }],
+ expect: Expect::SpaceNamed(id.to_string(), name.to_string()),
+ }
+}
+
+/// Delete a Space; the server drops its projects and threads with it.
+pub fn delete_space(id: &str) -> Intent {
+ Intent {
+ ops: vec![TreeOp::DeleteSpace { space_id: id.to_string() }],
+ expect: Expect::SpaceGone(id.to_string()),
+ }
+}
+
+pub fn set_unread(id: &str, unread: bool) -> Intent {
+ Intent {
+ ops: vec![TreeOp::SetThreadUnread { thread_id: id.to_string(), unread }],
+ expect: Expect::ThreadUnread(id.to_string(), unread),
+ }
+}
+
+/// Remove a project and its threads for good.
+pub fn remove_project(id: &str) -> Intent {
+ Intent {
+ ops: vec![TreeOp::RemoveProject { project_id: id.to_string() }],
+ expect: Expect::ProjectGone(id.to_string()),
+ }
+}
+
pub fn archive_project(id: &str, archived: bool, now: i64) -> Intent {
Intent {
ops: vec![TreeOp::SetProjectArchived { project_id: id.to_string(), archived_at: archived.then_some(now) }],
diff --git a/thinkterm-web/src/views.rs b/thinkterm-web/src/views.rs
new file mode 100644
index 00000000..97c0d992
--- /dev/null
+++ b/thinkterm-web/src/views.rs
@@ -0,0 +1,223 @@
+//! What the page's display layer reads: plain values, serialised as JSON
+//! by the bridge, one per part of the chrome. The types they carry are
+//! the models' own (`tree::Row`, `navbar::NavView`, `chrome::TabView`),
+//! so the JSON is the model, not a second description of it.
+
+use crate::chrome::{Controls, TabView};
+use crate::navbar::NavView;
+use crate::sidebar::Editing;
+use crate::tree::Row;
+use serde::Serialize;
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct SidebarView {
+ pub rows: Vec<Row>,
+ pub editing: Editing,
+ /// The Space on show, for the page to remember.
+ pub space: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct TabsView {
+ pub tabs: Vec<TabView>,
+ pub controls: Controls,
+}
+
+pub type NavsView = Vec<NavView>;
+
+/// A passing remark (`sticky` while the page is disconnected, where it is
+/// the state rather than a remark), the desktop's takeover card, and the
+/// one-line summary probes read.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct StatusView {
+ pub toast: Option<Toast>,
+ pub card: Option<Card>,
+ pub summary: String,
+}
+
+/// What a menu row's action came to: `copy` is text for the page to put
+/// on the clipboard, `paste` asks the page to read the clipboard.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct MenuOutcome {
+ pub handled: bool,
+ pub copy: Option<String>,
+ pub paste: bool,
+}
+
+/// What a palette pick came to: `page` names something only the page
+/// does (`toggle-sidebar`, `settings`, `lang:<tag>`), `recent` is the
+/// updated list of picks for the page to keep.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct PaletteOutcome {
+ pub handled: bool,
+ pub page: Option<String>,
+ pub recent: Vec<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Toast {
+ pub text: String,
+ pub sticky: bool,
+ /// When it was raised, in the page's monotonic milliseconds.
+ pub at: f64,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Card {
+ pub title: String,
+ pub hint: String,
+}
+
+/// The static labels the page draws itself (tooltips, headers, the
+/// confirmation words), keyed by their catalogue id, in the active locale.
+pub const STRING_KEYS: &[&str] = &[
+ "sidebar-new-thread",
+ "sidebar-pinned",
+ "sidebar-workspaces",
+ "web-sidebar-other-windows",
+ "web-path-placeholder",
+ "web-tip-space",
+ "web-tip-new-thread",
+ "web-tip-new-thread-here",
+ "web-tip-new-project",
+ "web-tip-restore",
+ "web-tip-archive",
+ "web-tip-pin",
+ "web-tip-unpin",
+ "web-tip-delete-thread",
+ "web-confirm-delete",
+ "web-confirm-close",
+ "web-tip-close-pane",
+ "web-tip-close-tab",
+ "web-tip-new-tab",
+ "web-tip-split-down",
+ "web-tip-split-right",
+ "web-tip-zoom",
+ "web-tip-unzoom",
+ "web-tip-sidebar",
+ "web-fitted",
+ "web-tip-fitted",
+ "web-tip-sidebar-options",
+ "tooltip-sidebar-notifications",
+ "tooltip-sidebar-thread-search",
+ "tooltip-sidebar-settings",
+ "web-tip-search",
+ "web-tip-agents",
+ "web-tip-settings",
+ "web-agents-title",
+ "sidebar-settings",
+ "settings-language",
+ "web-settings-theme",
+ "web-theme-dark",
+ "web-theme-light",
+ "web-theme-system",
+ "web-settings-font",
+ "web-font-follow",
+ "web-font-pinned",
+ "web-settings-hover-reveal",
+ "web-settings-agents-panel",
+ "web-settings-palette-hotkey",
+ "web-settings-sidebar-reset",
+ "web-settings-about",
+ "web-settings-close",
+ "language-system",
+ "settings-section-general",
+ "settings-section-appearance",
+ "settings-section-sidebar",
+ "settings-section-agents",
+ "settings-section-about",
+ "web-settings-search",
+ "web-settings-build",
+ "web-settings-language-description",
+ "web-settings-hotkey-description",
+ "web-settings-theme-description",
+ "web-settings-font-description",
+ "web-settings-hover-reveal-description",
+ "web-settings-agents-panel-description",
+ "web-settings-sidebar-reset-description",
+ "web-cmd-font-reset",
+ "common-reset",
+];
+
+pub fn strings() -> std::collections::BTreeMap<&'static str, String> {
+ STRING_KEYS.iter().map(|key| (*key, thinkterm_i18n::tr(key))).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::tree::{Dot, Status, ThreadRow};
+ use serde_json::{json, to_value};
+
+ #[test]
+ fn rows_serialise_as_kinded_objects() {
+ let rows = vec![
+ Row::Space { id: "space-1".into(), name: "Default".into() },
+ Row::NewThread,
+ Row::Thread(ThreadRow {
+ id: "thread-1".into(),
+ project_id: "project-1".into(),
+ name: "main".into(),
+ status: Status::Running,
+ dot: Dot::Active,
+ pinned: false,
+ unread: true,
+ live: true,
+ selected: true,
+ deleting: false,
+ }),
+ Row::Window { window_id: 3, title: "Terminal".into(), selected: false },
+ ];
+ let v = to_value(SidebarView { rows, editing: Editing::Thread("thread-1".into()), space: Some("space-1".into()) }).unwrap();
+ assert_eq!(v["rows"][0], json!({"kind": "space", "id": "space-1", "name": "Default"}));
+ assert_eq!(v["space"], "space-1");
+ assert_eq!(v["rows"][1], json!({"kind": "new-thread"}));
+ let t = &v["rows"][2];
+ assert_eq!(t["kind"], "thread");
+ assert_eq!(t["project"], "project-1");
+ assert_eq!(t["status"], "Running");
+ assert_eq!(t["dot"], "Active");
+ assert_eq!(t["unread"], true);
+ assert_eq!(v["rows"][3], json!({"kind": "window", "id": 3, "title": "Terminal", "selected": false}));
+ assert_eq!(v["editing"], json!({"kind": "thread", "id": "thread-1"}));
+ assert_eq!(to_value(Editing::None).unwrap(), json!({"kind": "none"}));
+ }
+
+ #[test]
+ fn every_page_string_is_defined() {
+ for key in STRING_KEYS {
+ assert!(thinkterm_i18n::has_key(key), "{key}");
+ }
+ assert_eq!(strings()["web-fitted"], "fitted");
+ }
+
+ #[test]
+ fn tabs_and_status_shapes() {
+ let v = to_value(TabsView {
+ tabs: vec![TabView {
+ tab_id: 7,
+ window_id: 0,
+ title: "zsh".into(),
+ label: "Terminal".into(),
+ target: 9,
+ current: true,
+ panes: vec![],
+ }],
+ controls: Controls { following: true, fit: false, closing_tab: Some(7), clipped: Some((80, 24)) },
+ })
+ .unwrap();
+ assert_eq!(v["tabs"][0]["tab"], 7);
+ assert_eq!(v["tabs"][0]["window"], 0);
+ assert_eq!(v["tabs"][0]["target"], 9);
+ assert_eq!(v["controls"], json!({"following": true, "fit": false, "closing": 7, "clipped": [80, 24]}));
+ let s = to_value(StatusView {
+ toast: Some(Toast { text: "hi".into(), sticky: false, at: 12.5 }),
+ card: Some(Card { title: "Terminal is available".into(), hint: "Click or scroll to take control".into() }),
+ summary: "zsh".into(),
+ })
+ .unwrap();
+ assert_eq!(s["toast"]["at"], 12.5);
+ assert_eq!(s["card"]["hint"], "Click or scroll to take control");
+ assert_eq!(to_value(StatusView { toast: None, card: None, summary: String::new() }).unwrap()["card"], serde_json::Value::Null);
+ }
+}