diff --git a/crates/ledger-gui/src/app.rs b/crates/ledger-gui/src/app.rs index 8e14ceb8..5acfdb71 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -22,7 +22,8 @@ //! 4. What is kept for next time: the open companies (`open_companies`, //! the ids of their books, comma separated) and the one in front //! (`active_company`); for each company its page, its report's -//! period, columns and comparison (`company..…`); and, as +//! period, columns and comparison and its name as last known +//! (`company..…`); and, as //! before and under the same keys, the scheme and its filter //! (`scheme`, `scheme_filter`, `dark`) and the dock (`dock_open`, //! `dock_agent`, the front tab's). @@ -35,7 +36,7 @@ use crate::company::CompanyView; use crate::data::Source; use crate::nav::Route; use crate::scheme_menu::SchemeMenu; -use crate::tabs::{Tab, TabAction, TabBar}; +use crate::tabs::{Listed, Tab, TabAction, TabBar}; use crate::theme::{self, pal}; use egui::{Frame, RichText, Ui}; use std::collections::HashMap; @@ -73,6 +74,10 @@ pub struct App { /// What was kept for companies not open now (and for those that are, /// as they were last closed), by key. kept: HashMap, + /// Each company's name as last known, by the id of its books: kept for + /// the tab's title before the books load and for the "+" list, which + /// doesn't read every company's journal for it. + names: HashMap, /// The dock's preferences as they were kept, for a dock made while no /// tab has one. dock_prefs: (Option, Option), @@ -223,6 +228,7 @@ impl App { root: None, today: None, kept: HashMap::new(), + names: HashMap::new(), dock_prefs: (None, None), title: TITLE.to_string(), welcome: None, @@ -269,7 +275,7 @@ impl App { /// The window's title now. pub fn window_title(&self) -> String { match self.active_view() { - Some(v) => format!("{} · {TITLE}", v.title()), + Some(v) => format!("{} · {TITLE}", self.title_of(v)), None => TITLE.to_string(), } } @@ -356,6 +362,9 @@ impl App { return; }; for id in list_books(&root) { + if let Some(name) = get(&format!("company.{id}.name")) { + self.names.insert(id.clone(), name); + } for k in crate::company::KEPT_KEYS { let key = format!("company.{id}.{k}"); if let Some(v) = get(&key) { @@ -383,20 +392,55 @@ impl App { } } - /// The ids of the data root's companies that aren't open. - fn not_open(&self) -> impl Fn() -> Vec + use<> { + /// The data root's companies that aren't open, with the names last + /// known (reading the ids is all it does). + fn not_open(&self) -> impl Fn() -> Vec + use<> { let root = self.root.clone(); let open: Vec = self.views.iter().filter_map(CompanyView::book_id).collect(); + let names = self.names.clone(); move || { root.as_deref() .map(list_books) .unwrap_or_default() .into_iter() .filter(|id| !open.contains(id)) + .map(|id| Listed { + name: names.get(&id).cloned(), + id, + }) .collect() } } + /// Note the name of every company whose books are loaded. + fn learn_names(&mut self) { + for v in &self.views { + if let (Some(id), Some(name)) = (v.book_id(), v.name()) + && self.names.get(&id) != Some(&name) + { + self.names.insert(id, name); + } + } + } + + /// The name last known for the company with books `id` (tests). + pub fn remembered_name(&self, id: &str) -> Option<&str> { + self.names.get(id).map(String::as_str) + } + + /// A view's tab title: the name its books carry, else the name last + /// known, else the id. + fn title_of(&self, v: &CompanyView) -> String { + v.name() + .or_else(|| self.names.get(&v.book_id()?).cloned()) + .unwrap_or_else(|| v.title()) + } + + /// Tab `i`'s title as the bar shows it (tests). + pub fn tab_title(&self, i: usize) -> Option { + self.views.get(i).map(|v| self.title_of(v)) + } + /// Do what the tab bar was asked. fn act(&mut self, ctx: &egui::Context, action: TabAction) { match action { @@ -561,30 +605,30 @@ impl eframe::App for App { for (i, v) in self.views.iter_mut().enumerate() { v.pump(&ctx, i == self.active); } + self.learn_names(); let tabs: Vec = self .views .iter() - .map(|v| Tab { - title: v.title(), - detail: v.book_id().unwrap_or_else(|| v.title()), + .map(|v| { + let title = self.title_of(v); + Tab { + detail: match v.book_id() { + Some(id) if id != title => format!("{title}\n{id}"), + _ => title.clone(), + }, + title, + } }) .collect(); let shown = self.active(); let others = self.not_open(); - let mut action = None; - // The bar goes where the front view says (beside its sidebar, which - // keeps the window's whole height), or across the window when - // there is no view. - let mut bar = |ui: &mut Ui| { - action = self.tabs.show(ui, &tabs, shown, &others); - }; + // The bar goes across the whole window, above everything of the + // company in front: a tab is the top level (D-78). + let action = self.tabs.show(ui, &tabs, shown, &others); let active = self.active; match self.views.get_mut(active) { - Some(v) => v.ui(ui, &mut self.schemes, &mut bar), - None => { - bar(ui); - self.empty(ui); - } + Some(v) => v.ui(ui, &mut self.schemes), + None => self.empty(ui), } if let Some(action) = action { self.act(&ctx, action); @@ -634,6 +678,9 @@ impl eframe::App for App { for (k, v) in &self.kept { storage.set_string(k, v.clone()); } + for (id, name) in &self.names { + storage.set_string(&format!("company.{id}.name"), name.clone()); + } for v in &self.views { if let Some(id) = v.book_id() { v.keep(&mut |k, val| storage.set_string(&format!("company.{id}.{k}"), val)); diff --git a/crates/ledger-gui/src/company.rs b/crates/ledger-gui/src/company.rs index 5ced75c5..ca3057ed 100644 --- a/crates/ledger-gui/src/company.rs +++ b/crates/ledger-gui/src/company.rs @@ -34,9 +34,7 @@ use crate::receipts::Receipts; use crate::scheme_menu::SchemeMenu; use crate::schemes; use crate::theme::{self, pal}; -use egui::{ - Align, CornerRadius, Frame, Key, Layout, Margin, RichText, Sense, Stroke, Ui, UiBuilder, vec2, -}; +use egui::{Align, CornerRadius, Frame, Key, Layout, Margin, RichText, Sense, Stroke, Ui, vec2}; use egui_phosphor::regular as icon; use std::sync::Arc; @@ -191,15 +189,19 @@ impl CompanyView { .flatten() } + /// The name the books carry, once they are loaded (and it isn't + /// blank). + pub fn name(&self) -> Option { + self.books + .as_ref() + .map(|b| b.company_name().trim().to_string()) + .filter(|n| !n.is_empty()) + } + /// The tab's title: the name the books carry, else the id of the /// books, else the folder's name. pub fn title(&self) -> String { - let named = self - .books - .as_ref() - .map(|b| b.company_name().trim().to_string()) - .filter(|n| !n.is_empty()); - named + self.name() .or_else(|| self.book_id()) .or_else(|| { let dir = self.data_dir.as_deref()?; @@ -350,28 +352,19 @@ impl CompanyView { /// The window: the sidebar, the top bar, the dock and the page, with /// every id in them scoped to this view (INVARIANT 2). /// - /// `bar` draws the app's tab bar. It goes where the sidebar has already - /// taken its column and nothing else has been laid out: along the top - /// of the rest of the window, so the sidebar keeps all the height the - /// owner's window gives it (`tests/sidenav.rs`), and in a scope of its - /// own, so the bar's ids are the app's and not this view's. - pub fn ui(&mut self, ui: &mut Ui, schemes: &mut SchemeMenu, bar: &mut dyn FnMut(&mut Ui)) { + /// The app's tab bar is already across the top of `ui` (`tabs.rs`): + /// this window is what is below it, and the sidebar's height is the + /// window's less the bar's (`tests/sidenav.rs` adds the bar's height + /// to the windows it sizes). + pub fn ui(&mut self, ui: &mut Ui, schemes: &mut SchemeMenu) { let id = self.id; - ui.push_id(id, |ui| self.window(ui, schemes, bar)); + ui.push_id(id, |ui| self.window(ui, schemes)); } - fn window(&mut self, ui: &mut Ui, schemes: &mut SchemeMenu, bar: &mut dyn FnMut(&mut Ui)) { + fn window(&mut self, ui: &mut Ui, schemes: &mut SchemeMenu) { self.handle_keys(ui); let compact = ui.available_width() < COMPACT_BELOW; self.sidebar(ui, schemes, compact); - // No space between the bar and what follows it (the scope's - // advance would add the item spacing: a strip of bare window). - let spacing = std::mem::take(&mut ui.spacing_mut().item_spacing); - ui.scope_builder( - UiBuilder::new().id(egui::Id::new("company_tab_bar")), - |ui| bar(ui), - ); - ui.spacing_mut().item_spacing = spacing; self.topbar(ui); self.draw_dock(ui); let p = pal(ui.ctx()); diff --git a/crates/ledger-gui/src/lib.rs b/crates/ledger-gui/src/lib.rs index b3b57a33..1ae01eb4 100644 --- a/crates/ledger-gui/src/lib.rs +++ b/crates/ledger-gui/src/lib.rs @@ -22,7 +22,7 @@ mod prefs; mod receipts; mod scheme_menu; mod schemes; -mod tabs; +pub mod tabs; #[cfg(test)] mod test_support; mod theme; @@ -140,8 +140,9 @@ pub fn run( .with_app_id("wanderbooks") .with_inner_size([1440.0, 920.0]) // Small on purpose: tiling window managers hand out small slots - // regardless, and every screen lays itself out to fit. - .with_min_inner_size([360.0, 400.0]), + // regardless, and every screen lays itself out to fit. The + // height is the window's below the tab bar (tabs::BAR_H). + .with_min_inner_size([360.0, 400.0 + tabs::BAR_H]), // The platform's place for app settings, never the books' folder // (prefs.rs). persistence_path: prefs::prepare(), diff --git a/crates/ledger-gui/src/tabs.rs b/crates/ledger-gui/src/tabs.rs index bb7a1e34..dac88a7f 100644 --- a/crates/ledger-gui/src/tabs.rs +++ b/crates/ledger-gui/src/tabs.rs @@ -7,6 +7,12 @@ //! points); with no company open there is no sidebar and it runs the whole //! width. //! +//! The bar spans the whole window, above the sidebar: a tab is the top +//! level, and the sidebar (its company badge, its pages, its status) is +//! the company in the tab's, which the layout shows. With no company open +//! it is the window's top all the same. The "+" follows the last tab, and +//! stays at the right edge, whole, while the tabs scroll. +//! //! ```text //! GOAL: a person has several companies open at once, each in its own //! tab, and moves between them, opens and closes them, without @@ -16,8 +22,9 @@ //! company is reachable exactly while it has a tab). //! INVARIANTS: //! 1. One tab per open company, in the order opened, showing the -//! company's name (the id of its books until the name is read). The -//! bar is there with one company open, and with none. +//! company's badge (as the sidebar's header draws it, small) and +//! name (the name last known, else the id of its books, until it is +//! read). The bar is there with one company open, and with none. //! 2. The tab shown is marked by more than colour: a heavier name, a //! bar in the accent colour along its top edge, and "selected" to //! assistive technology. @@ -25,12 +32,15 @@ //! technology with the company's name; a middle click on a tab //! closes it as well. //! 4. "+" lists only companies of the data root that are not open -//! (a company can't be opened twice), and says so when there are -//! none. -//! 5. Tabs never overlap or leave the bar: they shrink to a least -//! width, then the strip scrolls, with a step control at each end -//! that is clipped; the tab shown is scrolled into view when it -//! changes. +//! (a company can't be opened twice), by name with the id of the +//! books beside it (the id alone for a company never opened), and +//! says so when there are none. +//! 5. Tabs never overlap or leave the bar: each is as wide as its +//! content between a least and a greatest width (a longer name is +//! cut, whole in its hover text), then the strip scrolls, with a +//! step control at each end; the tab shown is scrolled into view +//! when it changes. Each tab leaves room left of its close control +//! for a state mark (drawn by a later unit, nothing now). //! 6. This only says what was asked (show, close, open); the app does //! it. //! ``` @@ -42,13 +52,30 @@ use egui::{ use egui_phosphor::regular as icon; use std::time::{Duration, Instant}; -/// The bar's height. +/// The bar's height: what the bar takes from the window, which the tests +/// of the sidebar's fit add to their window heights (D-78). pub const BAR_H: f32 = 36.0; /// A tab's widest and least widths (a name is cut with an ellipsis to fit). -const TAB_MAX: f32 = 220.0; -const TAB_MIN: f32 = 120.0; +const TAB_MAX: f32 = 240.0; +const TAB_MIN: f32 = 110.0; /// The close control's size. const CLOSE: f32 = 20.0; +/// The badge's size, and its gap to the name. +const BADGE: f32 = 18.0; +const GAP: f32 = 8.0; +/// Room left of the close control for the connection state, which a later +/// unit draws there. +const STATE_W: f32 = 14.0; +/// The room round a tab's content: left and right. +const PAD_L: f32 = 10.0; +const PAD_R: f32 = 6.0; +/// The "+"'s width, and the gap before it. +const PLUS_W: f32 = 30.0; +const PLUS_GAP: f32 = 6.0; +/// The "+" list's width. +const LIST_W: f32 = 260.0; +/// The gap between tabs. +const TAB_GAP: f32 = 2.0; /// How long a reading of the data root's companies is kept while "+" is /// open. const LIST_KEPT: Duration = Duration::from_millis(750); @@ -61,6 +88,15 @@ pub struct Tab { pub detail: String, } +/// A company of the data root that is not open, as "+" lists it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Listed { + /// The id of its books. + pub id: String, + /// Its name as last known, if it was ever opened here. + pub name: Option, +} + /// What a person asked of the bar. #[derive(Clone, Debug, PartialEq, Eq)] pub enum TabAction { @@ -77,7 +113,7 @@ pub enum TabAction { #[derive(Default)] pub struct TabBar { reveal: bool, - listed: Option<(Instant, Vec)>, + listed: Option<(Instant, Vec)>, } impl TabBar { @@ -86,15 +122,16 @@ impl TabBar { self.reveal = true; } - /// The bar. `shown` is the tab in front, if there is one; `others` - /// reads the ids of the root's companies that are not open (called - /// now and then while "+" is open, never otherwise). + /// The bar, across the top of the window. `shown` is the tab in + /// front, if there is one; `others` reads the companies of the root + /// that are not open (called now and then while "+" is open, never + /// otherwise). pub fn show( &mut self, ui: &mut Ui, tabs: &[Tab], shown: Option, - others: &dyn Fn() -> Vec, + others: &dyn Fn() -> Vec, ) -> Option { let p = pal(ui.ctx()); let mut action = None; @@ -102,19 +139,27 @@ impl TabBar { egui::Panel::top("company_tabs") .exact_size(BAR_H) .resizable(false) - .frame( - Frame::new() - .fill(p.sidebar) - .inner_margin(Margin::symmetric(8, 0)) - .stroke(Stroke::new(1.0, p.border)), - ) + .frame(Frame::new().inner_margin(Margin::symmetric(8, 0))) .show(ui, |ui| { - ui.spacing_mut().item_spacing = vec2(2.0, 0.0); + ui.spacing_mut().item_spacing = vec2(TAB_GAP, 0.0); let bar = ui.max_rect(); - // The "+" at the right end, always whole; the tabs get the - // rest. - let plus_w = 30.0; - let strip_w = (ui.available_width() - plus_w - 6.0).max(0.0); + // The line along the bar's foot; the tab in front covers + // it, and so is one with what is below. + let outer = ui.clip_rect(); + ui.painter().rect_filled(outer, 0.0, p.sidebar); + ui.painter().hline( + outer.x_range(), + outer.bottom() - 0.5, + Stroke::new(1.0, p.border), + ); + // The tabs as wide as they are, the "+" right after them; + // when they don't fit, the "+" stays at the right edge + // and the tabs scroll. + let widths: Vec = tabs.iter().map(|t| tab_width(ui, t)).collect(); + let total: f32 = + widths.iter().sum::() + widths.len().saturating_sub(1) as f32 * TAB_GAP; + let room = (ui.available_width() - PLUS_W - PLUS_GAP).max(0.0); + let strip_w = total.min(room); let strip = egui::Rect::from_min_size(bar.min, vec2(strip_w, bar.height())); let mut strip_ui = ui.new_child( UiBuilder::new() @@ -122,10 +167,18 @@ impl TabBar { .layout(Layout::left_to_right(Align::Max)), ); strip_ui.set_clip_rect(strip); - self.strip(&mut strip_ui, tabs, shown, &mut reveal, &mut action); + self.strip( + &mut strip_ui, + tabs, + &widths, + total > room + 0.5, + shown, + &mut reveal, + &mut action, + ); let plus = egui::Rect::from_min_size( - egui::pos2(strip.right() + 6.0, bar.top()), - vec2(plus_w, bar.height()), + egui::pos2(strip.right() + PLUS_GAP, bar.top()), + vec2(PLUS_W, bar.height()), ); let mut plus_ui = ui.new_child( UiBuilder::new() @@ -143,28 +196,29 @@ impl TabBar { } /// The tabs, scrolling sideways when they don't fit. + #[allow(clippy::too_many_arguments)] fn strip( &mut self, ui: &mut Ui, tabs: &[Tab], + widths: &[f32], + overflows: bool, shown: Option, reveal: &mut bool, action: &mut Option, ) { let p = pal(ui.ctx()); let room = ui.available_width(); - let n = tabs.len().max(1) as f32; - let each = ((room - (n - 1.0) * 2.0) / n).clamp(TAB_MIN, TAB_MAX); - let overflows = each * n + (n - 1.0) * 2.0 > room + 0.5; // A step control at each end while the tabs overflow. let step_w = if overflows { 22.0 } else { 0.0 }; + let step_by = widths.first().copied().unwrap_or(TAB_MIN) + TAB_GAP; let area_id = ui.id().with("tab_scroll"); let mut step = 0.0_f32; if overflows { let (r, resp) = ui.allocate_exact_size(vec2(step_w, 26.0), Sense::click()); step_button(ui, r, &resp, icon::CARET_LEFT, "Earlier tabs"); if resp.clicked() { - step = -each; + step = -step_by; } } let view_w = room - 2.0 * step_w; @@ -178,11 +232,11 @@ impl TabBar { .max_width(view_w.max(0.0)) .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden) .show(ui, |ui| { - ui.spacing_mut().item_spacing.x = 2.0; + ui.spacing_mut().item_spacing.x = TAB_GAP; ui.horizontal_top(|ui| { for (i, tab) in tabs.iter().enumerate() { let here = shown == Some(i); - let r = one_tab(ui, i, tab, here, each, &p, action); + let r = one_tab(ui, i, tab, here, widths[i], &p, action); if here && *reveal { r.scroll_to_me(Some(Align::Center)); *reveal = false; @@ -197,7 +251,7 @@ impl TabBar { step_button(ui, r, &resp, icon::CARET_RIGHT, "Later tabs"); if resp.clicked() { let mut s = out.state; - s.offset.x = (offset + each).min(max); + s.offset.x = (offset + step_by).min(max); s.store(ui.ctx(), out.id); } } @@ -210,16 +264,16 @@ impl TabBar { fn plus( &mut self, ui: &mut Ui, - others: &dyn Fn() -> Vec, + others: &dyn Fn() -> Vec, action: &mut Option, ) { let p = pal(ui.ctx()); - let button = egui::Button::new(RichText::new(icon::PLUS).size(16.0).color(p.muted)) + let button = egui::Button::new(RichText::new(icon::PLUS).size(16.0).color(p.text)) .frame(false) .min_size(vec2(28.0, 28.0)); let (response, open) = egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| { - ui.set_min_width(200.0); + ui.set_min_width(LIST_W); let stale = self .listed .as_ref() @@ -231,11 +285,11 @@ impl TabBar { let list = self .listed .as_ref() - .map(|(_, l)| l.as_slice()) - .unwrap_or(&[]); + .map(|(_, l)| l.clone()) + .unwrap_or_default(); if list.is_empty() { ui.label( - RichText::new("Every company here is open.") + RichText::new("Every company is already open.") .font(theme::regular(13.0)) .color(p.muted), ); @@ -245,9 +299,9 @@ impl TabBar { .font(theme::regular(12.0)) .color(p.muted), ); - for id in list { - if ui.button(id).clicked() { - *action = Some(TabAction::Open(id.clone())); + for c in &list { + if listed_row(ui, c, &p).clicked() { + *action = Some(TabAction::Open(c.id.clone())); ui.close(); } } @@ -257,13 +311,54 @@ impl TabBar { if open.is_none() { self.listed = None; } + // Named as it always was for assistive technology; the hover says + // what it does. response.widget_info(|| { egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Open another company") }); - response.on_hover_text("Open another company"); + response.on_hover_text("Open a company"); } } +/// One company in the "+" list: its name, the id of its books beside it +/// in small text (the id alone when the name was never known). +fn listed_row(ui: &mut Ui, c: &Listed, p: &theme::Palette) -> egui::Response { + let (rect, resp) = ui.allocate_exact_size(vec2(LIST_W, 28.0), Sense::click()); + let primary = c.name.as_deref().unwrap_or(&c.id); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, primary)); + if resp.hovered() { + ui.painter() + .rect_filled(rect, CornerRadius::same(6), p.hover); + } + let mut right = rect.right() - 8.0; + if c.name.is_some() { + let g = ui + .painter() + .layout_no_wrap(c.id.clone(), theme::regular(11.0), p.muted); + right -= g.size().x; + ui.painter().galley( + egui::pos2(right, rect.center().y - g.size().y / 2.0), + g, + p.muted, + ); + } + let mut job = egui::text::LayoutJob::single_section( + primary.to_string(), + egui::TextFormat::simple(theme::regular(13.0), p.text), + ); + job.wrap.max_width = (right - 8.0 - (rect.left() + 8.0)).max(10.0); + job.wrap.max_rows = 1; + job.wrap.break_anywhere = true; + job.wrap.overflow_character = Some('…'); + let g = ui.painter().layout_job(job); + ui.painter().galley( + egui::pos2(rect.left() + 8.0, rect.center().y - g.size().y / 2.0), + g, + p.text, + ); + resp +} + /// A step control at an end of the strip. fn step_button(ui: &Ui, r: egui::Rect, resp: &egui::Response, glyph: &str, label: &'static str) { let p = pal(ui.ctx()); @@ -280,6 +375,22 @@ fn step_button(ui: &Ui, r: egui::Rect, resp: &egui::Response, glyph: &str, label ); } +/// What a tab holds besides its name: the badge, the room for the state +/// mark, the close control and the room round them. +const TAB_FIXED: f32 = PAD_L + BADGE + GAP + GAP + STATE_W + CLOSE + PAD_R; + +/// A tab's width: its content's, between the least and the greatest. The +/// name is measured in the heavier face for every tab, so the tab in front +/// doesn't move the others. +fn tab_width(ui: &Ui, tab: &Tab) -> f32 { + let g = ui.painter().layout_no_wrap( + tab.title.clone(), + theme::semibold(13.0), + egui::Color32::PLACEHOLDER, + ); + (TAB_FIXED + g.size().x.ceil()).clamp(TAB_MIN, TAB_MAX) +} + /// One tab, `width` wide. fn one_tab( ui: &mut Ui, @@ -290,12 +401,12 @@ fn one_tab( p: &theme::Palette, action: &mut Option, ) -> egui::Response { - let height = BAR_H - 6.0; + let height = BAR_H - 4.0; let (rect, resp) = ui.allocate_exact_size(vec2(width, height), Sense::click()); // The tab's own id for its close control: tabs are told apart by // their place, and two tabs never share one. let close_rect = egui::Rect::from_center_size( - egui::pos2(rect.right() - 6.0 - CLOSE / 2.0, rect.center().y), + egui::pos2(rect.right() - PAD_R - CLOSE / 2.0, rect.center().y), vec2(CLOSE, CLOSE), ); let close = ui.interact(close_rect, resp.id.with("close"), Sense::click()); @@ -317,47 +428,62 @@ fn one_tab( sw: 0, se: 0, }; - let fill = if here { - Some(p.bg) - } else if resp.hovered() || close.hovered() { - Some(p.hover) - } else { - None - }; - if let Some(fill) = fill { - painter.rect_filled(rect, top, fill); - } if here { - // A bar along the top edge and the page's own fill: the tab - // in front is part of the page below it. - painter.rect_filled( - egui::Rect::from_min_size(rect.min, vec2(rect.width(), 3.0)), - CornerRadius { - nw: 8, - ne: 8, - sw: 0, - se: 0, - }, - p.accent, + // The lit tab: the page's surface, outlined on its top and + // sides, open at the foot where it meets what is below, with a + // bar in the accent colour along its top edge. + painter.rect_filled(rect, top, p.surface); + painter.rect_stroke( + rect, + top, + Stroke::new(1.0, p.border), + egui::StrokeKind::Inside, ); painter.rect_filled( egui::Rect::from_min_max( - egui::pos2(rect.left(), rect.bottom() - 1.0), - egui::pos2(rect.right(), rect.bottom() + 1.0), + egui::pos2(rect.left() + 1.0, rect.bottom() - 1.0), + egui::pos2(rect.right() - 1.0, rect.bottom() + 1.0), ), 0.0, - p.bg, + p.surface, ); + painter.rect_filled( + egui::Rect::from_min_size(rect.min, vec2(rect.width(), 3.0)), + top, + p.accent, + ); + } else if resp.hovered() || close.hovered() { + painter.rect_filled(rect.shrink2(vec2(0.0, 2.0)), CornerRadius::same(8), p.hover); } + // The badge, as the sidebar's header draws it. + let badge = egui::Rect::from_center_size( + egui::pos2(rect.left() + PAD_L + BADGE / 2.0, rect.center().y + 1.0), + vec2(BADGE, BADGE), + ); + painter.rect_filled(badge, CornerRadius::same(5), p.accent); + let initial = tab + .title + .chars() + .next() + .map(|c| c.to_uppercase().next().unwrap_or(c)) + .unwrap_or('W'); + painter.text( + badge.center(), + egui::Align2::CENTER_CENTER, + initial, + theme::bold(11.0), + crate::schemes::on(p.accent), + ); let font = if here { theme::semibold(13.0) } else { theme::regular(13.0) }; - let text_w = rect.width() - 14.0 - CLOSE - 10.0; + let text_x = badge.right() + GAP; + let text_w = close_rect.left() - STATE_W - GAP - text_x; let mut job = egui::text::LayoutJob::single_section( tab.title.clone(), - egui::TextFormat::simple(font, if here { p.text } else { p.muted }), + egui::TextFormat::simple(font, p.text), ); job.wrap.max_width = text_w.max(10.0); job.wrap.max_rows = 1; @@ -365,10 +491,7 @@ fn one_tab( job.wrap.overflow_character = Some('…'); let galley = painter.layout_job(job); painter.galley( - egui::pos2( - rect.left() + 14.0, - rect.center().y - galley.size().y / 2.0 + 1.0, - ), + egui::pos2(text_x, rect.center().y - galley.size().y / 2.0 + 1.0), galley, p.text, ); @@ -380,7 +503,11 @@ fn one_tab( egui::Align2::CENTER_CENTER, icon::X, egui::FontId::proportional(12.0), - if close.hovered() { p.text } else { p.muted }, + if close.hovered() || here { + p.text + } else { + p.muted + }, ); } let resp = resp.on_hover_text(&tab.detail); diff --git a/crates/ledger-gui/tests/goldens/sidenav-1440x920.shapes b/crates/ledger-gui/tests/goldens/sidenav-1440x920.shapes index c5220a62..edf60281 100644 --- a/crates/ledger-gui/tests/goldens/sidenav-1440x920.shapes +++ b/crates/ledger-gui/tests/goldens/sidenav-1440x920.shapes @@ -1 +1 @@ -b4c03adfe9dc03e6 +fb22421d46ed2f8b diff --git a/crates/ledger-gui/tests/sidenav.rs b/crates/ledger-gui/tests/sidenav.rs index 76193ddb..5fb59ab6 100644 --- a/crates/ledger-gui/tests/sidenav.rs +++ b/crates/ledger-gui/tests/sidenav.rs @@ -24,6 +24,7 @@ use ledger_core::{AccountType, Currency, Money, Side}; use ledger_gui::books::Books; use ledger_gui::nav::{Route, Section}; use ledger_gui::owner::{Agent, Owner, RestorePlan}; +use ledger_gui::tabs::BAR_H; use ledger_gui::{App, Source, data}; use ledger_store::{DiskCheck, Store}; use rust_decimal::Decimal; @@ -372,7 +373,8 @@ fn grid(scale: f32) { for side in [Pane::Sidebar, Pane::Rail] { let mut h = f.harness(footer, Route::Projects, side.width(), 920.0, scale); for px in (300..=920).step_by(20) { - let pt = px as f32 / scale; + // The tab bar takes BAR_H points of the window; D-78. + let pt = px as f32 / scale + BAR_H; h.set_size(vec2(side.width(), pt)); h.run_steps(4); let tag = format!("{footer:?} {side:?} {px}px @{scale}"); @@ -413,7 +415,8 @@ fn no_link_is_ever_under_the_footer_at_scale_2() { fn at_1479x519_every_link_shows_unscrolled() { let f = Fixture::new(); for footer in FOOTERS { - let mut h = f.harness(footer, Route::Projects, 1479.0, 519.0, 1.0); + // The tab bar takes BAR_H points of the window; D-78. + let mut h = f.harness(footer, Route::Projects, 1479.0, 519.0 + BAR_H, 1.0); let (view, _, scrolls) = drawn(&h, Pane::Sidebar); assert!(!scrolls, "{footer:?}: the links scroll"); for s in Section::ALL { @@ -546,7 +549,8 @@ fn the_rail_at_519_shows_every_link_unscrolled() { let f = Fixture::new(); for footer in FOOTERS { for route in [Route::Projects, Route::Overview, Route::Journal] { - let h = f.harness(footer, route.clone(), 900.0, 519.0, 1.0); + // The tab bar takes BAR_H points of the window; D-78. + let h = f.harness(footer, route.clone(), 900.0, 519.0 + BAR_H, 1.0); let tag = format!("{footer:?} {route:?}"); let (view, _, scrolls) = drawn(&h, Pane::Rail); assert!(!scrolls, "{tag}: the rail's links scroll"); @@ -638,7 +642,9 @@ fn going_somewhere_scrolls_its_link_into_view() { #[test] fn a_tall_sidebar_is_unchanged() { let f = Fixture::new(); - let mut h = f.harness(Footer::Owners, Route::Overview, 1440.0, 920.0, 1.0); + // The tab bar takes BAR_H points of the window, and the sidebar is + // what is below it; D-78. + let mut h = f.harness(Footer::Owners, Route::Overview, 1440.0, 920.0 + BAR_H, 1.0); let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/goldens"); let shapes = sidebar_shapes(&h); let bless = std::env::var("SIDENAV_BLESS").is_ok(); @@ -664,7 +670,9 @@ fn a_tall_sidebar_is_unchanged() { let png = dir.join("sidenav-1440x920.png"); match h.render() { Ok(img) => { - let side = image::imageops::crop_imm(&img, 0, 0, 224, img.height()).to_image(); + let side = + image::imageops::crop_imm(&img, 0, BAR_H as u32, 224, img.height() - BAR_H as u32) + .to_image(); if bless { side.save(&png).unwrap(); } else { @@ -687,7 +695,8 @@ fn a_tall_sidebar_is_unchanged() { fn sidebar_shapes(h: &Harness<'_, App>) -> u64 { let mut hash: u64 = 0xcbf2_9ce4_8422_2325; for s in &h.output().shapes { - if s.clip_rect.max.x <= 224.5 { + // Below the tab bar (D-78): the shapes that are the sidebar's. + if s.clip_rect.max.x <= 224.5 && s.clip_rect.min.y >= BAR_H - 0.5 { for b in format!("{:?}", s.shape).bytes() { hash ^= b as u64; hash = hash.wrapping_mul(0x100_0000_01b3); diff --git a/crates/ledger-gui/tests/snapshots/tabs_empty_dark.png b/crates/ledger-gui/tests/snapshots/tabs_empty_dark.png index 004c87bb..4c86a06a 100644 Binary files a/crates/ledger-gui/tests/snapshots/tabs_empty_dark.png and b/crates/ledger-gui/tests/snapshots/tabs_empty_dark.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_empty_light.png b/crates/ledger-gui/tests/snapshots/tabs_empty_light.png index f49c7697..ff6b4c56 100644 Binary files a/crates/ledger-gui/tests/snapshots/tabs_empty_light.png and b/crates/ledger-gui/tests/snapshots/tabs_empty_light.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_many_dark.png b/crates/ledger-gui/tests/snapshots/tabs_many_dark.png index 51a13e0a..3c307258 100644 Binary files a/crates/ledger-gui/tests/snapshots/tabs_many_dark.png and b/crates/ledger-gui/tests/snapshots/tabs_many_dark.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_many_light.png b/crates/ledger-gui/tests/snapshots/tabs_many_light.png index 6fda7c5c..46b2bc50 100644 Binary files a/crates/ledger-gui/tests/snapshots/tabs_many_light.png and b/crates/ledger-gui/tests/snapshots/tabs_many_light.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_one_dark.png b/crates/ledger-gui/tests/snapshots/tabs_one_dark.png index 5fe413dd..a0aea9a6 100644 Binary files a/crates/ledger-gui/tests/snapshots/tabs_one_dark.png and b/crates/ledger-gui/tests/snapshots/tabs_one_dark.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_one_light.png b/crates/ledger-gui/tests/snapshots/tabs_one_light.png index 1e877cf2..31d20c41 100644 Binary files a/crates/ledger-gui/tests/snapshots/tabs_one_light.png and b/crates/ledger-gui/tests/snapshots/tabs_one_light.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_plus_dark.png b/crates/ledger-gui/tests/snapshots/tabs_plus_dark.png index e9df2309..d08f1703 100644 Binary files a/crates/ledger-gui/tests/snapshots/tabs_plus_dark.png and b/crates/ledger-gui/tests/snapshots/tabs_plus_dark.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_plus_light.png b/crates/ledger-gui/tests/snapshots/tabs_plus_light.png index 82901fed..7f13370d 100644 Binary files a/crates/ledger-gui/tests/snapshots/tabs_plus_light.png and b/crates/ledger-gui/tests/snapshots/tabs_plus_light.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_two_dark.png b/crates/ledger-gui/tests/snapshots/tabs_two_dark.png index 76934131..9b4ee3b2 100644 Binary files a/crates/ledger-gui/tests/snapshots/tabs_two_dark.png and b/crates/ledger-gui/tests/snapshots/tabs_two_dark.png differ diff --git a/crates/ledger-gui/tests/snapshots/tabs_two_light.png b/crates/ledger-gui/tests/snapshots/tabs_two_light.png index 4bf10e11..15b2e61a 100644 Binary files a/crates/ledger-gui/tests/snapshots/tabs_two_light.png and b/crates/ledger-gui/tests/snapshots/tabs_two_light.png differ diff --git a/crates/ledger-gui/tests/tabs.rs b/crates/ledger-gui/tests/tabs.rs index c438cb42..8ed14011 100644 --- a/crates/ledger-gui/tests/tabs.rs +++ b/crates/ledger-gui/tests/tabs.rs @@ -28,6 +28,12 @@ //! sizes and times as they were. //! 8. The tab bar and the empty state look as pictured //! (`tests/snapshots/`). +//! 9. The bar spans the whole window above the sidebar; its "+" is +//! right after the last tab, and at the right edge, whole, when the +//! tabs overflow. +//! 10. A company's name is remembered when it is loaded: the "+" list +//! shows it (the id alone for a company never opened), and so does a +//! tab whose books are not loaded yet. //! ``` use chrono::NaiveDate; @@ -625,7 +631,7 @@ fn closing_a_tab_releases_its_lock_its_threads_and_its_agent() { // Beta can be opened again: a new tab, a new lock. h.get_by_label("Open another company").click(); h.run_steps(3); - h.get_by_label("beta").click(); + h.get_by_label("Beta Co").click(); h.run_steps(3); assert_eq!(titles(&h).len(), 2); until(&mut h, "beta's lock is taken again", |_| { @@ -652,7 +658,11 @@ fn plus_lists_only_the_companies_not_open_and_none_opens_twice() { // Every one is open: the list says so. h.get_by_label("Open another company").click(); h.run_steps(3); - assert!(shows(&h, "Every company here is open."), "{:?}", texts(&h)); + assert!( + shows(&h, "Every company is already open."), + "{:?}", + texts(&h) + ); // Opening an open company by other means shows its tab, never a second. let ctx = h.ctx.clone(); let n = h.state_mut().open(&ctx, w.source("beta")); @@ -772,7 +782,7 @@ fn the_open_tabs_and_each_ones_page_and_period_are_kept_and_come_back() { close_tab(&mut h, "Alpha Co"); h.get_by_label("Open another company").click(); h.run_steps(3); - h.get_by_label("alpha").click(); + h.get_by_label("Alpha Co").click(); h.run_steps(3); let last = h.state().views().len() - 1; assert!(matches!( @@ -786,7 +796,7 @@ fn the_open_tabs_and_each_ones_page_and_period_are_kept_and_come_back() { // Closing the last tab keeps a list with nothing in it, and the next // start opens the data root's first. for _ in 0..3 { - let name = h.state().views()[0].title(); + let name = h.state().tab_title(0).unwrap(); close_tab(&mut h, &name); } assert!(h.state().views().is_empty()); @@ -827,7 +837,7 @@ fn closing_the_front_tab_shows_a_neighbour_and_the_last_leaves_an_empty_window() // The bar is still there, and "+" opens a company from the empty window. h.get_by_label("Open another company").click(); h.run_steps(3); - h.get_by_label("beta").click(); + h.get_by_label("Beta Co").click(); loaded(&mut h); assert_eq!(titles(&h), ["Beta Co"]); assert!(!shows(&h, "No company is open")); @@ -865,6 +875,181 @@ fn the_tab_in_front_is_marked_by_more_than_colour() { h.get_by_role_and_label(Role::Button, "Close Beta Co"); } +// ---- 9: the bar's place -------------------------------------------------------- + +/// The fill of the bar: a rectangle from the window's corner, as wide as +/// the window and as high as the bar. +fn bar_rect(h: &Harness<'_, App>, size: egui::Vec2) -> Option { + fn walk(s: &egui::Shape, size: egui::Vec2, out: &mut Option) { + match s { + egui::Shape::Rect(r) + if r.rect.min.x.abs() < 0.5 + && r.rect.min.y.abs() < 0.5 + && (r.rect.height() - ledger_gui::tabs::BAR_H).abs() < 0.5 + && r.rect.width() >= size.x - 0.5 => + { + *out = Some(r.rect) + } + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, size, out)), + _ => {} + } + } + let mut found = None; + for c in &h.output().shapes { + walk(&c.shape, size, &mut found); + } + found +} + +#[test] +fn the_bar_spans_the_window_above_the_sidebar() { + let size = egui::vec2(1280.0, 600.0); + let w = World::new(); + let h = shown(&w, &["Wanderland Labs LLC", "Fernhill Studio"], false, size); + let bar = bar_rect(&h, size).expect("a bar the window's width, at its top"); + assert!(bar.max.x >= size.x - 0.5, "{bar:?}"); + // Every tab, and its close control, is inside the bar... + for name in ["Wanderland Labs LLC", "Fernhill Studio"] { + let tab = h + .get_by_role_and_label(egui::accesskit::Role::Button, name) + .rect(); + assert!(bar.contains_rect(tab), "{name}: {tab:?} is in {bar:?}"); + } + // ...and the first is over the sidebar's column, whose links, header + // and status all lie below the bar. + let first = h + .get_by_role_and_label(egui::accesskit::Role::Button, "Wanderland Labs LLC") + .rect(); + assert!(first.left() < 224.0, "the first tab is above the sidebar"); + for link in ["Overview", "Journal"] { + let r = h + .query_all_by_role_and_label(egui::accesskit::Role::Button, link) + .map(|n| n.rect()) + .min_by(|a, b| a.left().total_cmp(&b.left())) + .unwrap(); + assert!(r.top() >= bar.bottom() - 0.5, "{link} {r:?} under {bar:?}"); + } + // Nothing but the bar is drawn across the top strip of the sidebar's + // column: the sidebar's own panel starts where the bar ends. + let sidebar_top = h + .output() + .shapes + .iter() + .filter(|s| s.clip_rect.max.x <= 224.5 && s.clip_rect.min.y > 1.0) + .map(|s| s.clip_rect.min.y) + .fold(f32::MAX, f32::min); + assert!( + sidebar_top >= bar.bottom() - 0.5, + "the sidebar starts at {sidebar_top}, below the bar's {}", + bar.bottom() + ); +} + +#[test] +fn the_plus_follows_the_last_tab_and_stays_whole_when_the_tabs_overflow() { + let size = egui::vec2(1100.0, 200.0); + let rect = |h: &Harness<'_, App>, label: &str| { + h.get_by_role_and_label(egui::accesskit::Role::Button, label) + .rect() + }; + // Few tabs: the "+" is right after the last, not at the window's edge. + let w = World::new(); + let h = shown(&w, &["Wanderland Labs LLC", "Fernhill Studio"], false, size); + let last = rect(&h, "Fernhill Studio"); + let plus = rect(&h, "Open another company"); + assert!( + plus.left() >= last.right() && plus.left() - last.right() < 16.0, + "the + at {plus:?} is not just after the last tab {last:?}" + ); + assert!(plus.right() < size.x / 2.0, "the + sits at the far right"); + // Many: the "+" is at the right edge, whole; the tabs scroll behind it. + let names: Vec = (0..9).map(|i| format!("Company number {i}")).collect(); + let refs: Vec<&str> = names.iter().map(String::as_str).collect(); + let w = World::new(); + let mut h = shown(&w, &refs, false, size); + h.state_mut().activate(8); + h.run_steps(6); + let plus = rect(&h, "Open another company"); + assert!( + plus.right() <= size.x && plus.right() > size.x - 24.0, + "the + at {plus:?} is not at the right edge" + ); + assert!( + plus.left() >= 0.0 && plus.width() >= 20.0, + "{plus:?} is whole" + ); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Later tabs"); + // The tab in front was scrolled into view, left of the "+". + let front = rect(&h, "Company number 8"); + assert!( + front.right() <= plus.left(), + "{front:?} under the + {plus:?}" + ); +} + +// ---- 10: names remembered --------------------------------------------------------- + +#[test] +fn a_name_is_remembered_and_shown_in_the_plus_list_and_on_a_loading_tab() { + let (w, _, _, _) = three(); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha,beta")]); + loaded(&mut h); + assert_eq!(h.state().remembered_name("beta"), Some("Beta Co")); + assert_eq!(h.state().remembered_name("gamma"), None); + // Beta closed: "+" offers it by name with its id beside, and gamma, + // never opened here, by its id alone. + close_tab(&mut h, "Beta Co"); + h.get_by_label("Open another company").click(); + h.run_steps(3); + assert!(shows(&h, "Open a company"), "{:?}", texts(&h)); + assert!(shows(&h, "Beta Co") && texts(&h).contains(&"beta".to_string())); + assert!(texts(&h).contains(&"gamma".to_string()), "{:?}", texts(&h)); + assert!(!shows(&h, "Gamma Co"), "gamma's name was never read"); + h.get_by_label("Beta Co").click(); + loaded(&mut h); + // Kept with the app's other state... + let mut kept = Prefs::default(); + eframe::App::save(h.state_mut(), &mut kept); + assert_eq!( + kept.0.get("company.beta.name").map(String::as_str), + Some("Beta Co") + ); + // ...and a window started from it titles a tab whose books are not + // loaded yet by name; a company with no name known by its id. + let ctx = egui::Context::default(); + kept.0.remove("company.alpha.name"); + kept.0.insert("open_companies".into(), "alpha,beta".into()); + let root = w.root.clone(); + let fallback = w.source("alpha"); + let app = App::start_with( + &ctx, + &|k| kept.0.get(k).cloned(), + Start::Restore { root, fallback }, + ); + assert_eq!(app.tab_title(0).as_deref(), Some("alpha"), "no name known"); + assert_eq!( + app.tab_title(1).as_deref(), + Some("Beta Co"), + "the name kept" + ); +} + +#[test] +fn the_plus_list_says_so_when_every_company_is_open() { + let w = World::new(); + w.company("alpha", "Alpha Co", 1_000_000, 100); + let mut h = start_with_prefs(&w, &[("open_companies", "alpha")]); + loaded(&mut h); + h.get_by_label("Open another company").click(); + h.run_steps(3); + assert!( + shows(&h, "Every company is already open."), + "{:?}", + texts(&h) + ); + assert!(!shows(&h, "Open a company"), "no heading over nothing"); +} + // ---- 7: read-only, in a tab that is not in front ----------------------------- type Tree = BTreeMap, u64, SystemTime)>; @@ -1200,5 +1385,34 @@ fn pictures() { close_tab(&mut h, "Beta Co"); h.run_steps(4); save(&mut h, &format!("empty-state-{mode}")); + // Eight companies open: the tabs scroll, the "+" stays at the edge. + let names: Vec = [ + "Wanderland Labs LLC", + "Fernhill Studio", + "Northgate Holdings Incorporated", + "Oak & Ash Carpentry", + "Harbor Lane Books", + "Quill and Compass", + "Mossy Rock Farm", + "Lantern Works", + ] + .map(String::from) + .to_vec(); + let refs: Vec<&str> = names.iter().map(String::as_str).collect(); + let w = World::new(); + let mut h = shown(&w, &refs, dark, egui::vec2(1100.0, 600.0)); + h.state_mut().activate(6); + h.run_steps(6); + save(&mut h, &format!("eight-tabs-overflow-{mode}")); + // The smallest window the viewer allows, two tabs. + let w = World::new(); + let mut h = shown( + &w, + &["Wanderland Labs LLC", "Fernhill Studio"], + dark, + egui::vec2(360.0, 400.0 + ledger_gui::tabs::BAR_H), + ); + h.run_steps(4); + save(&mut h, &format!("smallest-window-two-tabs-{mode}")); } }