diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml
new file mode 100644
index 0000000..f79b3da
--- /dev/null
+++ b/crates/ui/Cargo.toml
@@ -0,0 +1,33 @@
+[package]
+name = "sccache-dash-ui"
+description = "Dashboard page for sccache-dash"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
+sccache-dash-api = { path = "../api" }
+
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+
+# The page is drawn with eframe in the browser for now. A native window would
+# open the same `Dashboard`, and needs eframe here with its x11 and wayland features.
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+eframe = { version = "0.37", default-features = false, features = [
+ "default_fonts",
+ "glow",
+ "persistence",
+] }
+egui_plot = "0.38"
+ehttp = "0.7"
+wasm-bindgen = "0.2"
+wasm-bindgen-futures = "0.4"
+js-sys = "0.3"
+web-sys = { version = "0.3", features = [
+ "Document",
+ "Element",
+ "HtmlAnchorElement",
+ "HtmlCanvasElement",
+ "Window",
+] }
diff --git a/crates/ui/index.html b/crates/ui/index.html
new file mode 100644
index 0000000..a1c9824
--- /dev/null
+++ b/crates/ui/index.html
@@ -0,0 +1,29 @@
+
+
+
+
+
+ sccache dash
+
+
+
+
+
+
+
diff --git a/crates/ui/src/app.rs b/crates/ui/src/app.rs
new file mode 100644
index 0000000..3eb9b04
--- /dev/null
+++ b/crates/ui/src/app.rs
@@ -0,0 +1,606 @@
+//! The dashboard: what it remembers, how it fetches, and the top of the page.
+
+use std::time::Duration;
+
+use eframe::egui;
+use sccache_dash_api::{Range, View};
+
+use crate::fmt;
+use crate::{cards, extras, net, overtime, problems, raw, speed, style, where_went};
+
+/// Refresh intervals offered, in seconds; zero means off.
+const REFRESH_CHOICES: [u64; 4] = [0, 5, 10, 30];
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+enum ThemeChoice {
+ /// Follow the browser's own light or dark setting.
+ Auto,
+ Light,
+ Dark,
+}
+
+impl ThemeChoice {
+ const ALL: [Self; 3] = [Self::Auto, Self::Light, Self::Dark];
+
+ fn name(self) -> &'static str {
+ match self {
+ Self::Auto => "Auto",
+ Self::Light => "Light",
+ Self::Dark => "Dark",
+ }
+ }
+
+ fn preference(self) -> egui::ThemePreference {
+ match self {
+ Self::Auto => egui::ThemePreference::System,
+ Self::Light => egui::ThemePreference::Light,
+ Self::Dark => egui::ThemePreference::Dark,
+ }
+ }
+}
+
+/// What a request in flight is for.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Ask {
+ View,
+ Zero,
+}
+
+/// The whole page. It draws one `View` at a time and keeps the last one on
+/// screen until the next arrives.
+pub struct Dashboard {
+ range: Range,
+ refresh_secs: u64,
+ theme: ThemeChoice,
+ view: Option,
+ pending: Option<(Ask, net::Answer)>,
+ /// Why the last request failed, if it did.
+ error: Option,
+ /// Page time, in seconds, when the last view was asked for.
+ sent_at: Option,
+ /// Languages unticked in the "Over time" filter.
+ hidden_languages: Vec,
+ /// Whether the "Zero stats" question is open.
+ asking_zero: bool,
+ /// A short message for the controls row, and the page time it goes away.
+ note: Option<(String, f64)>,
+ /// Set when the range, refresh interval or theme changed and should be remembered.
+ settings_changed: bool,
+}
+
+impl Dashboard {
+ pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
+ let storage = cc.storage;
+ let dashboard = Self {
+ range: remembered(storage, "range").unwrap_or(Range::Day),
+ refresh_secs: remembered(storage, "refresh").unwrap_or(10),
+ theme: remembered(storage, "theme").unwrap_or(ThemeChoice::Auto),
+ view: None,
+ pending: None,
+ error: None,
+ sent_at: None,
+ hidden_languages: Vec::new(),
+ asking_zero: false,
+ note: None,
+ settings_changed: false,
+ };
+ let ctx = &cc.egui_ctx;
+ ctx.set_theme(dashboard.theme.preference());
+ ctx.all_styles_mut(|style| {
+ style
+ .text_styles
+ .insert(egui::TextStyle::Small, egui::FontId::proportional(11.5));
+ style.spacing.item_spacing = egui::vec2(8.0, 4.0);
+ });
+ dashboard
+ }
+
+ fn now(ctx: &egui::Context) -> f64 {
+ ctx.input(|input| input.time)
+ }
+
+ /// Send a request, replacing any request still in flight.
+ fn send(&mut self, ctx: &egui::Context, ask: Ask) {
+ if ask == Ask::View {
+ self.sent_at = Some(Self::now(ctx));
+ }
+ let request = match ask {
+ Ask::View => net::view(self.range),
+ Ask::Zero => net::zero(),
+ };
+ self.pending = Some((ask, net::Answer::send(request, ctx)));
+ }
+
+ /// Pick up the answer to the request in flight, if it has arrived.
+ fn collect(&mut self, ctx: &egui::Context, now: f64) {
+ if self.note.as_ref().is_some_and(|(_, until)| *until <= now) {
+ self.note = None;
+ }
+ let Some(answer) = self
+ .pending
+ .as_ref()
+ .and_then(|(_, answer)| answer.take())
+ else {
+ return;
+ };
+ let Some((ask, _)) = self.pending.take() else {
+ return;
+ };
+ match ask {
+ Ask::View => match net::view_from(answer) {
+ Ok(view) => {
+ self.view = Some(view);
+ self.error = None;
+ }
+ Err(error) => self.error = Some(error),
+ },
+ Ask::Zero => match net::accepted(answer) {
+ Ok(()) => {
+ self.flash("Stats zeroed", now);
+ self.send(ctx, Ask::View);
+ }
+ Err(error) => self.error = Some(format!("The stats could not be zeroed: {error}")),
+ },
+ }
+ }
+
+ /// Keep asking for a new view at the chosen interval.
+ fn tick(&mut self, ctx: &egui::Context, now: f64) {
+ if self.pending.is_some() {
+ return;
+ }
+ let Some(sent_at) = self.sent_at else {
+ self.send(ctx, Ask::View);
+ return;
+ };
+ if self.refresh_secs == 0 {
+ return;
+ }
+ let every = self.refresh_secs as f64;
+ let since = now - sent_at;
+ if since >= every {
+ self.send(ctx, Ask::View);
+ } else {
+ ctx.request_repaint_after(Duration::from_secs_f64((every - since).max(0.05)));
+ }
+ }
+
+ fn flash(&mut self, text: impl Into, now: f64) {
+ self.note = Some((text.into(), now + 4.0));
+ }
+}
+
+impl eframe::App for Dashboard {
+ /// Runs before every frame, also while the window is hidden: pick up answers and keep asking.
+ fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
+ let now = Self::now(ctx);
+ self.collect(ctx, now);
+ self.tick(ctx, now);
+ }
+
+ fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
+ controls(self, ui);
+ egui::CentralPanel::default().show(ui, |ui| {
+ egui::ScrollArea::vertical()
+ .auto_shrink([false; 2])
+ .show(ui, |ui| {
+ ui.add_space(8.0);
+ let Self {
+ range,
+ view,
+ error,
+ hidden_languages,
+ ..
+ } = self;
+ match view {
+ None => waiting(ui, error.as_deref(), self.refresh_secs),
+ Some(view) => {
+ page(ui, view, *range, error.as_deref(), hidden_languages)
+ }
+ }
+ });
+ });
+
+ if self.asking_zero {
+ zero_question(self, ui.ctx());
+ }
+ if self.settings_changed {
+ if let Some(storage) = frame.storage_mut() {
+ remember(self, storage);
+ }
+ self.settings_changed = false;
+ }
+ }
+
+ /// Remember the range, refresh interval and theme when the page is closed.
+ fn save(&mut self, storage: &mut dyn eframe::Storage) {
+ remember(self, storage);
+ }
+}
+
+/// Put the range, refresh interval and theme into the storage eframe keeps between visits.
+fn remember(dashboard: &Dashboard, storage: &mut dyn eframe::Storage) {
+ eframe::set_value(storage, "range", &dashboard.range);
+ eframe::set_value(storage, "refresh", &dashboard.refresh_secs);
+ eframe::set_value(storage, "theme", &dashboard.theme);
+}
+
+fn remembered(
+ storage: Option<&dyn eframe::Storage>,
+ key: &str,
+) -> Option {
+ storage.and_then(|storage| eframe::get_value(storage, key))
+}
+
+/// The row of controls that stays at the top of the page.
+fn controls(dashboard: &mut Dashboard, ui: &mut egui::Ui) {
+ let ctx = ui.ctx().clone();
+ let now = Dashboard::now(&ctx);
+ egui::Panel::top("controls").show(ui, |ui| {
+ ui.add_space(6.0);
+ ui.horizontal_wrapped(|ui| {
+ for range in Range::ALL {
+ if ui
+ .add(egui::Button::selectable(
+ dashboard.range == range,
+ range.code(),
+ ))
+ .clicked()
+ {
+ dashboard.range = range;
+ dashboard.settings_changed = true;
+ dashboard.send(&ctx, Ask::View);
+ }
+ }
+
+ ui.add_space(8.0);
+ let mut refresh_secs = dashboard.refresh_secs;
+ egui::ComboBox::from_id_salt("refresh")
+ .selected_text(fmt::refresh_label(refresh_secs))
+ .show_ui(ui, |ui| {
+ for secs in REFRESH_CHOICES {
+ ui.selectable_value(&mut refresh_secs, secs, fmt::refresh_label(secs));
+ }
+ });
+ if refresh_secs != dashboard.refresh_secs {
+ dashboard.refresh_secs = refresh_secs;
+ dashboard.settings_changed = true;
+ }
+ if ui.button("Refresh").clicked() {
+ dashboard.send(&ctx, Ask::View);
+ }
+
+ ui.add_space(8.0);
+ for theme in ThemeChoice::ALL {
+ if ui
+ .add(egui::Button::selectable(dashboard.theme == theme, theme.name()))
+ .clicked()
+ {
+ dashboard.theme = theme;
+ dashboard.settings_changed = true;
+ ctx.set_theme(theme.preference());
+ }
+ }
+
+ ui.add_space(8.0);
+ let online = dashboard.view.is_some();
+ let copy = ui.add_enabled(online, egui::Button::new("Copy summary"));
+ if copy.clicked() {
+ if let Some(view) = &dashboard.view {
+ ctx.copy_text(view.summary_markdown.clone());
+ }
+ dashboard.flash("Summary copied", now);
+ }
+ let export = ui.add_enabled(online, egui::Button::new("Export JSON"));
+ if export.clicked() {
+ let note = net::download("/api/export").map_or_else(
+ |error| format!("Export failed: {error}"),
+ |()| "Export started".to_owned(),
+ );
+ dashboard.flash(note, now);
+ }
+ let zeroing = dashboard
+ .pending
+ .as_ref()
+ .is_some_and(|(ask, _)| *ask == Ask::Zero);
+ let zero = ui.add_enabled(online && !zeroing, egui::Button::new("Zero stats"));
+ if zero.clicked() {
+ dashboard.asking_zero = true;
+ }
+
+ // A fixed-size slot, so that messages come and go without moving the controls.
+ ui.add_space(8.0);
+ ui.allocate_ui_with_layout(
+ egui::vec2(120.0, 20.0),
+ egui::Layout::left_to_right(egui::Align::Center),
+ |ui| {
+ if dashboard
+ .pending
+ .as_ref()
+ .is_some_and(|(ask, _)| *ask == Ask::View)
+ {
+ ui.spinner();
+ ui.label(egui::RichText::new("Updating").small());
+ } else if let Some((note, _)) = &dashboard.note {
+ ui.add(egui::Label::new(egui::RichText::new(note).small()).truncate());
+ }
+ },
+ );
+ });
+ ui.add_space(6.0);
+ });
+}
+
+/// Ask before zeroing: it can't be undone.
+fn zero_question(dashboard: &mut Dashboard, ctx: &egui::Context) {
+ let modal = egui::Modal::new(egui::Id::unique("zero-stats-question")).show(ctx, |ui| {
+ ui.set_max_width(360.0);
+ ui.label(egui::RichText::new("Zero sccache's stats?").strong());
+ ui.add(egui::Label::new(
+ "The counters go back to zero. The saved history stays, so the charts keep their \
+ older data. This can't be undone.",
+ ).wrap());
+ ui.horizontal(|ui| {
+ if ui.button("Zero stats").clicked() {
+ Some(true)
+ } else if ui.button("Cancel").clicked() {
+ Some(false)
+ } else {
+ None
+ }
+ })
+ .inner
+ });
+ let answer = modal.inner;
+ if modal.should_close() || answer == Some(false) {
+ dashboard.asking_zero = false;
+ }
+ if answer == Some(true) {
+ dashboard.asking_zero = false;
+ dashboard.send(ctx, Ask::Zero);
+ }
+}
+
+/// What the page says while no view has arrived yet.
+fn waiting(ui: &mut egui::Ui, error: Option<&str>, refresh_secs: u64) {
+ let [_, _, bad] = style::marks(ui.visuals().dark_mode);
+ let retry = if refresh_secs > 0 {
+ format!("Trying again every {refresh_secs} seconds.")
+ } else {
+ "Press Refresh to try again.".to_owned()
+ };
+ let (heading, body, color) = match error {
+ Some(error) => (
+ "Can't reach the server".to_owned(),
+ format!(
+ "{error}.\n\nCheck that sccache-dash is running on this machine. {retry}"
+ ),
+ bad,
+ ),
+ None => (
+ "Waiting for the first figures".to_owned(),
+ "Asking the server for your cache numbers.".to_owned(),
+ ui.visuals().text_color(),
+ ),
+ };
+ // The same height the headline and cards take, so the page doesn't jump when they arrive.
+ ui.allocate_ui_with_layout(
+ egui::vec2(ui.available_rect_before_wrap().width(), 250.0),
+ egui::Layout::centered_and_justified(egui::Direction::TopDown),
+ |ui| {
+ ui.vertical(|ui| {
+ ui.label(egui::RichText::new(heading).size(20.0).color(color));
+ ui.add(egui::Label::new(body).wrap());
+ });
+ },
+ );
+}
+
+/// The whole page below the controls.
+fn page(
+ ui: &mut egui::Ui,
+ view: &View,
+ asked: Range,
+ error: Option<&str>,
+ hidden_languages: &mut Vec,
+) {
+ let dark = ui.visuals().dark_mode;
+ let [_, _, bad] = style::marks(dark);
+ if let Some(error) = error {
+ let from = fmt::moment_text(view.generated_at + fmt::local_offset());
+ style::banner(
+ ui,
+ format!("Lost contact with the server: {error}. These figures are from {from}."),
+ bad,
+ );
+ }
+ if let Some(error) = &view.server.error {
+ style::banner(ui, format!("sccache is not working: {error}"), bad);
+ }
+ headline(ui, view, asked, dark);
+ ui.add_space(10.0);
+ cards::row(ui, view, dark);
+ problems::section(ui, view, dark);
+ where_went::section(ui, view, dark);
+ overtime::section(ui, view, hidden_languages, dark);
+ speed::section(ui, view);
+ extras::section(ui, view);
+ raw::section(ui, view);
+ ui.add_space(12.0);
+}
+
+/// One of the three big figures.
+struct Figure<'a> {
+ value: String,
+ color: egui::Color32,
+ caption: String,
+ /// Smaller print under the figure.
+ small: String,
+ /// A second line of smaller print, kept so the block's height never changes.
+ small2: String,
+ /// A trend line and the value it is drawn against.
+ trend: Option<(&'a [Option], f64)>,
+ hover: Option,
+}
+
+impl Figure<'_> {
+ /// Draw in a column `width` wide and always the same height.
+ fn draw(self, ui: &mut egui::Ui, width: f32) {
+ let gap = ui.spacing().item_spacing.y;
+ let block = ui.allocate_ui_with_layout(
+ egui::vec2(width, FIGURE_HEIGHT),
+ egui::Layout::top_down(egui::Align::Min),
+ |ui| {
+ ui.set_width(width);
+ ui.add(
+ egui::Label::new(egui::RichText::new(&self.value).size(30.0).color(self.color))
+ .truncate(),
+ );
+ ui.add(egui::Label::new(egui::RichText::new(&self.caption).small()).truncate());
+ match self.trend {
+ Some((values, top)) => style::sparkline(ui, TREND_HEIGHT, values, top, self.color),
+ None => ui.add_space(TREND_HEIGHT + gap),
+ }
+ ui.add(egui::Label::new(egui::RichText::new(&self.small).small().weak()).truncate());
+ ui.add(egui::Label::new(egui::RichText::new(&self.small2).small().weak()).truncate());
+ },
+ );
+ if let Some(hover) = self.hover {
+ block.response.on_hover_text(hover);
+ }
+ }
+}
+
+const TREND_HEIGHT: f32 = 22.0;
+const FIGURE_HEIGHT: f32 = 120.0;
+
+/// The big numbers, what they mean, and where the cache lives.
+fn headline(ui: &mut egui::Ui, view: &View, asked: Range, dark: bool) {
+ let range = view.range.unwrap_or(asked);
+ let totals = &view.totals;
+ let text_color = ui.visuals().text_color();
+
+ let rates: Vec