Skip to main content

apalis_tui/
lib.rs

1//! **Most users should not add this crate as a dependency.** Use `apalis-rtui`'s `ui` feature,
2//! which serves this crate's web build for you, or install the standalone terminal client with
3//! `cargo install apalis-tui` and run `apalis-tui --api http://127.0.0.1:8080/api/v1`
4//! (`docs/PLAN.md` §8.4).
5//!
6//! The `apalis-rtui` ratatui dashboard: one codebase, a native terminal binary and a WebAssembly
7//! bundle, both plain HTTP clients of the `apalis-rtui` JSON API. A host application depends on
8//! `apalis-rtui` to mount that API and `ServeUI`, and `ServeUI` already serves this crate's web
9//! build as a static asset (`apalis-rtui/assets/tui-web-dist/`, built once by CI and vendored in,
10//! never rebuilt on a consumer's machine). Reach for the crate itself to work on the dashboard.
11//! Repository: <https://github.com/ngriaznov/apalis-rtui>.
12//!
13//! Every module here compiles and runs on the host target with no feature enabled (`cargo test
14//! -p apalis-tui`), which is what makes it unit- and snapshot-testable without a browser, a wasm
15//! target, or a running server:
16//!
17//! - [`app`]: `App`, the one state machine both backends drive: screens, selection, the
18//!   hit-region mouse model, the confirm dialog, capability-gated actions.
19//! - [`data`]: the [`data::DataSource`] trait a backend implements, the pure `apply_*` functions
20//!   that fold a fetched value into `App`'s data, and the `Compact`-args decode (§7.3).
21//! - [`theme`]: the Phosphor Slate palette and style helpers.
22//! - [`keymap`]: the keyboard reference `App::key` and the Help overlay both read from.
23//! - [`draw`]: one `draw` function per screen.
24//! - [`input`]: backend-agnostic key/mouse event types.
25//! - [`hash`]: the `web` build's `#/<screen>/…` deep-link format, parsed and formatted with no
26//!   `web_sys` dependency so it is unit-tested here on the host target.
27//! - [`backend`]: the `web` (wasm32 + ratzilla) and `native` (crossterm + reqwest) data/event
28//!   loops. See its module docs for the wiring points a backend implementation builds against.
29//!   `native` is a default feature, so `cargo install apalis-tui` builds the terminal client and
30//!   nothing else. `web` is opt-in and only `build-web.sh` asks for it.
31
32#![forbid(unsafe_code)]
33#![warn(missing_docs)]
34#![warn(unreachable_pub)]
35#![warn(missing_debug_implementations)]
36
37pub mod app;
38pub mod backend;
39pub mod data;
40pub mod draw;
41pub mod hash;
42pub mod input;
43pub mod keymap;
44pub mod theme;
45
46pub use app::{Action, App, Origin, PendingAction, Screen, describe_action_outcome};
47pub use data::Data;
48pub use hash::{Route, RouteScreen};
49pub use input::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
50pub use theme::Theme;
51
52/// The wasm module's entry point (`docs/PLAN.md` §3.3): `wasm-bindgen`'s generated JS glue calls
53/// this once the module is instantiated. Building the `[lib]` target as a `cdylib` for
54/// `wasm32-unknown-unknown` with the `web` feature (`build-web.sh`) is what turns this into the
55/// module's real start function. Every other build, native or wasm32 without `web`, never sees
56/// it at all.
57#[cfg(all(target_arch = "wasm32", feature = "web"))]
58#[wasm_bindgen::prelude::wasm_bindgen(start)]
59pub fn start() {
60    backend::web::run_web();
61}
62
63// -------------------------------------------------------------------------------------------
64// Platform shims: wall-clock time, clipboard copy, opening a new tab. wasm32 talks to the
65// browser; every other target (including a plain `cargo test`) is a harmless no-op. `App::now`
66// is driven by `App::with_clock` in tests, never by `now_secs`, so these never affect a
67// deterministic test run.
68// -------------------------------------------------------------------------------------------
69
70#[cfg(target_arch = "wasm32")]
71pub(crate) fn now_secs() -> u64 {
72    (js_sys::Date::now() / 1000.0) as u64
73}
74#[cfg(not(target_arch = "wasm32"))]
75pub(crate) fn now_secs() -> u64 {
76    std::time::SystemTime::now()
77        .duration_since(std::time::UNIX_EPOCH)
78        .map(|d| d.as_secs())
79        .unwrap_or(0)
80}
81
82// `text`/`url` here are user-visible values (a task id, or a `{API}/queues/{q}/tasks/{id}` URL
83// built from a registered queue name) that only pass `apalis-rtui`'s queue-name validation, which
84// rejects `/`, `?`, `#`, whitespace and control characters, not quotes or backslashes. Building a
85// JS source string by interpolation and running it through `js_sys::eval` would let such a value
86// break out of the generated snippet, so both shims call the real `web_sys` bindings instead: the
87// value travels as a genuine `JsValue`/`&str` argument, never as JS source text.
88#[cfg(all(target_arch = "wasm32", feature = "web"))]
89pub(crate) fn copy_to_clipboard(text: &str) {
90    let Some(window) = web_sys::window() else {
91        return;
92    };
93    let promise = window.navigator().clipboard().write_text(text);
94    wasm_bindgen_futures::spawn_local(async move {
95        let _ = wasm_bindgen_futures::JsFuture::from(promise).await;
96    });
97}
98#[cfg(all(target_arch = "wasm32", not(feature = "web")))]
99pub(crate) fn copy_to_clipboard(_text: &str) {}
100// There is no non-wasm32 arm on purpose. A native clipboard write would need a dependency this
101// crate does not carry (`arboard` and an X11/Wayland/macOS link), so `App::act`'s `CopyId` and
102// `RawJson` arms show the value in a toast on native and never call this. A no-op shim here
103// would let a caller write "copied" over a copy that did not happen.
104
105#[cfg(all(target_arch = "wasm32", feature = "web"))]
106pub(crate) fn open_url(url: &str) {
107    if let Some(window) = web_sys::window() {
108        let _ = window.open_with_url_and_target(url, "_blank");
109    }
110}
111#[cfg(all(target_arch = "wasm32", not(feature = "web")))]
112pub(crate) fn open_url(_url: &str) {}
113// No non-wasm32 arm, for the same reason as `copy_to_clipboard` above: a terminal has no browser
114// tab to open, and `App::act`'s `RawJson` arm shows the URL instead of calling this.
115
116// -------------------------------------------------------------------------------------------
117// Time/format helpers shared by `draw`'s screens. No chrono: epoch seconds -> a UTC clock
118// string, since a TUI has no locale-aware formatting concern beyond what these need.
119// -------------------------------------------------------------------------------------------
120
121/// `HH:MM:SS` within the day, from Unix seconds.
122pub(crate) fn hms(secs: u64) -> String {
123    let s = secs % 86_400;
124    format!("{:02}:{:02}:{:02}", s / 3600, (s % 3600) / 60, s % 60)
125}
126
127/// `"N ago"` / `"in N"`, `secs` relative to `now`. Takes `now` explicitly (never reads the wall
128/// clock itself) so `App::ago` can drive it off `App`'s own, possibly pinned, clock and stay
129/// deterministic in tests.
130pub(crate) fn ago_at(secs: u64, now: u64) -> String {
131    if secs > now {
132        return format!("in {}", ago_units(secs - now));
133    }
134    format!("{} ago", ago_units(now - secs))
135}
136
137fn ago_units(d: u64) -> String {
138    if d < 60 {
139        format!("{d} s")
140    } else if d < 3600 {
141        format!("{} min", d / 60)
142    } else if d < 86_400 {
143        format!("{} h", d / 3600)
144    } else {
145        format!("{} d", d / 86_400)
146    }
147}
148
149/// A thousands-grouped decimal, e.g. `1234567` -> `"1 234 567"`.
150pub(crate) fn group(n: u64) -> String {
151    let s = n.to_string();
152    let mut out = String::new();
153    for (i, ch) in s.chars().enumerate() {
154        if i > 0 && (s.len() - i).is_multiple_of(3) {
155            out.push(' ');
156        }
157        out.push(ch);
158    }
159    out
160}
161
162/// An 8-level unicode-block sparkline of `values`, scaled to their own max.
163///
164/// A zero draws as a blank, not as the shortest bar. The Overview's activity series is mostly
165/// zeros on a quiet server, and a row of `▁` there would read as "a little of everything happened
166/// every minute" when nothing did.
167pub(crate) fn spark(values: &[u64]) -> String {
168    const BARS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
169    let max = values.iter().copied().max().unwrap_or(1).max(1);
170    values
171        .iter()
172        .map(|v| {
173            if *v == 0 {
174                ' '
175            } else {
176                BARS[(v.saturating_mul(7) / max) as usize]
177            }
178        })
179        .collect()
180}
181
182/// Truncates to at most `n` chars, replacing the last with `…` when it doesn't fit.
183pub(crate) fn trunc(s: &str, n: usize) -> String {
184    if s.chars().count() <= n {
185        s.to_owned()
186    } else {
187        let mut t: String = s.chars().take(n.saturating_sub(1)).collect();
188        t.push('…');
189        t
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    #[test]
198    fn ago_at_reports_past_and_future() {
199        assert_eq!(ago_at(90, 100), "10 s ago");
200        assert_eq!(ago_at(110, 100), "in 10 s");
201    }
202
203    #[test]
204    fn trunc_appends_ellipsis_only_when_it_overflows() {
205        assert_eq!(trunc("hello", 10), "hello");
206        assert_eq!(trunc("hello world", 5), "hell…");
207    }
208
209    #[test]
210    fn group_inserts_thin_spaces_every_three_digits() {
211        assert_eq!(group(1_234_567), "1 234 567");
212        assert_eq!(group(42), "42");
213    }
214}